From 073cc188efe9abb4c010cf674e34e2cf46ef1c52 Mon Sep 17 00:00:00 2001 From: Guo Ruijing Date: Mon, 31 Jul 2017 08:47:35 +0000 Subject: [PATCH] [POLICY-73] replace openecomp for policy-engine Change-Id: I54072f6bcd388c0e05562614ee89b4ae7ad67004 Signed-off-by: Guo Ruijing Signed-off-by: Pamela Dragosh --- BRMSGateway/config.properties | 8 +- BRMSGateway/config/policyLogger.properties | 2 +- BRMSGateway/policyLogger.properties | 2 +- BRMSGateway/pom.xml | 10 +- .../org/onap/policy/brmsInterface/BRMSGateway.java | 88 + .../org/onap/policy/brmsInterface/BRMSHandler.java | 184 ++ .../org/onap/policy/brmsInterface/BRMSPush.java | 1107 ++++++++ .../onap/policy/brmsInterface/ControllerPOJO.java | 52 + .../policy/brmsInterface/NotificationPOJO.java | 52 + .../policy/brmsInterface/jpa/BRMSGroupInfo.java | 75 + .../policy/brmsInterface/jpa/BRMSPolicyInfo.java | 56 + .../policy/brmsInterface/jpa/DependencyInfo.java | 38 + .../policy/brmsInterface/BRMSGateway.java | 88 - .../policy/brmsInterface/BRMSHandler.java | 184 -- .../openecomp/policy/brmsInterface/BRMSPush.java | 1107 -------- .../policy/brmsInterface/ControllerPOJO.java | 52 - .../policy/brmsInterface/NotificationPOJO.java | 52 - .../policy/brmsInterface/jpa/BRMSGroupInfo.java | 75 - .../policy/brmsInterface/jpa/BRMSPolicyInfo.java | 56 - .../policy/brmsInterface/jpa/DependencyInfo.java | 38 - .../main/resources/META-INF/persistenceBRMS.xml | 4 +- BRMSGateway/src/main/resources/log4j.properties | 2 +- BRMSGateway/src/main/resources/logback.xml | 4 +- ECOMP-ASDC/pom.xml | 37 - .../java/org/openecomp/policy/asdc/Resource.java | 159 -- .../openecomp/policy/asdc/ResourceInstance.java | 157 -- .../org/openecomp/policy/asdc/ResourceType.java | 40 - .../java/org/openecomp/policy/asdc/Service.java | 140 - .../org/openecomp/policy/asdc/ServiceInstance.java | 177 -- ECOMP-ControlloopPolicy/pom.xml | 62 - .../controlloop/compiler/CompilerException.java | 47 - .../controlloop/compiler/ControlLoopCompiler.java | 617 ----- .../compiler/ControlLoopCompilerCallback.java | 29 - .../guard/compiler/ControlLoopGuardCompiler.java | 133 - .../policy/controlloop/policy/ControlLoop.java | 189 -- .../controlloop/policy/ControlLoopPolicy.java | 83 - .../policy/controlloop/policy/FinalResult.java | 93 - .../policy/OperationsAccumulateParams.java | 99 - .../policy/controlloop/policy/Policy.java | 353 --- .../policy/controlloop/policy/PolicyResult.java | 82 - .../policy/controlloop/policy/Target.java | 106 - .../policy/controlloop/policy/TargetType.java | 39 - .../policy/builder/BuilderException.java | 31 - .../policy/builder/ControlLoopPolicyBuilder.java | 287 -- .../policy/controlloop/policy/builder/Message.java | 29 - .../controlloop/policy/builder/MessageLevel.java | 29 - .../policy/controlloop/policy/builder/Results.java | 33 - .../builder/impl/ControlLoopPolicyBuilderImpl.java | 496 ---- .../policy/builder/impl/MessageImpl.java | 46 - .../policy/builder/impl/ResultsImpl.java | 55 - .../controlloop/policy/guard/Constraint.java | 171 -- .../controlloop/policy/guard/ControlLoopGuard.java | 92 - .../policy/guard/ControlLoopParameter.java | 89 - .../policy/controlloop/policy/guard/Guard.java | 67 - .../controlloop/policy/guard/GuardPolicy.java | 181 -- .../controlloop/policy/guard/MatchParameters.java | 142 - .../guard/builder/ControlLoopGuardBuilder.java | 130 - .../builder/impl/ControlLoopGuardBuilderImpl.java | 244 -- .../compiler/ControlLoopCompilerTest.java | 80 - .../compiler/ControlLoopGuardCompilerTest.java | 101 - .../policy/ControlLoopPolicyBuilderTest.java | 516 ---- .../controlloop/policy/ControlLoopPolicyTest.java | 101 - .../policy/guard/ControlLoopGuardBuilderTest.java | 202 -- .../policy/guard/ControlLoopGuardTest.java | 93 - .../resource-59a2ee3fB58045feB5a1-template.yml | 1698 ------------ .../resource-Eace933104d443b496b8-template.yml | 2525 ------------------ .../service-57e66ea70ed645c7970f-template.yml | 677 ----- .../service-D473899264974dca9db9-template.yml | 677 ----- ECOMP-PAP-REST/autopush.properties | 22 - ECOMP-PAP-REST/dictionaryItemsAPI.json | 52 - ECOMP-PAP-REST/pip.properties | 15 - ECOMP-PAP-REST/policyLogger.properties | 44 - ECOMP-PAP-REST/policyelk.properties | 30 - ECOMP-PAP-REST/pom.xml | 344 --- .../policy/pap/xacml/rest/PAPRestConfig.java | 145 - .../openecomp/policy/pap/xacml/rest/WebConfig.java | 43 - .../policy/pap/xacml/rest/XACMLPapServlet.java | 2617 ------------------ .../policy/pap/xacml/rest/adapters/GridData.java | 62 - .../pap/xacml/rest/adapters/package-info.java | 21 - .../pap/xacml/rest/components/ActionPolicy.java | 529 ---- .../pap/xacml/rest/components/AutoPushPolicy.java | 100 - .../xacml/rest/components/ClosedLoopPolicy.java | 412 --- .../pap/xacml/rest/components/ConfigPolicy.java | 564 ---- .../rest/components/CreateBRMSRuleTemplate.java | 73 - .../rest/components/CreateBrmsParamPolicy.java | 692 ----- .../xacml/rest/components/CreateBrmsRawPolicy.java | 489 ---- .../CreateClosedLoopPerformanceMetrics.java | 412 --- .../components/CreateNewMicroServiceModel.java | 248 -- .../pap/xacml/rest/components/DecisionPolicy.java | 793 ------ .../rest/components/FirewallConfigPolicy.java | 1305 --------- .../rest/components/MicroServiceConfigPolicy.java | 555 ---- .../policy/pap/xacml/rest/components/Policy.java | 416 --- .../pap/xacml/rest/components/PolicyDBDao.java | 2798 -------------------- .../rest/components/PolicyDBDaoTransaction.java | 188 -- .../xacml/rest/components/SafePolicyBuilder.java | 86 - .../pap/xacml/rest/components/package-info.java | 21 - .../ActionPolicyDictionaryController.java | 261 -- .../rest/controller/BRMSDictionaryController.java | 552 ---- .../controller/ClosedLoopDictionaryController.java | 1031 -------- .../DecisionPolicyDictionaryController.java | 426 --- .../DescriptiveDictionaryController.java | 246 -- .../rest/controller/DictionaryController.java | 447 ---- .../controller/DictionaryImportController.java | 539 ---- .../controller/EnforcerDictionaryController.java | 139 - .../controller/FirewallDictionaryController.java | 2279 ---------------- .../MicroServiceDictionaryController.java | 1051 -------- .../PolicyScopeDictionaryController.java | 927 ------- .../rest/controller/PushPolicyController.java | 229 -- .../rest/controller/SafePolicyController.java | 385 --- .../pap/xacml/rest/controller/package-info.java | 22 - .../pap/xacml/rest/daoimpl/CommonClassDaoImpl.java | 443 ---- .../rest/elk/client/ElasticSearchPolicyUpdate.java | 311 --- .../pap/xacml/rest/elk/client/ElkConnector.java | 101 - .../xacml/rest/elk/client/ElkConnectorImpl.java | 418 --- .../policy/pap/xacml/rest/elk/client/Pair.java | 33 - .../xacml/rest/elk/client/PolicyElasticData.java | 623 ----- .../elk/client/PolicyElasticSearchController.java | 563 ---- .../pap/xacml/rest/elk/client/PolicyLocator.java | 51 - .../pap/xacml/rest/handler/APIRequestHandler.java | 96 - .../pap/xacml/rest/handler/DeleteHandler.java | 477 ---- .../pap/xacml/rest/handler/DictionaryHandler.java | 63 - .../xacml/rest/handler/DictionaryHandlerImpl.java | 323 --- .../pap/xacml/rest/handler/PushPolicyHandler.java | 123 - .../pap/xacml/rest/handler/SavePolicyHandler.java | 157 -- .../pap/xacml/rest/model/PDPPolicyContainer.java | 348 --- .../pap/xacml/rest/model/RemoveGroupPolicy.java | 102 - .../policy/pap/xacml/rest/model/package-info.java | 20 - .../rest/policycontroller/PolicyCreation.java | 550 ---- .../xacml/rest/policycontroller/package-info.java | 20 - .../pap/xacml/rest/service/DictionaryService.java | 995 ------- .../pap/xacml/rest/service/ImportService.java | 157 -- .../pap/xacml/rest/service/MetricService.java | 93 - .../xacml/rest/util/AbstractPolicyCreation.java | 104 - .../policy/pap/xacml/rest/util/JPAUtils.java | 239 -- .../policy/pap/xacml/rest/util/JsonMessage.java | 67 - .../pap/xacml/rest/util/PolicyContainer.java | 121 - .../rest/util/PolicyItemSetChangeNotifier.java | 96 - .../pap/xacml/restAuth/AuthenticationService.java | 63 - .../policy/pap/xacml/restAuth/CheckPDP.java | 181 -- .../xacml/restAuth/PAPAuthenticationFilter.java | 130 - .../resources/Decision_GuardBLPolicyTemplate.xml | 111 - .../resources/Decision_GuardPolicyTemplate.xml | 107 - .../main/resources/META-INF/generatedCreate.ddl | 119 - .../src/main/resources/META-INF/generatedDrop.ddl | 118 - .../src/main/resources/META-INF/persistence.xml | 201 -- ECOMP-PAP-REST/src/main/resources/log4j.properties | 71 - ECOMP-PAP-REST/src/main/resources/logback.xml | 254 -- ECOMP-PAP-REST/src/main/resources/spring.xml | 46 - .../policy/pap/ia/DbAuditCompareEntriesTest.java | 450 ---- .../pap/xacml/rest/components/PolicyDBDaoTest.java | 636 ----- .../rest/controller/DictionaryControllerTest.java | 319 --- .../MicroServiceDictionaryControllerTest.java | 693 ----- .../pap/xacml/rest/jpa/PolicyEntityTest.java | 803 ------ ECOMP-PAP-REST/test.properties | 22 - ECOMP-PAP-REST/xacml.pap.properties | 165 -- ECOMP-PAP-REST/xacml.pap.test.properties | 145 - ECOMP-PDP-REST/config/policyLogger.properties | 44 - ECOMP-PDP-REST/policyLogger.properties | 44 - ECOMP-PDP-REST/pom.xml | 223 -- .../openecomp/policy/pdp/rest/PapUrlResolver.java | 377 --- .../openecomp/policy/pdp/rest/XACMLPdpLoader.java | 645 ----- .../policy/pdp/rest/XACMLPdpRegisterThread.java | 285 -- .../openecomp/policy/pdp/rest/XACMLPdpServlet.java | 1266 --------- .../rest/api/controller/PolicyEngineServices.java | 658 ----- .../api/models/ConfigFirewallPolicyAPIRequest.java | 80 - .../pdp/rest/api/models/ConfigNameRequest.java | 39 - .../rest/api/models/ConfigPolicyAPIRequest.java | 188 -- .../policy/pdp/rest/api/models/PDPResponse.java | 159 -- .../policy/pdp/rest/api/models/PolicyConfig.java | 95 - .../pdp/rest/api/services/ActionPolicyService.java | 105 - .../rest/api/services/BRMSParamPolicyService.java | 96 - .../rest/api/services/BRMSRawPolicyService.java | 106 - .../api/services/ClosedLoopFaultPolicyService.java | 121 - .../api/services/ClosedLoopPMPolicyService.java | 122 - .../pdp/rest/api/services/ConfigPolicyService.java | 136 - .../services/CreateUpdateConfigPolicyService.java | 118 - .../services/CreateUpdateDictionaryService.java | 153 -- .../CreateUpdateFirewallPolicyService.java | 92 - .../api/services/CreateUpdatePolicyService.java | 35 - .../services/CreateUpdatePolicyServiceImpl.java | 293 -- .../rest/api/services/DecisionPolicyService.java | 100 - .../pdp/rest/api/services/DeletePolicyService.java | 258 -- .../rest/api/services/FirewallPolicyService.java | 113 - .../pdp/rest/api/services/GetConfigService.java | 318 --- .../pdp/rest/api/services/GetDecisionService.java | 189 -- .../rest/api/services/GetDictionaryService.java | 276 -- .../pdp/rest/api/services/GetMetricsService.java | 157 -- .../pdp/rest/api/services/ListConfigService.java | 64 - .../api/services/MicroServicesPolicyService.java | 135 - .../pdp/rest/api/services/NotificationService.java | 314 --- .../policy/pdp/rest/api/services/PAPServices.java | 656 ----- .../policy/pdp/rest/api/services/PDPServices.java | 439 --- .../api/services/PolicyEngineImportService.java | 186 -- .../pdp/rest/api/services/PushPolicyService.java | 236 -- .../pdp/rest/api/services/SendEventService.java | 170 -- .../policy/pdp/rest/api/utils/PolicyApiUtils.java | 72 - .../policy/pdp/rest/config/PDPApiAuth.java | 189 -- .../policy/pdp/rest/config/PDPRestConfig.java | 77 - .../policy/pdp/rest/config/PDPRestInitializer.java | 51 - .../pdp/rest/impl/XACMLPdpPIPFinderFactory.java | 88 - .../pdp/rest/impl/XACMLPdpPolicyFinderFactory.java | 208 -- .../policy/pdp/rest/jmx/PdpRestMBeanListener.java | 85 - .../policy/pdp/rest/jmx/PdpRestMonitor.java | 162 -- .../policy/pdp/rest/jmx/PdpRestMonitorMBean.java | 40 - .../ManualNotificationUpdateThread.java | 229 -- .../pdp/rest/notifications/Notification.java | 62 - .../rest/notifications/NotificationController.java | 415 --- .../pdp/rest/notifications/NotificationServer.java | 224 -- .../policy/pdp/rest/notifications/Removed.java | 54 - .../policy/pdp/rest/notifications/Updated.java | 74 - .../pdp/rest/notifications/package-info.java | 28 - .../pdp/rest/restAuth/AuthenticationService.java | 62 - .../pdp/rest/restAuth/PDPAuthenticationFilter.java | 117 - ECOMP-PDP-REST/src/main/resources/log4j.properties | 71 - ECOMP-PDP-REST/src/main/resources/logback.xml | 253 -- .../policy/pdp/rest/PapUrlResolverTest.java | 224 -- .../policy/pdp/rest/XACMLPdpServletTest.java | 364 --- .../pdp/rest/api/services/PDPServicesTest.java | 194 -- .../pdp/rest/api/test/NotificationAPITest.java | 87 - .../rest/api/test/PolicyEngineServicesTest.java | 832 ------ .../policy/pdp/rest/api/test/getConfigTest.java | 70 - .../pdp/rest/api/test/getDictionaryTest.java | 231 -- .../policy/pdp/rest/auth/test/FilterTests.java | 199 -- .../src/test/resources/fail.xacml.pdp.properties | 171 -- .../src/test/resources/pass.xacml.pdp.properties | 171 -- ECOMP-PDP-REST/src/test/resources/test.drl | 1121 -------- ECOMP-PDP-REST/xacml.pdp.properties | 172 -- ECOMP-PDP/config_testing/test_PolicyEngine.xml | 595 ----- ECOMP-PDP/config_testing/xacml.pip.properties | 19 - ECOMP-PDP/config_testing/xacml.policy.properties | 23 - ECOMP-PDP/logging.properties | 29 - ECOMP-PDP/policyLogger.properties | 44 - ECOMP-PDP/pom.xml | 88 - .../openecomp/policy/xacml/action/FindAction.java | 356 --- .../policy/xacml/action/package-info.java | 30 - .../custom/EcompFunctionDefinitionFactory.java | 88 - .../openecomp/policy/xacml/pdp/ECOMPPDPEngine.java | 60 - .../policy/xacml/pdp/ECOMPPDPEngineFactory.java | 54 - .../FunctionDefinitionCustomRegexpMatch.java | 130 - .../policy/xacml/pdp/std/functions/PolicyList.java | 49 - .../FunctionDefinitionAccessPermittedTest.java | 521 ---- .../pdp/test/FunctionDefinitionArithmeticTest.java | 717 ----- .../pdp/test/FunctionDefinitionBagIsInTest.java | 221 -- .../test/FunctionDefinitionBagOneAndOnlyTest.java | 224 -- .../pdp/test/FunctionDefinitionBagSizeTest.java | 158 -- .../policy/pdp/test/FunctionDefinitionBagTest.java | 547 ---- .../pdp/test/FunctionDefinitionBaseTest.java | 131 - .../pdp/test/FunctionDefinitionComparisonTest.java | 1366 ---------- .../FunctionDefinitionDateTimeArithmeticTest.java | 1602 ----------- .../pdp/test/FunctionDefinitionEqualityTest.java | 1192 --------- .../test/FunctionDefinitionHigherOrderBagTest.java | 2193 --------------- .../FunctionDefinitionHomogeneousSimpleTest.java | 151 -- .../pdp/test/FunctionDefinitionLogicalTest.java | 422 --- ...FunctionDefinitionNumberTypeConversionTest.java | 119 - .../test/FunctionDefinitionRegexpMatchTest.java | 511 ---- .../policy/pdp/test/FunctionDefinitionSetTest.java | 1903 ------------- .../test/FunctionDefinitionSpecialMatchTest.java | 487 ---- .../FunctionDefinitionStringConversionTest.java | 2504 ------------------ ...unctionDefinitionStringEqualIgnoreCaseTest.java | 129 - .../FunctionDefinitionStringFunctionsTest.java | 1497 ----------- .../FunctionDefinitionStringNormalizeTest.java | 118 - ...FunctionDefinitionURIStringConcatenateTest.java | 185 -- .../pdp/test/FunctionDefinitionXPathTest.java | 1127 -------- .../org/openecomp/policy/pdp/test/PDPTest.java | 36 - .../org/openecomp/policy/pdp/test/TestRunner.java | 46 - .../policy/pdp/test/conformance/Conformance.java | 634 ----- .../pdp/test/conformance/ConformancePIPEngine.java | 242 -- .../test/conformance/ConformanceRepository.java | 127 - .../test/conformance/ConformanceScopeResolver.java | 121 - .../pdp/test/conformance/ConformanceTest.java | 104 - .../test/conformance/ConformanceTestEngine.java | 219 -- .../test/conformance/ConformanceTestResult.java | 122 - .../pdp/test/conformance/ConformanceTestSet.java | 180 -- .../pdp/test/conformance/ResponseMatchResult.java | 137 - .../pdp/test/conformance/ResultMatchResult.java | 136 - .../pdp/test/custom/CustomDataTypeFactory.java | 88 - .../custom/CustomFunctionDefinitionFactory.java | 90 - .../policy/pdp/test/custom/DataTypePrivateKey.java | 54 - .../policy/pdp/test/custom/DataTypePublicKey.java | 54 - .../pdp/test/custom/FunctionDefinitionDecrypt.java | 162 -- .../openecomp/policy/pdp/test/custom/TestBase.java | 1082 -------- .../policy/pdp/test/custom/TestCustom.java | 392 --- ECOMP-PDP/src/test/resources/CSVPolicy.xml | 205 -- ECOMP-PDP/src/test/resources/log4j.properties | 42 - ECOMP-PDP/src/test/resources/logback.xml | 253 -- ECOMP-PDP/src/test/resources/logging.properties | 32 - ECOMP-PDP/src/test/resources/xacml.pip.properties | 23 - .../src/test/resources/xacml.policy.properties | 25 - ECOMP-PDP/testclient.properties | 21 - ECOMP-PDP/testpdp.properties | 21 - ECOMP-PDP/xacml.pap.properties | 107 - ECOMP-PDP/xacml.pdp.properties | 86 - ECOMP-PDP/xacml.properties | 46 - ECOMP-REST/policyLogger.properties | 44 - ECOMP-REST/pom.xml | 114 - .../java/org/openecomp/policy/rest/XACMLRest.java | 216 -- .../openecomp/policy/rest/XACMLRestProperties.java | 456 ---- .../policy/rest/XacmlAdminAuthorization.java | 220 -- .../policy/rest/adapter/AddressGroupJson.java | 83 - .../openecomp/policy/rest/adapter/AddressJson.java | 52 - .../policy/rest/adapter/AddressMembers.java | 46 - .../policy/rest/adapter/AutoPushTabAdapter.java | 42 - .../policy/rest/adapter/ClosedLoopFaultBody.java | 280 -- .../ClosedLoopFaultTriggerUISignatures.java | 44 - .../policy/rest/adapter/ClosedLoopPMBody.java | 133 - .../rest/adapter/ClosedLoopPerformanceMetrics.java | 36 - .../policy/rest/adapter/ClosedLoopPolicy.java | 61 - .../rest/adapter/ClosedLoopPolicyConditions.java | 39 - .../rest/adapter/ClosedLoopPolicyStatus.java | 41 - .../policy/rest/adapter/ClosedLoopSignatures.java | 52 - .../policy/rest/adapter/DeletePolicyCondition.java | 38 - .../policy/rest/adapter/DeployNowJson.java | 36 - .../openecomp/policy/rest/adapter/GridData.java | 54 - .../org/openecomp/policy/rest/adapter/IdMap.java | 42 - .../policy/rest/adapter/PolicyExportAdapter.java | 36 - .../policy/rest/adapter/PolicyRestAdapter.java | 896 ------- .../policy/rest/adapter/PrefixIPList.java | 72 - .../policy/rest/adapter/RainyDayParams.java | 100 - .../policy/rest/adapter/ServiceGroupJson.java | 83 - .../policy/rest/adapter/ServiceListJson.java | 111 - .../policy/rest/adapter/ServiceMembers.java | 48 - .../policy/rest/adapter/ServicesJson.java | 44 - .../openecomp/policy/rest/adapter/TagDefines.java | 41 - .../org/openecomp/policy/rest/adapter/Tags.java | 59 - .../org/openecomp/policy/rest/adapter/Term.java | 201 -- .../policy/rest/adapter/TermCollector.java | 145 - .../policy/rest/adapter/VendorSpecificData.java | 38 - .../openecomp/policy/rest/adapter/YAMLParams.java | 97 - .../policy/rest/adapter/package-info.java | 20 - .../openecomp/policy/rest/dao/CommonClassDao.java | 57 - .../openecomp/policy/rest/dao/package-info.java | 21 - .../policy/rest/jpa/ActionBodyEntity.java | 195 -- .../org/openecomp/policy/rest/jpa/ActionList.java | 103 - .../policy/rest/jpa/ActionPolicyDict.java | 211 -- .../openecomp/policy/rest/jpa/AddressGroup.java | 114 - .../org/openecomp/policy/rest/jpa/Attribute.java | 363 --- .../policy/rest/jpa/AttributeAssignment.java | 93 - .../openecomp/policy/rest/jpa/BRMSController.java | 154 -- .../openecomp/policy/rest/jpa/BRMSDependency.java | 153 -- .../policy/rest/jpa/BRMSParamTemplate.java | 142 - .../org/openecomp/policy/rest/jpa/Category.java | 218 -- .../policy/rest/jpa/ClosedLoopD2Services.java | 175 -- .../openecomp/policy/rest/jpa/ClosedLoopSite.java | 177 -- .../org/openecomp/policy/rest/jpa/ClosedLoops.java | 99 - .../policy/rest/jpa/ConfigurationDataEntity.java | 224 -- .../openecomp/policy/rest/jpa/ConstraintType.java | 121 - .../openecomp/policy/rest/jpa/ConstraintValue.java | 116 - .../org/openecomp/policy/rest/jpa/DCAEUsers.java | 102 - .../org/openecomp/policy/rest/jpa/DCAEuuid.java | 102 - .../policy/rest/jpa/DatabaseLockEntity.java | 47 - .../org/openecomp/policy/rest/jpa/Datatype.java | 244 -- .../policy/rest/jpa/DecisionSettings.java | 235 -- .../policy/rest/jpa/DescriptiveScope.java | 181 -- .../org/openecomp/policy/rest/jpa/EcompName.java | 167 -- .../openecomp/policy/rest/jpa/EnforcingType.java | 96 - .../java/org/openecomp/policy/rest/jpa/FWTag.java | 180 -- .../org/openecomp/policy/rest/jpa/FWTagPicker.java | 189 -- .../policy/rest/jpa/FirewallDictionaryList.java | 164 -- .../policy/rest/jpa/FunctionArgument.java | 122 - .../policy/rest/jpa/FunctionDefinition.java | 219 -- .../policy/rest/jpa/GlobalRoleSettings.java | 93 - .../org/openecomp/policy/rest/jpa/GroupEntity.java | 270 -- .../policy/rest/jpa/GroupPolicyScopeList.java | 111 - .../policy/rest/jpa/GroupServiceList.java | 104 - .../policy/rest/jpa/MicroServiceAttribute.java | 109 - .../policy/rest/jpa/MicroServiceConfigName.java | 102 - .../policy/rest/jpa/MicroServiceLocation.java | 102 - .../policy/rest/jpa/MicroServiceModels.java | 189 -- .../org/openecomp/policy/rest/jpa/Obadvice.java | 227 -- .../policy/rest/jpa/ObadviceExpression.java | 123 - .../org/openecomp/policy/rest/jpa/PEPOptions.java | 183 -- .../openecomp/policy/rest/jpa/PIPConfigParam.java | 147 - .../policy/rest/jpa/PIPConfiguration.java | 537 ---- .../org/openecomp/policy/rest/jpa/PIPResolver.java | 365 --- .../policy/rest/jpa/PIPResolverParam.java | 147 - .../org/openecomp/policy/rest/jpa/PIPType.java | 131 - .../org/openecomp/policy/rest/jpa/PdpEntity.java | 241 -- .../policy/rest/jpa/PolicyAlgorithms.java | 116 - .../policy/rest/jpa/PolicyDBDaoEntity.java | 150 -- .../policy/rest/jpa/PolicyEditorScopes.java | 159 -- .../openecomp/policy/rest/jpa/PolicyEntity.java | 308 --- .../policy/rest/jpa/PolicyGroupEntity.java | 60 - .../policy/rest/jpa/PolicyManagement.java | 162 -- .../org/openecomp/policy/rest/jpa/PolicyRoles.java | 102 - .../policy/rest/jpa/PolicyScopeClosedLoop.java | 100 - .../policy/rest/jpa/PolicyScopeResource.java | 100 - .../policy/rest/jpa/PolicyScopeService.java | 100 - .../openecomp/policy/rest/jpa/PolicyScopeType.java | 100 - .../org/openecomp/policy/rest/jpa/PolicyScore.java | 104 - .../openecomp/policy/rest/jpa/PolicyVersion.java | 183 -- .../org/openecomp/policy/rest/jpa/PortList.java | 104 - .../org/openecomp/policy/rest/jpa/PrefixList.java | 114 - .../openecomp/policy/rest/jpa/ProtocolList.java | 105 - .../policy/rest/jpa/RainyDayTreatments.java | 118 - .../policy/rest/jpa/RemoteCatalogValues.java | 102 - .../org/openecomp/policy/rest/jpa/RiskType.java | 172 -- .../openecomp/policy/rest/jpa/RuleAlgorithms.java | 125 - .../policy/rest/jpa/SafePolicyWarning.java | 109 - .../openecomp/policy/rest/jpa/SecurityZone.java | 101 - .../org/openecomp/policy/rest/jpa/ServiceList.java | 154 -- .../org/openecomp/policy/rest/jpa/SystemLogDB.java | 163 -- .../org/openecomp/policy/rest/jpa/TermList.java | 261 -- .../org/openecomp/policy/rest/jpa/UserInfo.java | 76 - .../java/org/openecomp/policy/rest/jpa/VMType.java | 102 - .../org/openecomp/policy/rest/jpa/VNFType.java | 173 -- .../org/openecomp/policy/rest/jpa/VSCLAction.java | 173 -- .../policy/rest/jpa/VarbindDictionary.java | 184 -- .../rest/jpa/WatchPolicyNotificationTable.java | 80 - .../java/org/openecomp/policy/rest/jpa/Zone.java | 101 - .../openecomp/policy/rest/jpa/package-info.java | 21 - .../policy/rest/util/LockdownListener.java | 36 - .../policy/rest/util/MSAttributeObject.java | 109 - .../policy/rest/util/MSAttributeValue.java | 60 - .../openecomp/policy/rest/util/MSModelUtils.java | 701 ----- .../org/openecomp/policy/rest/util/Webapps.java | 115 - .../org/openecomp/policy/rest/XACMLRestTest.java | 107 - ECOMP-SDK-APP/README.md | 68 - ECOMP-SDK-APP/policyLogger.properties | 44 - ECOMP-SDK-APP/pom.xml | 267 -- .../portalapp/conf/ExternalAppConfig.java | 161 -- .../portalapp/conf/ExternalAppInitializer.java | 47 - .../portalapp/conf/HibernateMappingLocations.java | 57 - .../portalapp/lm/FusionLicenseManagerImpl.java | 69 - .../portalapp/lm/LicenseableClassImpl.java | 62 - .../portalapp/login/LoginStrategyImpl.java | 73 - .../openecomp/portalapp/scheduler/Register.java | 71 - .../portalapp/scheduler/RegistryAdapter.java | 92 - .../portalapp/service/AdminAuthExtension.java | 113 - ECOMP-SDK-APP/src/main/resources/logback.xml | 370 --- ECOMP-SDK-APP/src/main/resources/portal.properties | 69 - .../src/main/webapp/WEB-INF/conf/system.properties | 72 - .../webapp/WEB-INF/fusion/jsp/ds2/left-menu.jsp | 778 ------ .../fusion/orm/RNoteBookIntegration.hbm.xml | 44 - ECOMP-SDK-APP/src/main/webapp/WEB-INF/index.jsp | 24 - .../src/main/webapp/WEB-INF/jsp/login.jsp | 113 - .../src/main/webapp/WEB-INF/jsp/login_external.jsp | 117 - ECOMP-SDK-APP/src/main/webapp/WEB-INF/web.xml | 17 - .../ds2-samplePages/samplePage.html | 62 - .../app/fusion/scripts/DS2-view-models/footer.html | 13 - .../app/fusion/scripts/utils/page-resource-ds2.js | 97 - .../app/fusion/scripts/view-models/footer.html | 17 - .../css/att_angular_gridster/ui-gridster.css | 116 - .../static/fusion/sample/html/data/worddata.csv | 1 - .../static/fusion/sample/html/wordcloud.html | 36 - ECOMP-SDK-APP/xacml.admin.properties | 203 -- ECOMP-XACML/config_testing/test_PolicyEngine.xml | 595 ----- ECOMP-XACML/config_testing/xacml.pip.properties | 19 - ECOMP-XACML/config_testing/xacml.policy.properties | 23 - ECOMP-XACML/policyLogger.properties | 44 - ECOMP-XACML/pom.xml | 88 - .../policy/xacml/api/XACMLErrorConstants.java | 56 - .../xacml/api/pap/ECOMPPapEngineFactory.java | 38 - .../policy/xacml/api/pap/EcompPAPPolicy.java | 89 - .../openecomp/policy/xacml/api/pap/EcompPDP.java | 44 - .../policy/xacml/api/pap/EcompPDPGroup.java | 15 - .../policy/xacml/api/pap/PAPPolicyEngine.java | 66 - .../openecomp/policy/xacml/std/pap/StdEngine.java | 1034 -------- .../policy/xacml/std/pap/StdEngineFactory.java | 57 - .../policy/xacml/std/pap/StdPAPPolicy.java | 910 ------- .../org/openecomp/policy/xacml/std/pap/StdPDP.java | 222 -- .../policy/xacml/std/pap/StdPDPGroup.java | 1058 -------- .../policy/xacml/std/pap/StdPDPGroupStatus.java | 405 --- .../xacml/std/pap/StdPDPItemSetChangeNotifier.java | 81 - .../policy/xacml/std/pap/StdPDPPIPConfig.java | 216 -- .../policy/xacml/std/pap/StdPDPPolicy.java | 366 --- .../policy/xacml/std/pap/StdPDPStatus.java | 265 -- .../std/pip/engines/OperationHistoryEngine.java | 297 --- .../xacml/std/pip/engines/aaf/AAFEngine.java | 272 -- .../openecomp/policy/xacml/util/MetricsUtil.java | 80 - .../policy/xacml/util/XACMLPolicyScanner.java | 722 ----- .../policy/xacml/util/XACMLPolicyWriter.java | 344 --- ECOMP-XACML/src/main/resources/xacml.properties | 46 - .../xacml/test/std/pap/StdEngineFactoryTest.java | 51 - .../policy/xacml/test/util/AAFEngineTest.java | 24 - .../policy/xacml/test/util/MetricsUtilTest.java | 52 - .../xacml/test/util/XACMLPolicyScannerTest.java | 88 - .../xacml/test/util/XACMLPolicyWriterTest.java | 62 - .../test/resources/Action_TestActionPolicy.1.xml | 52 - ECOMP-XACML/src/test/resources/CSVPolicy.xml | 205 -- .../src/test/resources/Config_SampleTest1206.1.xml | 90 - ECOMP-XACML/src/test/resources/log4j.properties | 42 - ECOMP-XACML/src/test/resources/logback.xml | 253 -- ECOMP-XACML/src/test/resources/logging.properties | 32 - ....Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml | 93 - .../resources/pdps/default/xacml.pip.properties | 6 - .../src/test/resources/xacml.pip.properties | 23 - .../src/test/resources/xacml.policy.properties | 25 - ECOMP-XACML/testclient.properties | 21 - ECOMP-XACML/testpdp.properties | 21 - ECOMP-XACML/xacml.pap.properties | 107 - ECOMP-XACML/xacml.pdp.properties | 86 - ECOMP-XACML/xacml.properties | 46 - LogParser/parserlog.properties | 2 +- LogParser/pom.xml | 8 +- .../java/org/onap/xacml/parser/LogEntryObject.java | 74 + .../main/java/org/onap/xacml/parser/ParseLog.java | 695 +++++ .../org/openecomp/xacml/parser/LogEntryObject.java | 74 - .../java/org/openecomp/xacml/parser/ParseLog.java | 695 ----- .../java/org/onap/xacml/parser/ParseLogTest.java | 506 ++++ .../org/openecomp/xacml/parser/ParseLogTest.java | 506 ---- LogParser/src/test/resources/LineTest.txt | 20 +- LogParser/src/test/resources/LineTest2.txt | 10 +- ONAP-ASDC/pom.xml | 37 + .../main/java/org/onap/policy/asdc/Resource.java | 159 ++ .../org/onap/policy/asdc/ResourceInstance.java | 157 ++ .../java/org/onap/policy/asdc/ResourceType.java | 40 + .../main/java/org/onap/policy/asdc/Service.java | 140 + .../java/org/onap/policy/asdc/ServiceInstance.java | 177 ++ .../src/main/resources/definitions.yaml | 0 ONAP-ControlloopPolicy/pom.xml | 62 + .../controlloop/compiler/CompilerException.java | 47 + .../controlloop/compiler/ControlLoopCompiler.java | 617 +++++ .../compiler/ControlLoopCompilerCallback.java | 29 + .../guard/compiler/ControlLoopGuardCompiler.java | 133 + .../policy/controlloop/policy/ControlLoop.java | 189 ++ .../controlloop/policy/ControlLoopPolicy.java | 83 + .../policy/controlloop/policy/FinalResult.java | 93 + .../policy/OperationsAccumulateParams.java | 99 + .../org/onap/policy/controlloop/policy/Policy.java | 353 +++ .../policy/controlloop/policy/PolicyResult.java | 82 + .../org/onap/policy/controlloop/policy/Target.java | 106 + .../onap/policy/controlloop/policy/TargetType.java | 39 + .../policy/builder/BuilderException.java | 31 + .../policy/builder/ControlLoopPolicyBuilder.java | 287 ++ .../policy/controlloop/policy/builder/Message.java | 29 + .../controlloop/policy/builder/MessageLevel.java | 29 + .../policy/controlloop/policy/builder/Results.java | 33 + .../builder/impl/ControlLoopPolicyBuilderImpl.java | 496 ++++ .../policy/builder/impl/MessageImpl.java | 46 + .../policy/builder/impl/ResultsImpl.java | 55 + .../controlloop/policy/guard/Constraint.java | 171 ++ .../controlloop/policy/guard/ControlLoopGuard.java | 92 + .../policy/guard/ControlLoopParameter.java | 89 + .../policy/controlloop/policy/guard/Guard.java | 67 + .../controlloop/policy/guard/GuardPolicy.java | 181 ++ .../controlloop/policy/guard/MatchParameters.java | 142 + .../guard/builder/ControlLoopGuardBuilder.java | 130 + .../builder/impl/ControlLoopGuardBuilderImpl.java | 244 ++ .../compiler/ControlLoopCompilerTest.java | 80 + .../compiler/ControlLoopGuardCompilerTest.java | 101 + .../policy/ControlLoopPolicyBuilderTest.java | 516 ++++ .../controlloop/policy/ControlLoopPolicyTest.java | 101 + .../policy/guard/ControlLoopGuardBuilderTest.java | 202 ++ .../policy/guard/ControlLoopGuardTest.java | 93 + .../src/test/resources/v1.0.0/bad_policies_1.yaml | 0 .../src/test/resources/v1.0.0/bad_trigger_1.yaml | 0 .../src/test/resources/v1.0.0/bad_trigger_2.yaml | 0 .../resources/v1.0.0/policy_OpenLoop_1610.yaml | 0 .../src/test/resources/v1.0.0/policy_Test.yaml | 0 .../v1.0.0/policy_Test_MultipleService.yaml | 0 .../src/test/resources/v1.0.0/test.yaml | 0 .../src/test/resources/v1.0.0/test_evil.yaml | 0 .../v2.0.0-guard/duplicate_guard_constraint.yaml | 0 .../v2.0.0-guard/duplicate_guard_policy.yaml | 0 .../v2.0.0-guard/no_guard_constraint.yaml | 0 .../resources/v2.0.0-guard/no_guard_policy.yaml | 0 .../v2.0.0-guard/policy_guard_1707_appc.yaml | 0 .../v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml | 0 .../resource-59a2ee3fB58045feB5a1-template.yml | 1698 ++++++++++++ .../resource-Eace933104d443b496b8-template.yml | 2525 ++++++++++++++++++ .../service-57e66ea70ed645c7970f-template.yml | 677 +++++ .../service-D473899264974dca9db9-template.yml | 677 +++++ .../src/test/resources/v2.0.0/pgstreams.json | 0 .../resources/v2.0.0/policy_ONAP_demo_vDNS.yaml | 0 .../v2.0.0/policy_ONAP_demo_vFirewall.yaml | 0 {ECOMP-PAP-REST => ONAP-PAP-REST}/.gitignore | 0 .../WebContent/META-INF/MANIFEST.MF | 0 .../WebContent/README.txt | 0 ONAP-PAP-REST/autopush.properties | 22 + ONAP-PAP-REST/dictionaryItemsAPI.json | 52 + ONAP-PAP-REST/pip.properties | 15 + ONAP-PAP-REST/policyLogger.properties | 44 + ONAP-PAP-REST/policyelk.properties | 30 + ONAP-PAP-REST/pom.xml | 344 +++ .../onap/policy/pap/xacml/rest/PAPRestConfig.java | 145 + .../org/onap/policy/pap/xacml/rest/WebConfig.java | 43 + .../policy/pap/xacml/rest/XACMLPapServlet.java | 2617 ++++++++++++++++++ .../policy/pap/xacml/rest/adapters/GridData.java | 62 + .../pap/xacml/rest/adapters/package-info.java | 21 + .../pap/xacml/rest/components/ActionPolicy.java | 529 ++++ .../pap/xacml/rest/components/AutoPushPolicy.java | 100 + .../xacml/rest/components/ClosedLoopPolicy.java | 412 +++ .../pap/xacml/rest/components/ConfigPolicy.java | 564 ++++ .../rest/components/CreateBRMSRuleTemplate.java | 73 + .../rest/components/CreateBrmsParamPolicy.java | 692 +++++ .../xacml/rest/components/CreateBrmsRawPolicy.java | 489 ++++ .../CreateClosedLoopPerformanceMetrics.java | 412 +++ .../components/CreateNewMicroServiceModel.java | 248 ++ .../pap/xacml/rest/components/DecisionPolicy.java | 793 ++++++ .../rest/components/FirewallConfigPolicy.java | 1305 +++++++++ .../rest/components/MicroServiceConfigPolicy.java | 555 ++++ .../policy/pap/xacml/rest/components/Policy.java | 416 +++ .../pap/xacml/rest/components/PolicyDBDao.java | 2798 ++++++++++++++++++++ .../rest/components/PolicyDBDaoTransaction.java | 188 ++ .../xacml/rest/components/SafePolicyBuilder.java | 86 + .../pap/xacml/rest/components/package-info.java | 21 + .../ActionPolicyDictionaryController.java | 261 ++ .../rest/controller/BRMSDictionaryController.java | 552 ++++ .../controller/ClosedLoopDictionaryController.java | 1031 ++++++++ .../DecisionPolicyDictionaryController.java | 426 +++ .../DescriptiveDictionaryController.java | 246 ++ .../rest/controller/DictionaryController.java | 447 ++++ .../controller/DictionaryImportController.java | 539 ++++ .../controller/EnforcerDictionaryController.java | 139 + .../controller/FirewallDictionaryController.java | 2279 ++++++++++++++++ .../MicroServiceDictionaryController.java | 1051 ++++++++ .../PolicyScopeDictionaryController.java | 927 +++++++ .../rest/controller/PushPolicyController.java | 229 ++ .../rest/controller/SafePolicyController.java | 385 +++ .../pap/xacml/rest/controller/package-info.java | 22 + .../pap/xacml/rest/daoimpl/CommonClassDaoImpl.java | 443 ++++ .../rest/elk/client/ElasticSearchPolicyUpdate.java | 311 +++ .../pap/xacml/rest/elk/client/ElkConnector.java | 101 + .../xacml/rest/elk/client/ElkConnectorImpl.java | 418 +++ .../policy/pap/xacml/rest/elk/client/Pair.java | 33 + .../xacml/rest/elk/client/PolicyElasticData.java | 623 +++++ .../elk/client/PolicyElasticSearchController.java | 563 ++++ .../pap/xacml/rest/elk/client/PolicyLocator.java | 51 + .../pap/xacml/rest/handler/APIRequestHandler.java | 96 + .../pap/xacml/rest/handler/DeleteHandler.java | 477 ++++ .../pap/xacml/rest/handler/DictionaryHandler.java | 63 + .../xacml/rest/handler/DictionaryHandlerImpl.java | 323 +++ .../pap/xacml/rest/handler/PushPolicyHandler.java | 123 + .../pap/xacml/rest/handler/SavePolicyHandler.java | 157 ++ .../pap/xacml/rest/model/PDPPolicyContainer.java | 348 +++ .../pap/xacml/rest/model/RemoveGroupPolicy.java | 102 + .../policy/pap/xacml/rest/model/package-info.java | 20 + .../rest/policycontroller/PolicyCreation.java | 550 ++++ .../xacml/rest/policycontroller/package-info.java | 20 + .../pap/xacml/rest/service/DictionaryService.java | 995 +++++++ .../pap/xacml/rest/service/ImportService.java | 157 ++ .../pap/xacml/rest/service/MetricService.java | 93 + .../xacml/rest/util/AbstractPolicyCreation.java | 104 + .../onap/policy/pap/xacml/rest/util/JPAUtils.java | 239 ++ .../policy/pap/xacml/rest/util/JsonMessage.java | 67 + .../pap/xacml/rest/util/PolicyContainer.java | 121 + .../rest/util/PolicyItemSetChangeNotifier.java | 96 + .../pap/xacml/restAuth/AuthenticationService.java | 63 + .../onap/policy/pap/xacml/restAuth/CheckPDP.java | 181 ++ .../xacml/restAuth/PAPAuthenticationFilter.java | 130 + .../resources/Decision_GuardBLPolicyTemplate.xml | 111 + .../resources/Decision_GuardPolicyTemplate.xml | 107 + .../src/main/resources/META-INF/drop.ddl | 0 .../main/resources/META-INF/generatedCreate.ddl | 119 + .../src/main/resources/META-INF/generatedDrop.ddl | 118 + .../src/main/resources/META-INF/persistence.xml | 201 ++ ONAP-PAP-REST/src/main/resources/log4j.properties | 71 + ONAP-PAP-REST/src/main/resources/logback.xml | 254 ++ ONAP-PAP-REST/src/main/resources/spring.xml | 46 + .../policy/pap/ia/DbAuditCompareEntriesTest.java | 450 ++++ .../pap/xacml/rest/components/PolicyDBDaoTest.java | 636 +++++ .../rest/controller/DictionaryControllerTest.java | 319 +++ .../MicroServiceDictionaryControllerTest.java | 693 +++++ .../pap/xacml/rest/jpa/PolicyEntityTest.java | 803 ++++++ ONAP-PAP-REST/test.properties | 22 + ONAP-PAP-REST/xacml.pap.properties | 165 ++ ONAP-PAP-REST/xacml.pap.test.properties | 145 + {ECOMP-PDP-REST => ONAP-PDP-REST}/.gitignore | 0 .../WebContent/META-INF/MANIFEST.MF | 0 .../WebContent/WEB-INF/.gitignore | 0 .../client.properties | 0 ONAP-PDP-REST/config/policyLogger.properties | 44 + .../config/xacml.pip.properties | 0 .../config/xacml.policy.properties | 0 ONAP-PDP-REST/policyLogger.properties | 44 + ONAP-PDP-REST/pom.xml | 223 ++ .../org/onap/policy/pdp/rest/PapUrlResolver.java | 377 +++ .../org/onap/policy/pdp/rest/XACMLPdpLoader.java | 645 +++++ .../policy/pdp/rest/XACMLPdpRegisterThread.java | 285 ++ .../org/onap/policy/pdp/rest/XACMLPdpServlet.java | 1266 +++++++++ .../rest/api/controller/PolicyEngineServices.java | 658 +++++ .../api/models/ConfigFirewallPolicyAPIRequest.java | 80 + .../pdp/rest/api/models/ConfigNameRequest.java | 39 + .../rest/api/models/ConfigPolicyAPIRequest.java | 188 ++ .../policy/pdp/rest/api/models/PDPResponse.java | 159 ++ .../policy/pdp/rest/api/models/PolicyConfig.java | 95 + .../pdp/rest/api/services/ActionPolicyService.java | 105 + .../rest/api/services/BRMSParamPolicyService.java | 96 + .../rest/api/services/BRMSRawPolicyService.java | 106 + .../api/services/ClosedLoopFaultPolicyService.java | 121 + .../api/services/ClosedLoopPMPolicyService.java | 122 + .../pdp/rest/api/services/ConfigPolicyService.java | 136 + .../services/CreateUpdateConfigPolicyService.java | 118 + .../services/CreateUpdateDictionaryService.java | 153 ++ .../CreateUpdateFirewallPolicyService.java | 92 + .../api/services/CreateUpdatePolicyService.java | 35 + .../services/CreateUpdatePolicyServiceImpl.java | 293 ++ .../rest/api/services/DecisionPolicyService.java | 100 + .../pdp/rest/api/services/DeletePolicyService.java | 258 ++ .../rest/api/services/FirewallPolicyService.java | 113 + .../pdp/rest/api/services/GetConfigService.java | 318 +++ .../pdp/rest/api/services/GetDecisionService.java | 189 ++ .../rest/api/services/GetDictionaryService.java | 276 ++ .../pdp/rest/api/services/GetMetricsService.java | 157 ++ .../pdp/rest/api/services/ListConfigService.java | 64 + .../api/services/MicroServicesPolicyService.java | 135 + .../pdp/rest/api/services/NotificationService.java | 314 +++ .../policy/pdp/rest/api/services/PAPServices.java | 656 +++++ .../policy/pdp/rest/api/services/PDPServices.java | 439 +++ .../api/services/PolicyEngineImportService.java | 186 ++ .../pdp/rest/api/services/PushPolicyService.java | 236 ++ .../pdp/rest/api/services/SendEventService.java | 170 ++ .../policy/pdp/rest/api/utils/PolicyApiUtils.java | 72 + .../onap/policy/pdp/rest/config/PDPApiAuth.java | 189 ++ .../onap/policy/pdp/rest/config/PDPRestConfig.java | 77 + .../policy/pdp/rest/config/PDPRestInitializer.java | 51 + .../pdp/rest/impl/XACMLPdpPIPFinderFactory.java | 88 + .../pdp/rest/impl/XACMLPdpPolicyFinderFactory.java | 208 ++ .../policy/pdp/rest/jmx/PdpRestMBeanListener.java | 85 + .../onap/policy/pdp/rest/jmx/PdpRestMonitor.java | 162 ++ .../policy/pdp/rest/jmx/PdpRestMonitorMBean.java | 40 + .../ManualNotificationUpdateThread.java | 229 ++ .../pdp/rest/notifications/Notification.java | 62 + .../rest/notifications/NotificationController.java | 415 +++ .../pdp/rest/notifications/NotificationServer.java | 224 ++ .../policy/pdp/rest/notifications/Removed.java | 54 + .../policy/pdp/rest/notifications/Updated.java | 74 + .../pdp/rest/notifications/package-info.java | 28 + .../pdp/rest/restAuth/AuthenticationService.java | 62 + .../pdp/rest/restAuth/PDPAuthenticationFilter.java | 117 + ONAP-PDP-REST/src/main/resources/log4j.properties | 71 + ONAP-PDP-REST/src/main/resources/logback.xml | 253 ++ .../onap/policy/pdp/rest/PapUrlResolverTest.java | 224 ++ .../onap/policy/pdp/rest/XACMLPdpServletTest.java | 364 +++ .../pdp/rest/api/services/PDPServicesTest.java | 194 ++ .../pdp/rest/api/test/NotificationAPITest.java | 87 + .../rest/api/test/PolicyEngineServicesTest.java | 832 ++++++ .../policy/pdp/rest/api/test/getConfigTest.java | 70 + .../pdp/rest/api/test/getDictionaryTest.java | 231 ++ .../policy/pdp/rest/auth/test/FilterTests.java | 199 ++ .../src/test/resources/client.properties | 0 .../src/test/resources/fail.xacml.pdp.properties | 171 ++ .../src/test/resources/pass.xacml.pdp.properties | 171 ++ ONAP-PDP-REST/src/test/resources/test.drl | 1121 ++++++++ ONAP-PDP-REST/xacml.pdp.properties | 172 ++ {ECOMP-PDP => ONAP-PDP}/.gitignore | 0 ONAP-PDP/config_testing/test_PolicyEngine.xml | 595 +++++ ONAP-PDP/config_testing/xacml.pip.properties | 19 + ONAP-PDP/config_testing/xacml.policy.properties | 23 + ONAP-PDP/logging.properties | 29 + ONAP-PDP/policyLogger.properties | 44 + ONAP-PDP/pom.xml | 88 + {ECOMP-PDP => ONAP-PDP}/sql/xacmlTest.mv.db | Bin .../org/onap/policy/xacml/action/FindAction.java | 356 +++ .../org/onap/policy/xacml/action/package-info.java | 30 + .../custom/OnapFunctionDefinitionFactory.java | 88 + .../org/onap/policy/xacml/pdp/ONAPPDPEngine.java | 60 + .../policy/xacml/pdp/ONAPPDPEngineFactory.java | 54 + .../FunctionDefinitionCustomRegexpMatch.java | 130 + .../policy/xacml/pdp/std/functions/PolicyList.java | 49 + .../FunctionDefinitionAccessPermittedTest.java | 521 ++++ .../pdp/test/FunctionDefinitionArithmeticTest.java | 717 +++++ .../pdp/test/FunctionDefinitionBagIsInTest.java | 221 ++ .../test/FunctionDefinitionBagOneAndOnlyTest.java | 224 ++ .../pdp/test/FunctionDefinitionBagSizeTest.java | 158 ++ .../policy/pdp/test/FunctionDefinitionBagTest.java | 547 ++++ .../pdp/test/FunctionDefinitionBaseTest.java | 131 + .../pdp/test/FunctionDefinitionComparisonTest.java | 1366 ++++++++++ .../FunctionDefinitionDateTimeArithmeticTest.java | 1602 +++++++++++ .../pdp/test/FunctionDefinitionEqualityTest.java | 1192 +++++++++ .../test/FunctionDefinitionHigherOrderBagTest.java | 2193 +++++++++++++++ .../FunctionDefinitionHomogeneousSimpleTest.java | 151 ++ .../pdp/test/FunctionDefinitionLogicalTest.java | 422 +++ ...FunctionDefinitionNumberTypeConversionTest.java | 119 + .../test/FunctionDefinitionRegexpMatchTest.java | 511 ++++ .../policy/pdp/test/FunctionDefinitionSetTest.java | 1903 +++++++++++++ .../test/FunctionDefinitionSpecialMatchTest.java | 487 ++++ .../FunctionDefinitionStringConversionTest.java | 2504 ++++++++++++++++++ ...unctionDefinitionStringEqualIgnoreCaseTest.java | 129 + .../FunctionDefinitionStringFunctionsTest.java | 1497 +++++++++++ .../FunctionDefinitionStringNormalizeTest.java | 118 + ...FunctionDefinitionURIStringConcatenateTest.java | 185 ++ .../pdp/test/FunctionDefinitionXPathTest.java | 1127 ++++++++ .../java/org/onap/policy/pdp/test/PDPTest.java | 36 + .../java/org/onap/policy/pdp/test/TestRunner.java | 46 + .../policy/pdp/test/conformance/Conformance.java | 634 +++++ .../pdp/test/conformance/ConformancePIPEngine.java | 242 ++ .../test/conformance/ConformanceRepository.java | 127 + .../test/conformance/ConformanceScopeResolver.java | 121 + .../pdp/test/conformance/ConformanceTest.java | 104 + .../test/conformance/ConformanceTestEngine.java | 219 ++ .../test/conformance/ConformanceTestResult.java | 122 + .../pdp/test/conformance/ConformanceTestSet.java | 180 ++ .../pdp/test/conformance/ResponseMatchResult.java | 137 + .../pdp/test/conformance/ResultMatchResult.java | 136 + .../pdp/test/custom/CustomDataTypeFactory.java | 88 + .../custom/CustomFunctionDefinitionFactory.java | 90 + .../policy/pdp/test/custom/DataTypePrivateKey.java | 54 + .../policy/pdp/test/custom/DataTypePublicKey.java | 54 + .../pdp/test/custom/FunctionDefinitionDecrypt.java | 162 ++ .../org/onap/policy/pdp/test/custom/TestBase.java | 1082 ++++++++ .../onap/policy/pdp/test/custom/TestCustom.java | 392 +++ ONAP-PDP/src/test/resources/CSVPolicy.xml | 205 ++ ONAP-PDP/src/test/resources/log4j.properties | 42 + ONAP-PDP/src/test/resources/logback.xml | 253 ++ ONAP-PDP/src/test/resources/logging.properties | 32 + ONAP-PDP/src/test/resources/xacml.pip.properties | 23 + .../src/test/resources/xacml.policy.properties | 25 + ONAP-PDP/testclient.properties | 21 + ONAP-PDP/testpdp.properties | 21 + ONAP-PDP/xacml.pap.properties | 107 + ONAP-PDP/xacml.pdp.properties | 86 + ONAP-PDP/xacml.properties | 46 + {ECOMP-REST => ONAP-REST}/.gitignore | 0 ONAP-REST/policyLogger.properties | 44 + ONAP-REST/pom.xml | 114 + .../main/java/org/onap/policy/rest/XACMLRest.java | 216 ++ .../org/onap/policy/rest/XACMLRestProperties.java | 456 ++++ .../onap/policy/rest/XacmlAdminAuthorization.java | 220 ++ .../onap/policy/rest/adapter/AddressGroupJson.java | 83 + .../org/onap/policy/rest/adapter/AddressJson.java | 52 + .../onap/policy/rest/adapter/AddressMembers.java | 46 + .../policy/rest/adapter/AutoPushTabAdapter.java | 42 + .../policy/rest/adapter/ClosedLoopFaultBody.java | 280 ++ .../ClosedLoopFaultTriggerUISignatures.java | 44 + .../onap/policy/rest/adapter/ClosedLoopPMBody.java | 133 + .../rest/adapter/ClosedLoopPerformanceMetrics.java | 36 + .../onap/policy/rest/adapter/ClosedLoopPolicy.java | 61 + .../rest/adapter/ClosedLoopPolicyConditions.java | 39 + .../rest/adapter/ClosedLoopPolicyStatus.java | 41 + .../policy/rest/adapter/ClosedLoopSignatures.java | 52 + .../policy/rest/adapter/DeletePolicyCondition.java | 38 + .../onap/policy/rest/adapter/DeployNowJson.java | 36 + .../org/onap/policy/rest/adapter/GridData.java | 54 + .../java/org/onap/policy/rest/adapter/IdMap.java | 42 + .../policy/rest/adapter/PolicyExportAdapter.java | 36 + .../policy/rest/adapter/PolicyRestAdapter.java | 896 +++++++ .../org/onap/policy/rest/adapter/PrefixIPList.java | 72 + .../onap/policy/rest/adapter/RainyDayParams.java | 100 + .../onap/policy/rest/adapter/ServiceGroupJson.java | 83 + .../onap/policy/rest/adapter/ServiceListJson.java | 111 + .../onap/policy/rest/adapter/ServiceMembers.java | 48 + .../org/onap/policy/rest/adapter/ServicesJson.java | 44 + .../org/onap/policy/rest/adapter/TagDefines.java | 41 + .../java/org/onap/policy/rest/adapter/Tags.java | 59 + .../java/org/onap/policy/rest/adapter/Term.java | 201 ++ .../onap/policy/rest/adapter/TermCollector.java | 145 + .../policy/rest/adapter/VendorSpecificData.java | 38 + .../org/onap/policy/rest/adapter/YAMLParams.java | 97 + .../org/onap/policy/rest/adapter/package-info.java | 20 + .../org/onap/policy/rest/dao/CommonClassDao.java | 57 + .../org/onap/policy/rest/dao/package-info.java | 21 + .../org/onap/policy/rest/jpa/ActionBodyEntity.java | 195 ++ .../java/org/onap/policy/rest/jpa/ActionList.java | 103 + .../org/onap/policy/rest/jpa/ActionPolicyDict.java | 211 ++ .../org/onap/policy/rest/jpa/AddressGroup.java | 114 + .../java/org/onap/policy/rest/jpa/Attribute.java | 363 +++ .../onap/policy/rest/jpa/AttributeAssignment.java | 93 + .../org/onap/policy/rest/jpa/BRMSController.java | 154 ++ .../org/onap/policy/rest/jpa/BRMSDependency.java | 153 ++ .../onap/policy/rest/jpa/BRMSParamTemplate.java | 142 + .../java/org/onap/policy/rest/jpa/Category.java | 218 ++ .../onap/policy/rest/jpa/ClosedLoopD2Services.java | 175 ++ .../org/onap/policy/rest/jpa/ClosedLoopSite.java | 177 ++ .../java/org/onap/policy/rest/jpa/ClosedLoops.java | 99 + .../policy/rest/jpa/ConfigurationDataEntity.java | 224 ++ .../org/onap/policy/rest/jpa/ConstraintType.java | 121 + .../org/onap/policy/rest/jpa/ConstraintValue.java | 116 + .../java/org/onap/policy/rest/jpa/DCAEUsers.java | 102 + .../java/org/onap/policy/rest/jpa/DCAEuuid.java | 102 + .../onap/policy/rest/jpa/DatabaseLockEntity.java | 47 + .../java/org/onap/policy/rest/jpa/Datatype.java | 244 ++ .../org/onap/policy/rest/jpa/DecisionSettings.java | 235 ++ .../org/onap/policy/rest/jpa/DescriptiveScope.java | 181 ++ .../org/onap/policy/rest/jpa/EnforcingType.java | 96 + .../main/java/org/onap/policy/rest/jpa/FWTag.java | 180 ++ .../java/org/onap/policy/rest/jpa/FWTagPicker.java | 189 ++ .../policy/rest/jpa/FirewallDictionaryList.java | 164 ++ .../org/onap/policy/rest/jpa/FunctionArgument.java | 122 + .../onap/policy/rest/jpa/FunctionDefinition.java | 219 ++ .../onap/policy/rest/jpa/GlobalRoleSettings.java | 93 + .../java/org/onap/policy/rest/jpa/GroupEntity.java | 270 ++ .../onap/policy/rest/jpa/GroupPolicyScopeList.java | 111 + .../org/onap/policy/rest/jpa/GroupServiceList.java | 104 + .../policy/rest/jpa/MicroServiceAttribute.java | 109 + .../policy/rest/jpa/MicroServiceConfigName.java | 102 + .../onap/policy/rest/jpa/MicroServiceLocation.java | 102 + .../onap/policy/rest/jpa/MicroServiceModels.java | 189 ++ .../java/org/onap/policy/rest/jpa/Obadvice.java | 227 ++ .../onap/policy/rest/jpa/ObadviceExpression.java | 123 + .../java/org/onap/policy/rest/jpa/OnapName.java | 167 ++ .../java/org/onap/policy/rest/jpa/PEPOptions.java | 183 ++ .../org/onap/policy/rest/jpa/PIPConfigParam.java | 147 + .../org/onap/policy/rest/jpa/PIPConfiguration.java | 537 ++++ .../java/org/onap/policy/rest/jpa/PIPResolver.java | 365 +++ .../org/onap/policy/rest/jpa/PIPResolverParam.java | 147 + .../java/org/onap/policy/rest/jpa/PIPType.java | 131 + .../java/org/onap/policy/rest/jpa/PdpEntity.java | 241 ++ .../org/onap/policy/rest/jpa/PolicyAlgorithms.java | 116 + .../onap/policy/rest/jpa/PolicyDBDaoEntity.java | 150 ++ .../onap/policy/rest/jpa/PolicyEditorScopes.java | 159 ++ .../org/onap/policy/rest/jpa/PolicyEntity.java | 308 +++ .../onap/policy/rest/jpa/PolicyGroupEntity.java | 60 + .../org/onap/policy/rest/jpa/PolicyManagement.java | 162 ++ .../java/org/onap/policy/rest/jpa/PolicyRoles.java | 102 + .../policy/rest/jpa/PolicyScopeClosedLoop.java | 100 + .../onap/policy/rest/jpa/PolicyScopeResource.java | 100 + .../onap/policy/rest/jpa/PolicyScopeService.java | 100 + .../org/onap/policy/rest/jpa/PolicyScopeType.java | 100 + .../java/org/onap/policy/rest/jpa/PolicyScore.java | 104 + .../org/onap/policy/rest/jpa/PolicyVersion.java | 183 ++ .../java/org/onap/policy/rest/jpa/PortList.java | 104 + .../java/org/onap/policy/rest/jpa/PrefixList.java | 114 + .../org/onap/policy/rest/jpa/ProtocolList.java | 105 + .../onap/policy/rest/jpa/RainyDayTreatments.java | 118 + .../onap/policy/rest/jpa/RemoteCatalogValues.java | 102 + .../java/org/onap/policy/rest/jpa/RiskType.java | 172 ++ .../org/onap/policy/rest/jpa/RuleAlgorithms.java | 125 + .../onap/policy/rest/jpa/SafePolicyWarning.java | 109 + .../org/onap/policy/rest/jpa/SecurityZone.java | 101 + .../java/org/onap/policy/rest/jpa/ServiceList.java | 154 ++ .../java/org/onap/policy/rest/jpa/SystemLogDB.java | 163 ++ .../java/org/onap/policy/rest/jpa/TermList.java | 261 ++ .../java/org/onap/policy/rest/jpa/UserInfo.java | 76 + .../main/java/org/onap/policy/rest/jpa/VMType.java | 102 + .../java/org/onap/policy/rest/jpa/VNFType.java | 173 ++ .../java/org/onap/policy/rest/jpa/VSCLAction.java | 173 ++ .../onap/policy/rest/jpa/VarbindDictionary.java | 184 ++ .../rest/jpa/WatchPolicyNotificationTable.java | 80 + .../main/java/org/onap/policy/rest/jpa/Zone.java | 101 + .../org/onap/policy/rest/jpa/package-info.java | 21 + .../onap/policy/rest/util/LockdownListener.java | 36 + .../onap/policy/rest/util/MSAttributeObject.java | 109 + .../onap/policy/rest/util/MSAttributeValue.java | 60 + .../org/onap/policy/rest/util/MSModelUtils.java | 701 +++++ .../java/org/onap/policy/rest/util/Webapps.java | 115 + .../java/org/onap/policy/rest/XACMLRestTest.java | 107 + ...clipse.wst.jsdt.core.javascriptValidator.launch | 0 {ECOMP-SDK-APP => ONAP-SDK-APP}/.gitignore | 0 {ECOMP-SDK-APP => ONAP-SDK-APP}/JSONConfig.json | 0 ONAP-SDK-APP/README.md | 68 + {ECOMP-SDK-APP => ONAP-SDK-APP}/distribution.xml | 0 ONAP-SDK-APP/policyLogger.properties | 44 + ONAP-SDK-APP/pom.xml | 267 ++ .../org/onap/portalapp/conf/ExternalAppConfig.java | 161 ++ .../portalapp/conf/ExternalAppInitializer.java | 47 + .../portalapp/conf/HibernateMappingLocations.java | 57 + .../portalapp/lm/FusionLicenseManagerImpl.java | 69 + .../onap/portalapp/lm/LicenseableClassImpl.java | 62 + .../onap/portalapp/login/LoginStrategyImpl.java | 73 + .../org/onap/portalapp/scheduler/Register.java | 72 + .../onap/portalapp/scheduler/RegistryAdapter.java | 92 + .../onap/portalapp/service/AdminAuthExtension.java | 114 + ONAP-SDK-APP/src/main/resources/logback.xml | 370 +++ ONAP-SDK-APP/src/main/resources/portal.properties | 69 + .../src/main/webapp/WEB-INF/conf/system.properties | 72 + .../src/main/webapp/WEB-INF/defs/definitions.xml | 0 .../webapp/WEB-INF/fusion/conf/fusion.properties | 0 .../main/webapp/WEB-INF/fusion/jsp/ds2/footer.jsp | 0 .../main/webapp/WEB-INF/fusion/jsp/ds2/header.jsp | 0 .../webapp/WEB-INF/fusion/jsp/ds2/left-menu.jsp | 778 ++++++ .../fusion/orm/RNoteBookIntegration.hbm.xml | 44 + ONAP-SDK-APP/src/main/webapp/WEB-INF/index.jsp | 24 + ONAP-SDK-APP/src/main/webapp/WEB-INF/jsp/login.jsp | 113 + .../src/main/webapp/WEB-INF/jsp/login_external.jsp | 117 + ONAP-SDK-APP/src/main/webapp/WEB-INF/web.xml | 17 + .../external/b2b/css/b2b-angular/font_icons.css | 0 .../ds2/css/digital-ng-library/ionicons.css | 0 .../app/fusion/external/ds2/css/fonts/ionicons.eot | Bin .../app/fusion/external/ds2/css/fonts/ionicons.svg | 0 .../app/fusion/external/ds2/css/fonts/ionicons.ttf | Bin .../fusion/external/ds2/css/fonts/ionicons.woff | Bin .../DS2-controllers/ds-profile/post-controller.js | 0 .../scripts/DS2-controllers/samplePage-route.js | 0 .../app/fusion/scripts/DS2-services/postSearch.js | 0 .../scripts/DS2-view-models/ds2-profile/post.html | 0 .../ds2-profile/profile_searchDS2.html | 0 .../DS2-view-models/ds2-profile/self_profile.html | 0 .../ds2-samplePages/samplePage.html | 62 + .../app/fusion/scripts/DS2-view-models/footer.html | 13 + .../app/fusion/scripts/utils/page-resource-ds2.js | 97 + .../app/fusion/scripts/view-models/footer.html | 17 + .../css/att_angular_gridster/sandbox-gridster.css | 0 .../css/att_angular_gridster/ui-gridster.css | 116 + .../main/webapp/static/fusion/css/fusion-sunny.css | 0 .../fusion/images/att_angular_gridster/grips.png | Bin .../static/fusion/images/onap-login-550x360.jpg | Bin .../webapp/static/fusion/images/onap-login.jpg | Bin .../src/main/webapp/static/fusion/images/onap.png | Bin .../webapp/static/fusion/images/onap_trans.png | Bin .../js/att_angular_gridster/angular-gridster.js | 0 .../js/att_angular_gridster/ui-gridster-tpls.js | 0 .../static/fusion/sample/css/images/blank.gif | Bin .../webapp/static/fusion/sample/css/scribble.css | 0 .../webapp/static/fusion/sample/css/slider.css | 0 .../static/fusion/sample/css/spacegallery.css | 0 .../webapp/static/fusion/sample/css/welcome.css | 0 .../static/fusion/sample/html/area_chart.html | 0 .../static/fusion/sample/html/bar_chart.html | 0 .../static/fusion/sample/html/d3_gauges_demo.html | 0 .../fusion/sample/html/data/speedometer2.csv | 0 .../fusion/sample/html/data/speedometer3.csv | 0 .../static/fusion/sample/html/data/worddata.csv | 1 + .../webapp/static/fusion/sample/html/donut_d3.html | 0 .../static/fusion/sample/html/js/area_chart.min.js | 0 .../static/fusion/sample/html/js/donut.min.js | 0 .../static/fusion/sample/html/js/gauges.min.js | 0 .../static/fusion/sample/html/js/line_chart.min.js | 0 .../static/fusion/sample/html/js/pie_chart.min.js | 0 .../static/fusion/sample/html/js/worddata.min.js | 0 .../static/fusion/sample/html/line_chart.html | 0 .../static/fusion/sample/html/pie_chart.html | 0 .../static/fusion/sample/html/wordcloud.html | 36 + .../static/fusion/sample/images/Calendar-16x16.png | Bin .../static/fusion/sample/images/arrow-next.png | Bin .../static/fusion/sample/images/arrow-prev.png | Bin .../images/carousel/slide_b_drive_test_map.png | Bin .../sample/images/carousel/slide_b_eppt_county.png | Bin .../images/carousel/slide_b_eppt_regression.png | Bin .../images/carousel/slide_b_ios_throughput.png | Bin .../sample/images/carousel/slide_b_lata_map.png | Bin .../images/carousel/slide_b_lata_map_legend.png | Bin .../images/carousel/slide_b_nova_sdn_map.png | Bin .../static/fusion/sample/images/copyicon.png | Bin .../static/fusion/sample/images/deleteicon.gif | Bin .../static/fusion/sample/images/example-frame.png | Bin .../webapp/static/fusion/sample/images/loading.gif | Bin .../static/fusion/sample/images/tunnels/1_mon.png | Bin .../static/fusion/sample/images/tunnels/2_tue.png | Bin .../static/fusion/sample/images/tunnels/3_wed.png | Bin .../static/fusion/sample/images/tunnels/4_thu.png | Bin .../static/fusion/sample/images/tunnels/5_fri.png | Bin .../static/fusion/sample/images/tunnels/6_sat.png | Bin .../static/fusion/sample/images/tunnels/7_sun.png | Bin .../fusion/sample/images/tunnels/BH_DLSTX_IN.png | Bin .../fusion/sample/images/tunnels/BH_DLSTX_OUT.png | Bin .../static/fusion/sample/images/tunnels/BH_Nat.png | Bin .../fusion/sample/images/tunnels/BH_Nat_Def.png | Bin .../sample/images/tunnels/BH_Nat_Priority.png | Bin .../webapp/static/fusion/sample/js/FusionCharts.js | 0 .../main/webapp/static/fusion/sample/js/charts.js | 0 .../fusion/sample/js/jquery.flexslider-min.js | 0 .../webapp/static/fusion/sample/js/scribble.js | 0 .../static/fusion/sample/js/slides.min.jquery.js | 0 .../webapp/static/fusion/sample/js/spacegallery.js | 0 .../fusion/sample/org_chart/css/bootstrap.min.css | 0 .../static/fusion/sample/org_chart/css/custom.css | 0 .../sample/org_chart/css/jquery.jOrgChart.css | 0 .../fusion/sample/org_chart/css/prettify.css | 0 .../static/fusion/sample/org_chart/example.html | 0 .../fusion/sample/org_chart/example_vsp.html | 0 .../static/fusion/sample/org_chart/images/bkgd.png | Bin .../fusion/sample/org_chart/images/raspberry.jpg | Bin .../fusion/sample/org_chart/jquery.jOrgChart.js | 0 .../static/fusion/sample/org_chart/prettify.js | 0 ONAP-SDK-APP/xacml.admin.properties | 203 ++ {ECOMP-XACML => ONAP-XACML}/.gitignore | 0 ONAP-XACML/config_testing/test_PolicyEngine.xml | 595 +++++ ONAP-XACML/config_testing/xacml.pip.properties | 19 + ONAP-XACML/config_testing/xacml.policy.properties | 23 + ONAP-XACML/policyLogger.properties | 44 + ONAP-XACML/pom.xml | 88 + {ECOMP-XACML => ONAP-XACML}/sql/xacmlTest.mv.db | Bin .../onap/policy/xacml/api/XACMLErrorConstants.java | 56 + .../policy/xacml/api/pap/ONAPPapEngineFactory.java | 38 + .../onap/policy/xacml/api/pap/OnapPAPPolicy.java | 89 + .../org/onap/policy/xacml/api/pap/OnapPDP.java | 44 + .../onap/policy/xacml/api/pap/OnapPDPGroup.java | 15 + .../onap/policy/xacml/api/pap/PAPPolicyEngine.java | 66 + .../org/onap/policy/xacml/std/pap/StdEngine.java | 1034 ++++++++ .../policy/xacml/std/pap/StdEngineFactory.java | 57 + .../onap/policy/xacml/std/pap/StdPAPPolicy.java | 910 +++++++ .../java/org/onap/policy/xacml/std/pap/StdPDP.java | 222 ++ .../org/onap/policy/xacml/std/pap/StdPDPGroup.java | 1058 ++++++++ .../policy/xacml/std/pap/StdPDPGroupStatus.java | 405 +++ .../xacml/std/pap/StdPDPItemSetChangeNotifier.java | 81 + .../onap/policy/xacml/std/pap/StdPDPPIPConfig.java | 216 ++ .../onap/policy/xacml/std/pap/StdPDPPolicy.java | 366 +++ .../onap/policy/xacml/std/pap/StdPDPStatus.java | 265 ++ .../std/pip/engines/OperationHistoryEngine.java | 297 +++ .../xacml/std/pip/engines/aaf/AAFEngine.java | 272 ++ .../org/onap/policy/xacml/util/MetricsUtil.java | 80 + .../onap/policy/xacml/util/XACMLPolicyScanner.java | 722 +++++ .../onap/policy/xacml/util/XACMLPolicyWriter.java | 344 +++ .../main/resources/META-INF/operationHistoryPU.xml | 0 ONAP-XACML/src/main/resources/xacml.properties | 46 + .../xacml/test/std/pap/StdEngineFactoryTest.java | 51 + .../onap/policy/xacml/test/util/AAFEngineTest.java | 24 + .../policy/xacml/test/util/MetricsUtilTest.java | 52 + .../xacml/test/util/XACMLPolicyScannerTest.java | 88 + .../xacml/test/util/XACMLPolicyWriterTest.java | 62 + .../test/resources/Action_TestActionPolicy.1.xml | 52 + ONAP-XACML/src/test/resources/CSVPolicy.xml | 205 ++ .../src/test/resources/Config_SampleTest1206.1.xml | 90 + ONAP-XACML/src/test/resources/log4j.properties | 42 + ONAP-XACML/src/test/resources/logback.xml | 253 ++ ONAP-XACML/src/test/resources/logging.properties | 32 + ....Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml | 93 + .../resources/pdps/default/xacml.pip.properties | 6 + .../resources/pdps/default/xacml.policy.properties | 0 .../src/test/resources/pdps/xacml.properties | 0 ONAP-XACML/src/test/resources/xacml.pip.properties | 23 + .../src/test/resources/xacml.policy.properties | 25 + ONAP-XACML/testclient.properties | 21 + ONAP-XACML/testpdp.properties | 21 + .../xacml3.0-ct-v.0.4/IIA001Response.xml | 0 ONAP-XACML/xacml.pap.properties | 107 + ONAP-XACML/xacml.pdp.properties | 86 + ONAP-XACML/xacml.properties | 46 + POLICY-SDK-APP/pom.xml | 6 +- .../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 +- .../Test/PDP_settings/test_PolicyEngine.xml | 98 +- PolicyEngineAPI/Test/test_PolicyEngine.xml | 98 +- PolicyEngineAPI/pom.xml | 8 +- .../java/org/onap/policy/api/AttributeType.java | 78 + .../onap/policy/api/ConfigRequestParameters.java | 148 ++ .../onap/policy/api/DecisionRequestParameters.java | 104 + .../java/org/onap/policy/api/DecisionResponse.java | 43 + .../org/onap/policy/api/DeletePolicyCondition.java | 65 + .../onap/policy/api/DeletePolicyParameters.java | 114 + .../org/onap/policy/api/DictionaryParameters.java | 82 + .../org/onap/policy/api/DictionaryResponse.java | 41 + .../java/org/onap/policy/api/DictionaryType.java | 100 + .../onap/policy/api/EventRequestParameters.java | 89 + .../java/org/onap/policy/api/ImportParameters.java | 175 ++ .../onap/policy/api/MetricsRequestParameters.java | 21 + .../java/org/onap/policy/api/MetricsResponse.java | 45 + .../org/onap/policy/api/NotificationScheme.java | 61 + .../org/onap/policy/api/PolicyChangeResponse.java | 44 + .../main/java/org/onap/policy/api/PolicyClass.java | 67 + .../java/org/onap/policy/api/PolicyConfig.java | 123 + .../org/onap/policy/api/PolicyConfigException.java | 49 + .../org/onap/policy/api/PolicyConfigStatus.java | 79 + .../java/org/onap/policy/api/PolicyConfigType.java | 87 + .../java/org/onap/policy/api/PolicyDecision.java | 68 + .../onap/policy/api/PolicyDecisionException.java | 50 + .../java/org/onap/policy/api/PolicyEngine.java | 602 +++++ .../org/onap/policy/api/PolicyEngineException.java | 49 + .../org/onap/policy/api/PolicyEventException.java | 49 + .../java/org/onap/policy/api/PolicyException.java | 29 + .../java/org/onap/policy/api/PolicyParameters.java | 557 ++++ .../java/org/onap/policy/api/PolicyResponse.java | 77 + .../org/onap/policy/api/PolicyResponseStatus.java | 85 + .../main/java/org/onap/policy/api/PolicyType.java | 72 + .../org/onap/policy/api/PushPolicyParameters.java | 131 + .../java/org/onap/policy/api/RuleProvider.java | 73 + .../java/org/onap/policy/api/package-info.java | 36 + .../org/onap/policy/models/APIConfigResponse.java | 37 + .../onap/policy/models/APIDictionaryResponse.java | 53 + .../policy/models/APIPolicyConfigResponse.java | 91 + .../java/org/onap/policy/std/AutoClientDMAAP.java | 132 + .../java/org/onap/policy/std/AutoClientEnd.java | 248 ++ .../java/org/onap/policy/std/AutoClientUEB.java | 178 ++ .../java/org/onap/policy/std/ManualClientEnd.java | 138 + .../org/onap/policy/std/ManualClientEndDMAAP.java | 107 + .../org/onap/policy/std/ManualClientEndUEB.java | 160 ++ .../main/java/org/onap/policy/std/MatchStore.java | 246 ++ .../src/main/java/org/onap/policy/std/Matches.java | 48 + .../org/onap/policy/std/NotificationUnMarshal.java | 69 + .../org/onap/policy/std/StdDecisionResponse.java | 55 + .../org/onap/policy/std/StdDictionaryResponse.java | 73 + .../org/onap/policy/std/StdMetricsResponse.java | 78 + .../onap/policy/std/StdPolicyChangeResponse.java | 47 + .../java/org/onap/policy/std/StdPolicyConfig.java | 168 ++ .../java/org/onap/policy/std/StdPolicyEngine.java | 1254 +++++++++ .../org/onap/policy/std/StdPolicyResponse.java | 98 + .../main/java/org/onap/policy/std/StdStatus.java | 235 ++ .../java/org/onap/policy/std/package-info.java | 27 + .../org/openecomp/policy/api/AttributeType.java | 78 - .../policy/api/ConfigRequestParameters.java | 148 -- .../policy/api/DecisionRequestParameters.java | 104 - .../org/openecomp/policy/api/DecisionResponse.java | 43 - .../policy/api/DeletePolicyCondition.java | 65 - .../policy/api/DeletePolicyParameters.java | 114 - .../openecomp/policy/api/DictionaryParameters.java | 82 - .../openecomp/policy/api/DictionaryResponse.java | 41 - .../org/openecomp/policy/api/DictionaryType.java | 100 - .../policy/api/EventRequestParameters.java | 89 - .../org/openecomp/policy/api/ImportParameters.java | 175 -- .../policy/api/MetricsRequestParameters.java | 21 - .../org/openecomp/policy/api/MetricsResponse.java | 45 - .../openecomp/policy/api/NotificationScheme.java | 61 - .../openecomp/policy/api/PolicyChangeResponse.java | 44 - .../java/org/openecomp/policy/api/PolicyClass.java | 67 - .../org/openecomp/policy/api/PolicyConfig.java | 123 - .../policy/api/PolicyConfigException.java | 49 - .../openecomp/policy/api/PolicyConfigStatus.java | 79 - .../org/openecomp/policy/api/PolicyConfigType.java | 87 - .../org/openecomp/policy/api/PolicyDecision.java | 68 - .../policy/api/PolicyDecisionException.java | 50 - .../org/openecomp/policy/api/PolicyEngine.java | 602 ----- .../policy/api/PolicyEngineException.java | 49 - .../openecomp/policy/api/PolicyEventException.java | 49 - .../org/openecomp/policy/api/PolicyException.java | 29 - .../org/openecomp/policy/api/PolicyParameters.java | 557 ---- .../org/openecomp/policy/api/PolicyResponse.java | 77 - .../openecomp/policy/api/PolicyResponseStatus.java | 85 - .../java/org/openecomp/policy/api/PolicyType.java | 72 - .../openecomp/policy/api/PushPolicyParameters.java | 131 - .../org/openecomp/policy/api/RuleProvider.java | 73 - .../org/openecomp/policy/api/package-info.java | 36 - .../openecomp/policy/models/APIConfigResponse.java | 37 - .../policy/models/APIDictionaryResponse.java | 53 - .../policy/models/APIPolicyConfigResponse.java | 91 - .../org/openecomp/policy/std/AutoClientDMAAP.java | 132 - .../org/openecomp/policy/std/AutoClientEnd.java | 248 -- .../org/openecomp/policy/std/AutoClientUEB.java | 178 -- .../org/openecomp/policy/std/ManualClientEnd.java | 138 - .../openecomp/policy/std/ManualClientEndDMAAP.java | 107 - .../openecomp/policy/std/ManualClientEndUEB.java | 160 -- .../java/org/openecomp/policy/std/MatchStore.java | 246 -- .../java/org/openecomp/policy/std/Matches.java | 48 - .../policy/std/NotificationUnMarshal.java | 69 - .../openecomp/policy/std/StdDecisionResponse.java | 55 - .../policy/std/StdDictionaryResponse.java | 73 - .../openecomp/policy/std/StdMetricsResponse.java | 78 - .../policy/std/StdPolicyChangeResponse.java | 47 - .../org/openecomp/policy/std/StdPolicyConfig.java | 168 -- .../org/openecomp/policy/std/StdPolicyEngine.java | 1254 --------- .../openecomp/policy/std/StdPolicyResponse.java | 98 - .../java/org/openecomp/policy/std/StdStatus.java | 235 -- .../org/openecomp/policy/std/package-info.java | 27 - PolicyEngineAPI/src/main/resources/logback.xml | 2 +- .../onap/policy/std/test/AutoClientEndTest.java | 228 ++ .../onap/policy/std/test/AutoClientUEBTest.java | 567 ++++ .../java/org/onap/policy/std/test/Handler.java | 126 + .../onap/policy/std/test/ManualClientEndTest.java | 126 + .../policy/std/test/ManualClientEndUEBTest.java | 119 + .../org/onap/policy/std/test/MatchStoreTest.java | 776 ++++++ .../java/org/onap/policy/std/test/MatchesTest.java | 216 ++ .../policy/std/test/NotificationStoreTest.java | 359 +++ .../policy/std/test/NotificationUnMarshalTest.java | 256 ++ .../onap/policy/std/test/StdLoadedPolicyTest.java | 314 +++ .../policy/std/test/StdPDPNotificationTest.java | 311 +++ .../std/test/StdPolicyChangeResponseTest.java | 166 ++ .../onap/policy/std/test/StdPolicyConfigTest.java | 821 ++++++ .../policy/std/test/StdPolicyResponseTest.java | 348 +++ .../onap/policy/std/test/StdRemovedPolicyTest.java | 206 ++ .../org/onap/policy/std/test/StdStatusTest.java | 1433 ++++++++++ .../org/onap/policy/std/test/package-info.java | 27 + .../org/onap/policy/test/ActionPolicyApiTest.java | 239 ++ .../org/onap/policy/test/AttributeTypeTest.java | 81 + .../org/onap/policy/test/ConfigBasePolicyTest.java | 325 +++ .../onap/policy/test/ConfigFirewallPolicyTest.java | 254 ++ .../policy/test/ConfigRequestParametersTest.java | 362 +++ .../onap/policy/test/DecisionPolicyApiTest.java | 219 ++ .../policy/test/DecisionRequestParametersTest.java | 232 ++ .../policy/test/DeletePolicyConditionTest.java | 91 + .../policy/test/DeletePolicyParametersTest.java | 314 +++ .../policy/test/EventRequestParametersTest.java | 193 ++ .../policy/test/GetConfigByPolicyNameTest.java | 63 + .../policy/test/GetConfigStringStringMapTest.java | 259 ++ .../policy/test/GetConfigStringStringTest.java | 213 ++ .../org/onap/policy/test/GetConfigStringTest.java | 170 ++ .../org/onap/policy/test/ImportParametersTest.java | 403 +++ .../org/onap/policy/test/LoadedPolicyTest.java | 72 + .../onap/policy/test/NotificationHandlerTest.java | 72 + .../onap/policy/test/NotificationSchemeTest.java | 91 + .../org/onap/policy/test/NotificationTypeTest.java | 91 + .../org/onap/policy/test/PDPNotificationTest.java | 72 + .../onap/policy/test/PolicyChangeResponseTest.java | 72 + .../java/org/onap/policy/test/PolicyClassTest.java | 91 + .../policy/test/PolicyConfigExceptionTest.java | 183 ++ .../onap/policy/test/PolicyConfigStatusTest.java | 133 + .../org/onap/policy/test/PolicyConfigTest.java | 72 + .../org/onap/policy/test/PolicyConfigTypeTest.java | 91 + .../policy/test/PolicyDecisionExceptionTest.java | 183 ++ .../org/onap/policy/test/PolicyDecisionTest.java | 91 + .../policy/test/PolicyEngineExceptionTest.java | 183 ++ .../policy/test/PolicyEngineInterfaceTest.java | 670 +++++ .../org/onap/policy/test/PolicyEngineTest.java | 170 ++ .../onap/policy/test/PolicyEventExceptionTest.java | 183 ++ .../org/onap/policy/test/PolicyParametersTest.java | 1409 ++++++++++ .../onap/policy/test/PolicyResponseStatusTest.java | 154 ++ .../org/onap/policy/test/PolicyResponseTest.java | 72 + .../java/org/onap/policy/test/PolicyTypeTest.java | 91 + .../onap/policy/test/PushPolicyParametersTest.java | 269 ++ .../org/onap/policy/test/RemovedPolicyTest.java | 72 + .../java/org/onap/policy/test/SendEventTest.java | 155 ++ .../test/java/org/onap/policy/test/TestRunner.java | 49 + .../java/org/onap/policy/test/UpdateTypeTest.java | 91 + .../java/org/onap/policy/test/package-info.java | 24 + .../policy/std/test/AutoClientEndTest.java | 228 -- .../policy/std/test/AutoClientUEBTest.java | 567 ---- .../org/openecomp/policy/std/test/Handler.java | 126 - .../policy/std/test/ManualClientEndTest.java | 126 - .../policy/std/test/ManualClientEndUEBTest.java | 119 - .../openecomp/policy/std/test/MatchStoreTest.java | 776 ------ .../org/openecomp/policy/std/test/MatchesTest.java | 216 -- .../policy/std/test/NotificationStoreTest.java | 359 --- .../policy/std/test/NotificationUnMarshalTest.java | 256 -- .../policy/std/test/StdLoadedPolicyTest.java | 314 --- .../policy/std/test/StdPDPNotificationTest.java | 311 --- .../std/test/StdPolicyChangeResponseTest.java | 166 -- .../policy/std/test/StdPolicyConfigTest.java | 821 ------ .../policy/std/test/StdPolicyResponseTest.java | 348 --- .../policy/std/test/StdRemovedPolicyTest.java | 206 -- .../openecomp/policy/std/test/StdStatusTest.java | 1433 ---------- .../openecomp/policy/std/test/package-info.java | 27 - .../openecomp/policy/test/ActionPolicyApiTest.java | 239 -- .../openecomp/policy/test/AttributeTypeTest.java | 81 - .../policy/test/ConfigBasePolicyTest.java | 325 --- .../policy/test/ConfigFirewallPolicyTest.java | 254 -- .../policy/test/ConfigRequestParametersTest.java | 362 --- .../policy/test/DecisionPolicyApiTest.java | 219 -- .../policy/test/DecisionRequestParametersTest.java | 232 -- .../policy/test/DeletePolicyConditionTest.java | 91 - .../policy/test/DeletePolicyParametersTest.java | 314 --- .../policy/test/EventRequestParametersTest.java | 193 -- .../policy/test/GetConfigByPolicyNameTest.java | 63 - .../policy/test/GetConfigStringStringMapTest.java | 259 -- .../policy/test/GetConfigStringStringTest.java | 213 -- .../openecomp/policy/test/GetConfigStringTest.java | 170 -- .../policy/test/ImportParametersTest.java | 403 --- .../openecomp/policy/test/LoadedPolicyTest.java | 72 - .../policy/test/NotificationHandlerTest.java | 72 - .../policy/test/NotificationSchemeTest.java | 91 - .../policy/test/NotificationTypeTest.java | 91 - .../openecomp/policy/test/PDPNotificationTest.java | 72 - .../policy/test/PolicyChangeResponseTest.java | 72 - .../org/openecomp/policy/test/PolicyClassTest.java | 91 - .../policy/test/PolicyConfigExceptionTest.java | 183 -- .../policy/test/PolicyConfigStatusTest.java | 133 - .../openecomp/policy/test/PolicyConfigTest.java | 72 - .../policy/test/PolicyConfigTypeTest.java | 91 - .../policy/test/PolicyDecisionExceptionTest.java | 183 -- .../openecomp/policy/test/PolicyDecisionTest.java | 91 - .../policy/test/PolicyEngineExceptionTest.java | 183 -- .../policy/test/PolicyEngineInterfaceTest.java | 670 ----- .../openecomp/policy/test/PolicyEngineTest.java | 170 -- .../policy/test/PolicyEventExceptionTest.java | 183 -- .../policy/test/PolicyParametersTest.java | 1409 ---------- .../policy/test/PolicyResponseStatusTest.java | 154 -- .../openecomp/policy/test/PolicyResponseTest.java | 72 - .../org/openecomp/policy/test/PolicyTypeTest.java | 91 - .../policy/test/PushPolicyParametersTest.java | 269 -- .../openecomp/policy/test/RemovedPolicyTest.java | 72 - .../org/openecomp/policy/test/SendEventTest.java | 155 -- .../java/org/openecomp/policy/test/TestRunner.java | 49 - .../org/openecomp/policy/test/UpdateTypeTest.java | 91 - .../org/openecomp/policy/test/package-info.java | 24 - PolicyEngineClient/input.testCases | 58 +- PolicyEngineClient/pom.xml | 6 +- .../org/onap/policyEngine/ActionPolicyClient.java | 111 + .../onap/policyEngine/BrmsParamPolicyClient.java | 96 + .../org/onap/policyEngine/BrmsRawPolicyClient.java | 131 + .../onap/policyEngine/ClosedLoopPolicyClient.java | 125 + .../ClosedLoopPolicyPerformanceMetricClient.java | 127 + .../onap/policyEngine/ConfigBasePolicyClient.java | 92 + .../policyEngine/ConfigFirewallPolicyClient.java | 119 + .../onap/policyEngine/DecisionPolicyClient.java | 114 + .../org/onap/policyEngine/DeletePolicyClient.java | 62 + .../org/onap/policyEngine/GeneralTestClient.java | 400 +++ .../org/onap/policyEngine/GetConfigSample.java | 41 + .../main/java/org/onap/policyEngine/Handler.java | 127 + .../org/onap/policyEngine/ImportBRMSTemplate.java | 30 + .../policyEngine/ImportMicroServiceClient.java | 53 + .../policyEngine/ListConfigPoliciesClient.java | 76 + .../java/org/onap/policyEngine/MainClient.java | 125 + .../policyEngine/MicroServicesPolicyClient.java | 127 + .../onap/policyEngine/PolicyEngineTestClient.java | 204 ++ .../org/onap/policyEngine/PushPoliciesToPDP.java | 59 + .../openecomp/policyEngine/ActionPolicyClient.java | 111 - .../policyEngine/BrmsParamPolicyClient.java | 96 - .../policyEngine/BrmsRawPolicyClient.java | 131 - .../policyEngine/ClosedLoopPolicyClient.java | 125 - .../ClosedLoopPolicyPerformanceMetricClient.java | 127 - .../policyEngine/ConfigBasePolicyClient.java | 92 - .../policyEngine/ConfigFirewallPolicyClient.java | 119 - .../policyEngine/DecisionPolicyClient.java | 114 - .../openecomp/policyEngine/DeletePolicyClient.java | 62 - .../openecomp/policyEngine/GeneralTestClient.java | 400 --- .../openecomp/policyEngine/GetConfigSample.java | 41 - .../java/org/openecomp/policyEngine/Handler.java | 127 - .../openecomp/policyEngine/ImportBRMSTemplate.java | 30 - .../policyEngine/ImportMicroServiceClient.java | 53 - .../policyEngine/ListConfigPoliciesClient.java | 76 - .../org/openecomp/policyEngine/MainClient.java | 125 - .../policyEngine/MicroServicesPolicyClient.java | 127 - .../policyEngine/PolicyEngineTestClient.java | 204 -- .../openecomp/policyEngine/PushPoliciesToPDP.java | 59 - PolicyEngineClient/testResources/test.drl | 4 +- PolicyEngineUtils/pom.xml | 12 +- .../java/org/onap/policy/api/LoadedPolicy.java | 57 + .../org/onap/policy/api/NotificationHandler.java | 34 + .../java/org/onap/policy/api/NotificationType.java | 58 + .../java/org/onap/policy/api/PDPNotification.java | 52 + .../java/org/onap/policy/api/PEDependency.java | 90 + .../java/org/onap/policy/api/RemovedPolicy.java | 41 + .../main/java/org/onap/policy/api/UpdateType.java | 54 + .../org/onap/policy/jpa/BackUpMonitorEntity.java | 117 + .../org/onap/policy/std/NotificationStore.java | 264 ++ .../java/org/onap/policy/std/StdLoadedPolicy.java | 72 + .../org/onap/policy/std/StdPDPNotification.java | 80 + .../java/org/onap/policy/std/StdRemovedPolicy.java | 49 + .../java/org/onap/policy/utils/AAFEnvironment.java | 29 + .../org/onap/policy/utils/AAFPolicyClient.java | 40 + .../org/onap/policy/utils/AAFPolicyClientImpl.java | 214 ++ .../org/onap/policy/utils/AAFPolicyException.java | 48 + .../java/org/onap/policy/utils/BackUpHandler.java | 41 + .../java/org/onap/policy/utils/BackUpMonitor.java | 422 +++ .../java/org/onap/policy/utils/BusConsumer.java | 99 + .../java/org/onap/policy/utils/BusPublisher.java | 119 + .../java/org/onap/policy/utils/PolicyAccess.java | 106 + .../java/org/onap/policy/utils/PolicyUtils.java | 201 ++ .../org/openecomp/policy/api/LoadedPolicy.java | 57 - .../openecomp/policy/api/NotificationHandler.java | 34 - .../org/openecomp/policy/api/NotificationType.java | 58 - .../org/openecomp/policy/api/PDPNotification.java | 52 - .../org/openecomp/policy/api/PEDependency.java | 90 - .../org/openecomp/policy/api/RemovedPolicy.java | 41 - .../java/org/openecomp/policy/api/UpdateType.java | 54 - .../openecomp/policy/jpa/BackUpMonitorEntity.java | 117 - .../openecomp/policy/std/NotificationStore.java | 264 -- .../org/openecomp/policy/std/StdLoadedPolicy.java | 72 - .../openecomp/policy/std/StdPDPNotification.java | 80 - .../org/openecomp/policy/std/StdRemovedPolicy.java | 49 - .../org/openecomp/policy/utils/AAFEnvironment.java | 29 - .../openecomp/policy/utils/AAFPolicyClient.java | 40 - .../policy/utils/AAFPolicyClientImpl.java | 214 -- .../openecomp/policy/utils/AAFPolicyException.java | 48 - .../org/openecomp/policy/utils/BackUpHandler.java | 41 - .../org/openecomp/policy/utils/BackUpMonitor.java | 422 --- .../org/openecomp/policy/utils/BusConsumer.java | 99 - .../org/openecomp/policy/utils/BusPublisher.java | 119 - .../org/openecomp/policy/utils/PolicyAccess.java | 106 - .../org/openecomp/policy/utils/PolicyUtils.java | 201 -- .../src/main/resources/META-INF/persistencePU.xml | 2 +- .../test/java/org/onap/policy/test/Handler.java | 38 + .../java/org/onap/policy/test/PolicyUtilsTest.java | 67 + .../org/onap/policy/test/testBackUpMonitor.java | 121 + .../java/org/openecomp/policy/test/Handler.java | 38 - .../org/openecomp/policy/test/PolicyUtilsTest.java | 67 - .../openecomp/policy/test/testBackUpMonitor.java | 121 - README.md | 2 +- packages/base/pom.xml | 28 +- packages/base/src/assembly/zip.xml | 2 +- packages/base/src/files/bin/backup.sh | 2 +- packages/base/src/files/bin/certtool.sh | 2 +- packages/base/src/files/bin/java/log4j.properties | 2 +- packages/base/src/files/bin/monitor.sh | 2 +- packages/base/src/files/bin/policy.sh | 2 +- packages/base/src/files/etc/profile.d/env.sh | 2 +- packages/base/src/files/install/elk/bin/elk.sh | 2 +- .../src/files/install/mysql/bin/cleanup_policy.sh | 2 +- .../base/src/files/install/mysql/bin/db_backup.sh | 6 +- .../src/files/install/mysql/bin/db_backup_data.sh | 2 +- .../files/install/mysql/bin/db_backup_remote.sh | 6 +- .../base/src/files/install/mysql/bin/db_restore.sh | 8 +- .../src/files/install/mysql/bin/db_restore_data.sh | 2 +- .../base/src/files/install/mysql/bin/db_upgrade.sh | 2 +- .../files/install/mysql/bin/db_upgrade_remote.sh | 2 +- .../install/mysql/data/161000_upgrade_script.sql | 80 +- .../install/mysql/data/170204_downgrade_script.sql | 4 +- .../install/mysql/data/170204_upgrade_script.sql | 4 +- .../install/mysql/data/170701_downgrade_script.sql | 4 +- .../install/mysql/data/170701_upgrade_script.sql | 6 +- .../install/mysql/data/171001_downgrade_script.sql | 4 +- .../install/mysql/data/171001_upgrade_script.sql | 8 +- .../files/install/servers/brmsgw/client.properties | 2 +- .../files/install/servers/brmsgw/config.properties | 2 +- .../servers/brmsgw/config/policyLogger.properties | 2 +- .../install/servers/common/tomcat/bin/setenv.sh | 2 +- .../install/servers/common/tomcat/conf/server.xml | 2 +- .../files/install/servers/configs/conf/server.xml | 2 +- .../install/servers/console/bin/Policy-Admin.xml | 2 +- .../console/bin/config/policyLogger.properties | 2 +- .../install/servers/console/bin/model.properties | 2 +- .../Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml | 18 +- .../Config_BRMS_Param_BRMSParamvLBDemoPolicy.1.xml | 18 +- .../admin/repository/com/Config_MS_vFirewall.1.xml | 24 +- .../repository/com/Config_MS_vLoadBalancer.1.xml | 24 +- .../servers/console/bin/xacml.admin.properties | 30 +- .../files/install/servers/console/conf/server.xml | 4 +- .../ecomp/WEB-INF/classes/portal.properties | 73 - .../servers/ecomp/WEB-INF/conf/system.properties | 84 - .../servers/onap/WEB-INF/classes/portal.properties | 73 + .../servers/onap/WEB-INF/conf/system.properties | 84 + .../install/servers/pap/bin/autopush.properties | 2 +- .../servers/pap/bin/config/policyLogger.properties | 2 +- ....Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml | 18 +- ....Config_BRMS_Param_BRMSParamvLBDemoPolicy.1.xml | 18 +- .../bin/pdps/default/com.Config_MS_vFirewall.1.xml | 24 +- .../pdps/default/com.Config_MS_vLoadBalancer.1.xml | 24 +- .../pap/bin/pdps/default/xacml.pip.properties | 2 +- .../files/install/servers/pap/bin/pip.properties | 4 +- .../install/servers/pap/bin/policyelk.properties | 2 +- .../files/install/servers/pap/bin/test.properties | 2 +- .../install/servers/pap/bin/xacml.pap.properties | 14 +- ....Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt | 4 +- ....Config_BRMS_Param_BRMSParamvLBDemoPolicy.1.txt | 8 +- .../paplp/bin/config/policyLogger.properties | 2 +- .../install/servers/paplp/bin/parserlog.properties | 2 +- .../install/servers/pdp/bin/client.properties | 2 +- .../servers/pdp/bin/config/policyLogger.properties | 2 +- .../install/servers/pdp/bin/xacml.pdp.properties | 12 +- .../pdplp/bin/config/policyLogger.properties | 2 +- .../install/servers/pdplp/bin/parserlog.properties | 2 +- packages/base/src/files/m2/settings.xml | 2 +- packages/install/pom.xml | 8 +- packages/install/src/assembly/zip.xml | 4 +- packages/install/src/files/brmsgw.conf | 6 +- packages/install/src/files/console.conf | 32 +- packages/pom.xml | 6 +- pom.xml | 34 +- project-configs/maven/conf/settings.xml | 2 +- 1845 files changed, 161068 insertions(+), 161066 deletions(-) create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSGateway.java create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSHandler.java create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/BRMSPush.java create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/ControllerPOJO.java create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/NotificationPOJO.java create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/jpa/BRMSGroupInfo.java create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/jpa/BRMSPolicyInfo.java create mode 100644 BRMSGateway/src/main/java/org/onap/policy/brmsInterface/jpa/DependencyInfo.java delete mode 100644 BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/BRMSGateway.java delete mode 100644 BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/BRMSHandler.java delete mode 100644 BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/BRMSPush.java delete mode 100644 BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/ControllerPOJO.java delete mode 100644 BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/NotificationPOJO.java delete mode 100644 BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/jpa/BRMSGroupInfo.java delete mode 100644 BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/jpa/BRMSPolicyInfo.java delete mode 100644 BRMSGateway/src/main/java/org/openecomp/policy/brmsInterface/jpa/DependencyInfo.java delete mode 100644 ECOMP-ASDC/pom.xml delete mode 100644 ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/Resource.java delete mode 100644 ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/ResourceInstance.java delete mode 100644 ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/ResourceType.java delete mode 100644 ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/Service.java delete mode 100644 ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/ServiceInstance.java delete mode 100644 ECOMP-ControlloopPolicy/pom.xml delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/CompilerException.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompiler.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompilerCallback.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/ControlLoop.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/ControlLoopPolicy.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/FinalResult.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/OperationsAccumulateParams.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/Policy.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/PolicyResult.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/Target.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/TargetType.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/BuilderException.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/Message.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/MessageLevel.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/Results.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/MessageImpl.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/ResultsImpl.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopParameter.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Guard.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/MatchParameters.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java delete mode 100644 ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java delete mode 100644 ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompilerTest.java delete mode 100644 ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java delete mode 100644 ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java delete mode 100644 ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/ControlLoopPolicyTest.java delete mode 100644 ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java delete mode 100644 ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardTest.java delete mode 100644 ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-59a2ee3fB58045feB5a1-template.yml delete mode 100644 ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-Eace933104d443b496b8-template.yml delete mode 100644 ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-57e66ea70ed645c7970f-template.yml delete mode 100644 ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-D473899264974dca9db9-template.yml delete mode 100644 ECOMP-PAP-REST/autopush.properties delete mode 100644 ECOMP-PAP-REST/dictionaryItemsAPI.json delete mode 100644 ECOMP-PAP-REST/pip.properties delete mode 100644 ECOMP-PAP-REST/policyLogger.properties delete mode 100644 ECOMP-PAP-REST/policyelk.properties delete mode 100644 ECOMP-PAP-REST/pom.xml delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/PAPRestConfig.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/WebConfig.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/adapters/GridData.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/adapters/package-info.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/AutoPushPolicy.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ClosedLoopPolicy.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ConfigPolicy.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/FirewallConfigPolicy.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/Policy.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDao.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/package-info.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/BRMSDictionaryController.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryController.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryImportController.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/EnforcerDictionaryController.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/FirewallDictionaryController.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PushPolicyController.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/SafePolicyController.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/package-info.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnector.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/Pair.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticData.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyLocator.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/APIRequestHandler.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandler.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/PushPolicyHandler.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/SavePolicyHandler.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/model/PDPPolicyContainer.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/model/RemoveGroupPolicy.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/model/package-info.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/package-info.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/DictionaryService.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/ImportService.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/MetricService.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/AbstractPolicyCreation.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/JPAUtils.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/JsonMessage.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/PolicyContainer.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/PolicyItemSetChangeNotifier.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/restAuth/AuthenticationService.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/restAuth/CheckPDP.java delete mode 100644 ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java delete mode 100644 ECOMP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml delete mode 100644 ECOMP-PAP-REST/src/main/resources/Decision_GuardPolicyTemplate.xml delete mode 100644 ECOMP-PAP-REST/src/main/resources/META-INF/generatedCreate.ddl delete mode 100644 ECOMP-PAP-REST/src/main/resources/META-INF/generatedDrop.ddl delete mode 100644 ECOMP-PAP-REST/src/main/resources/META-INF/persistence.xml delete mode 100644 ECOMP-PAP-REST/src/main/resources/log4j.properties delete mode 100644 ECOMP-PAP-REST/src/main/resources/logback.xml delete mode 100644 ECOMP-PAP-REST/src/main/resources/spring.xml delete mode 100644 ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/ia/DbAuditCompareEntriesTest.java delete mode 100644 ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDaoTest.java delete mode 100644 ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryControllerTest.java delete mode 100644 ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java delete mode 100644 ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/jpa/PolicyEntityTest.java delete mode 100644 ECOMP-PAP-REST/test.properties delete mode 100644 ECOMP-PAP-REST/xacml.pap.properties delete mode 100644 ECOMP-PAP-REST/xacml.pap.test.properties delete mode 100644 ECOMP-PDP-REST/config/policyLogger.properties delete mode 100644 ECOMP-PDP-REST/policyLogger.properties delete mode 100644 ECOMP-PDP-REST/pom.xml delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpRegisterThread.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpServlet.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/controller/PolicyEngineServices.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigFirewallPolicyAPIRequest.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigNameRequest.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigPolicyAPIRequest.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PDPResponse.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PolicyConfig.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ActionPolicyService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSParamPolicyService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSRawPolicyService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ConfigPolicyService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DecisionPolicyService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DeletePolicyService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/FirewallPolicyService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetConfigService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDecisionService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDictionaryService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetMetricsService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ListConfigService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/MicroServicesPolicyService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/NotificationService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PDPServices.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PushPolicyService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/SendEventService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/utils/PolicyApiUtils.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPRestConfig.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPRestInitializer.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPIPFinderFactory.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPolicyFinderFactory.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMBeanListener.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMonitor.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMonitorMBean.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Notification.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationController.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Removed.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Updated.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/package-info.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/AuthenticationService.java delete mode 100644 ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java delete mode 100644 ECOMP-PDP-REST/src/main/resources/log4j.properties delete mode 100644 ECOMP-PDP-REST/src/main/resources/logback.xml delete mode 100644 ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/PapUrlResolverTest.java delete mode 100644 ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/XACMLPdpServletTest.java delete mode 100644 ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/services/PDPServicesTest.java delete mode 100644 ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/NotificationAPITest.java delete mode 100644 ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/PolicyEngineServicesTest.java delete mode 100644 ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/getConfigTest.java delete mode 100644 ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/getDictionaryTest.java delete mode 100644 ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/auth/test/FilterTests.java delete mode 100644 ECOMP-PDP-REST/src/test/resources/fail.xacml.pdp.properties delete mode 100644 ECOMP-PDP-REST/src/test/resources/pass.xacml.pdp.properties delete mode 100644 ECOMP-PDP-REST/src/test/resources/test.drl delete mode 100644 ECOMP-PDP-REST/xacml.pdp.properties delete mode 100644 ECOMP-PDP/config_testing/test_PolicyEngine.xml delete mode 100644 ECOMP-PDP/config_testing/xacml.pip.properties delete mode 100644 ECOMP-PDP/config_testing/xacml.policy.properties delete mode 100644 ECOMP-PDP/logging.properties delete mode 100644 ECOMP-PDP/policyLogger.properties delete mode 100644 ECOMP-PDP/pom.xml delete mode 100644 ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/action/FindAction.java delete mode 100644 ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/action/package-info.java delete mode 100644 ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/custom/EcompFunctionDefinitionFactory.java delete mode 100644 ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/pdp/ECOMPPDPEngine.java delete mode 100644 ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/pdp/ECOMPPDPEngineFactory.java delete mode 100644 ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatch.java delete mode 100644 ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/pdp/std/functions/PolicyList.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionAccessPermittedTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionArithmeticTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagIsInTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagOneAndOnlyTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagSizeTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBaseTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionComparisonTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionDateTimeArithmeticTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionEqualityTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionHigherOrderBagTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionHomogeneousSimpleTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionLogicalTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionNumberTypeConversionTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionRegexpMatchTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionSetTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionSpecialMatchTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringConversionTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringEqualIgnoreCaseTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringFunctionsTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringNormalizeTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionURIStringConcatenateTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionXPathTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/PDPTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/TestRunner.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/Conformance.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformancePIPEngine.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceRepository.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceScopeResolver.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTest.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTestEngine.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTestResult.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTestSet.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ResponseMatchResult.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ResultMatchResult.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/CustomDataTypeFactory.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/CustomFunctionDefinitionFactory.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/DataTypePrivateKey.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/DataTypePublicKey.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/FunctionDefinitionDecrypt.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/TestBase.java delete mode 100644 ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/TestCustom.java delete mode 100644 ECOMP-PDP/src/test/resources/CSVPolicy.xml delete mode 100644 ECOMP-PDP/src/test/resources/log4j.properties delete mode 100644 ECOMP-PDP/src/test/resources/logback.xml delete mode 100644 ECOMP-PDP/src/test/resources/logging.properties delete mode 100644 ECOMP-PDP/src/test/resources/xacml.pip.properties delete mode 100644 ECOMP-PDP/src/test/resources/xacml.policy.properties delete mode 100644 ECOMP-PDP/testclient.properties delete mode 100644 ECOMP-PDP/testpdp.properties delete mode 100644 ECOMP-PDP/xacml.pap.properties delete mode 100644 ECOMP-PDP/xacml.pdp.properties delete mode 100644 ECOMP-PDP/xacml.properties delete mode 100644 ECOMP-REST/policyLogger.properties delete mode 100644 ECOMP-REST/pom.xml delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/XACMLRest.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/XACMLRestProperties.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/XacmlAdminAuthorization.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AddressGroupJson.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AddressJson.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AddressMembers.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AutoPushTabAdapter.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopFaultBody.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopFaultTriggerUISignatures.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPMBody.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPerformanceMetrics.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPolicy.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPolicyConditions.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPolicyStatus.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopSignatures.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/DeletePolicyCondition.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/DeployNowJson.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/GridData.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/IdMap.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PolicyExportAdapter.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PolicyRestAdapter.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PrefixIPList.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/RainyDayParams.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServiceGroupJson.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServiceListJson.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServiceMembers.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServicesJson.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/TagDefines.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/Tags.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/Term.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/TermCollector.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/VendorSpecificData.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/package-info.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/dao/CommonClassDao.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/dao/package-info.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ActionBodyEntity.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ActionList.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ActionPolicyDict.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/AddressGroup.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Attribute.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/AttributeAssignment.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/BRMSController.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/BRMSDependency.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/BRMSParamTemplate.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Category.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ClosedLoopD2Services.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ClosedLoopSite.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ClosedLoops.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ConfigurationDataEntity.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ConstraintType.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ConstraintValue.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DCAEUsers.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DCAEuuid.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DatabaseLockEntity.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Datatype.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DecisionSettings.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DescriptiveScope.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/EcompName.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/EnforcingType.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FWTag.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FWTagPicker.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FirewallDictionaryList.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FunctionArgument.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FunctionDefinition.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GlobalRoleSettings.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GroupEntity.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GroupPolicyScopeList.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GroupServiceList.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceAttribute.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceConfigName.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceLocation.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceModels.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Obadvice.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ObadviceExpression.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PEPOptions.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPConfigParam.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPConfiguration.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPResolver.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPResolverParam.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPType.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PdpEntity.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyAlgorithms.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyDBDaoEntity.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyEditorScopes.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyEntity.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyGroupEntity.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyManagement.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyRoles.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeClosedLoop.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeResource.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeService.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeType.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScore.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyVersion.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PortList.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PrefixList.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ProtocolList.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RainyDayTreatments.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RemoteCatalogValues.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RiskType.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RuleAlgorithms.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/SafePolicyWarning.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/SecurityZone.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ServiceList.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/SystemLogDB.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/TermList.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/UserInfo.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VMType.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VNFType.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VSCLAction.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VarbindDictionary.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/WatchPolicyNotificationTable.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Zone.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/package-info.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/LockdownListener.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSAttributeObject.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSAttributeValue.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSModelUtils.java delete mode 100644 ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/Webapps.java delete mode 100644 ECOMP-REST/src/test/java/org/openecomp/policy/rest/XACMLRestTest.java delete mode 100644 ECOMP-SDK-APP/README.md delete mode 100644 ECOMP-SDK-APP/policyLogger.properties delete mode 100644 ECOMP-SDK-APP/pom.xml delete mode 100644 ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java delete mode 100644 ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java delete mode 100644 ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java delete mode 100644 ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/lm/FusionLicenseManagerImpl.java delete mode 100644 ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/lm/LicenseableClassImpl.java delete mode 100644 ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/login/LoginStrategyImpl.java delete mode 100644 ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/scheduler/Register.java delete mode 100644 ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java delete mode 100644 ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java delete mode 100644 ECOMP-SDK-APP/src/main/resources/logback.xml delete mode 100644 ECOMP-SDK-APP/src/main/resources/portal.properties delete mode 100644 ECOMP-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties delete mode 100644 ECOMP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/left-menu.jsp delete mode 100644 ECOMP-SDK-APP/src/main/webapp/WEB-INF/fusion/orm/RNoteBookIntegration.hbm.xml delete mode 100644 ECOMP-SDK-APP/src/main/webapp/WEB-INF/index.jsp delete mode 100644 ECOMP-SDK-APP/src/main/webapp/WEB-INF/jsp/login.jsp delete mode 100644 ECOMP-SDK-APP/src/main/webapp/WEB-INF/jsp/login_external.jsp delete mode 100644 ECOMP-SDK-APP/src/main/webapp/WEB-INF/web.xml delete mode 100644 ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-samplePages/samplePage.html delete mode 100644 ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/footer.html delete mode 100644 ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/utils/page-resource-ds2.js delete mode 100644 ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/view-models/footer.html delete mode 100644 ECOMP-SDK-APP/src/main/webapp/static/fusion/css/att_angular_gridster/ui-gridster.css delete mode 100644 ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/worddata.csv delete mode 100644 ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/wordcloud.html delete mode 100644 ECOMP-SDK-APP/xacml.admin.properties delete mode 100644 ECOMP-XACML/config_testing/test_PolicyEngine.xml delete mode 100644 ECOMP-XACML/config_testing/xacml.pip.properties delete mode 100644 ECOMP-XACML/config_testing/xacml.policy.properties delete mode 100644 ECOMP-XACML/policyLogger.properties delete mode 100644 ECOMP-XACML/pom.xml delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/XACMLErrorConstants.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/ECOMPPapEngineFactory.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/EcompPAPPolicy.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/EcompPDP.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/EcompPDPGroup.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/PAPPolicyEngine.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdEngine.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdEngineFactory.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPAPPolicy.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDP.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPGroup.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPGroupStatus.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPPIPConfig.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPPolicy.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPStatus.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pip/engines/OperationHistoryEngine.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pip/engines/aaf/AAFEngine.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/util/MetricsUtil.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/util/XACMLPolicyScanner.java delete mode 100644 ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/util/XACMLPolicyWriter.java delete mode 100644 ECOMP-XACML/src/main/resources/xacml.properties delete mode 100644 ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/std/pap/StdEngineFactoryTest.java delete mode 100644 ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/AAFEngineTest.java delete mode 100644 ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/MetricsUtilTest.java delete mode 100644 ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/XACMLPolicyScannerTest.java delete mode 100644 ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/XACMLPolicyWriterTest.java delete mode 100644 ECOMP-XACML/src/test/resources/Action_TestActionPolicy.1.xml delete mode 100644 ECOMP-XACML/src/test/resources/CSVPolicy.xml delete mode 100644 ECOMP-XACML/src/test/resources/Config_SampleTest1206.1.xml delete mode 100644 ECOMP-XACML/src/test/resources/log4j.properties delete mode 100644 ECOMP-XACML/src/test/resources/logback.xml delete mode 100644 ECOMP-XACML/src/test/resources/logging.properties delete mode 100644 ECOMP-XACML/src/test/resources/pdps/default/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml delete mode 100644 ECOMP-XACML/src/test/resources/pdps/default/xacml.pip.properties delete mode 100644 ECOMP-XACML/src/test/resources/xacml.pip.properties delete mode 100644 ECOMP-XACML/src/test/resources/xacml.policy.properties delete mode 100644 ECOMP-XACML/testclient.properties delete mode 100644 ECOMP-XACML/testpdp.properties delete mode 100644 ECOMP-XACML/xacml.pap.properties delete mode 100644 ECOMP-XACML/xacml.pdp.properties delete mode 100644 ECOMP-XACML/xacml.properties create mode 100644 LogParser/src/main/java/org/onap/xacml/parser/LogEntryObject.java create mode 100644 LogParser/src/main/java/org/onap/xacml/parser/ParseLog.java delete mode 100644 LogParser/src/main/java/org/openecomp/xacml/parser/LogEntryObject.java delete mode 100644 LogParser/src/main/java/org/openecomp/xacml/parser/ParseLog.java create mode 100644 LogParser/src/test/java/org/onap/xacml/parser/ParseLogTest.java delete mode 100644 LogParser/src/test/java/org/openecomp/xacml/parser/ParseLogTest.java create mode 100644 ONAP-ASDC/pom.xml create mode 100644 ONAP-ASDC/src/main/java/org/onap/policy/asdc/Resource.java create mode 100644 ONAP-ASDC/src/main/java/org/onap/policy/asdc/ResourceInstance.java create mode 100644 ONAP-ASDC/src/main/java/org/onap/policy/asdc/ResourceType.java create mode 100644 ONAP-ASDC/src/main/java/org/onap/policy/asdc/Service.java create mode 100644 ONAP-ASDC/src/main/java/org/onap/policy/asdc/ServiceInstance.java rename {ECOMP-ASDC => ONAP-ASDC}/src/main/resources/definitions.yaml (100%) create mode 100644 ONAP-ControlloopPolicy/pom.xml create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/compiler/CompilerException.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerCallback.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/Policy.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/Target.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/TargetType.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/BuilderException.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/Message.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/MessageLevel.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/Results.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/impl/MessageImpl.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ResultsImpl.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopParameter.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java create mode 100644 ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java create mode 100644 ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java create mode 100644 ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java create mode 100644 ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java create mode 100644 ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyTest.java create mode 100644 ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java create mode 100644 ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java rename {ECOMP-ControlloopPolicy => ONAP-ControlloopPolicy}/src/test/resources/v1.0.0/bad_policies_1.yaml (100%) rename {ECOMP-ControlloopPolicy => ONAP-ControlloopPolicy}/src/test/resources/v1.0.0/bad_trigger_1.yaml (100%) rename {ECOMP-ControlloopPolicy => ONAP-ControlloopPolicy}/src/test/resources/v1.0.0/bad_trigger_2.yaml (100%) rename {ECOMP-ControlloopPolicy => ONAP-ControlloopPolicy}/src/test/resources/v1.0.0/policy_OpenLoop_1610.yaml (100%) rename {ECOMP-ControlloopPolicy => ONAP-ControlloopPolicy}/src/test/resources/v1.0.0/policy_Test.yaml (100%) rename {ECOMP-ControlloopPolicy => ONAP-ControlloopPolicy}/src/test/resources/v1.0.0/policy_Test_MultipleService.yaml (100%) rename {ECOMP-ControlloopPolicy => ONAP-ControlloopPolicy}/src/test/resources/v1.0.0/test.yaml (100%) rename {ECOMP-ControlloopPolicy => ONAP-ControlloopPolicy}/src/test/resources/v1.0.0/test_evil.yaml (100%) rename {ECOMP-ControlloopPolicy => ONAP-ControlloopPolicy}/src/test/resources/v2.0.0-guard/duplicate_guard_constraint.yaml (100%) rename {ECOMP-ControlloopPolicy => ONAP-ControlloopPolicy}/src/test/resources/v2.0.0-guard/duplicate_guard_policy.yaml (100%) rename {ECOMP-ControlloopPolicy => ONAP-ControlloopPolicy}/src/test/resources/v2.0.0-guard/no_guard_constraint.yaml (100%) rename {ECOMP-ControlloopPolicy => ONAP-ControlloopPolicy}/src/test/resources/v2.0.0-guard/no_guard_policy.yaml (100%) rename {ECOMP-ControlloopPolicy => ONAP-ControlloopPolicy}/src/test/resources/v2.0.0-guard/policy_guard_1707_appc.yaml (100%) rename ECOMP-ControlloopPolicy/src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml => ONAP-ControlloopPolicy/src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml (100%) create mode 100644 ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-59a2ee3fB58045feB5a1-template.yml create mode 100644 ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-Eace933104d443b496b8-template.yml create mode 100644 ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-57e66ea70ed645c7970f-template.yml create mode 100644 ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-D473899264974dca9db9-template.yml rename {ECOMP-ControlloopPolicy => ONAP-ControlloopPolicy}/src/test/resources/v2.0.0/pgstreams.json (100%) rename ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/policy_OpenECOMP_demo_vDNS.yaml => ONAP-ControlloopPolicy/src/test/resources/v2.0.0/policy_ONAP_demo_vDNS.yaml (100%) rename ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/policy_OpenECOMP_demo_vFirewall.yaml => ONAP-ControlloopPolicy/src/test/resources/v2.0.0/policy_ONAP_demo_vFirewall.yaml (100%) rename {ECOMP-PAP-REST => ONAP-PAP-REST}/.gitignore (100%) rename {ECOMP-PAP-REST => ONAP-PAP-REST}/WebContent/META-INF/MANIFEST.MF (100%) rename {ECOMP-PAP-REST => ONAP-PAP-REST}/WebContent/README.txt (100%) create mode 100644 ONAP-PAP-REST/autopush.properties create mode 100644 ONAP-PAP-REST/dictionaryItemsAPI.json create mode 100644 ONAP-PAP-REST/pip.properties create mode 100644 ONAP-PAP-REST/policyLogger.properties create mode 100644 ONAP-PAP-REST/policyelk.properties create mode 100644 ONAP-PAP-REST/pom.xml create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/WebConfig.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/GridData.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/package-info.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/AutoPushPolicy.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/package-info.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/EnforcerDictionaryController.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyController.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/package-info.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/PDPPolicyContainer.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/package-info.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/package-info.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/PolicyContainer.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/PolicyItemSetChangeNotifier.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java create mode 100644 ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java create mode 100644 ONAP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml create mode 100644 ONAP-PAP-REST/src/main/resources/Decision_GuardPolicyTemplate.xml rename {ECOMP-PAP-REST => ONAP-PAP-REST}/src/main/resources/META-INF/drop.ddl (100%) create mode 100644 ONAP-PAP-REST/src/main/resources/META-INF/generatedCreate.ddl create mode 100644 ONAP-PAP-REST/src/main/resources/META-INF/generatedDrop.ddl create mode 100644 ONAP-PAP-REST/src/main/resources/META-INF/persistence.xml create mode 100644 ONAP-PAP-REST/src/main/resources/log4j.properties create mode 100644 ONAP-PAP-REST/src/main/resources/logback.xml create mode 100644 ONAP-PAP-REST/src/main/resources/spring.xml create mode 100644 ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java create mode 100644 ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java create mode 100644 ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java create mode 100644 ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java create mode 100644 ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java create mode 100644 ONAP-PAP-REST/test.properties create mode 100644 ONAP-PAP-REST/xacml.pap.properties create mode 100644 ONAP-PAP-REST/xacml.pap.test.properties rename {ECOMP-PDP-REST => ONAP-PDP-REST}/.gitignore (100%) rename {ECOMP-PDP-REST => ONAP-PDP-REST}/WebContent/META-INF/MANIFEST.MF (100%) rename {ECOMP-PDP-REST => ONAP-PDP-REST}/WebContent/WEB-INF/.gitignore (100%) rename {ECOMP-PDP-REST => ONAP-PDP-REST}/client.properties (100%) create mode 100644 ONAP-PDP-REST/config/policyLogger.properties rename {ECOMP-PDP-REST => ONAP-PDP-REST}/config/xacml.pip.properties (100%) rename {ECOMP-PDP-REST => ONAP-PDP-REST}/config/xacml.policy.properties (100%) create mode 100644 ONAP-PDP-REST/policyLogger.properties create mode 100644 ONAP-PDP-REST/pom.xml create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpLoader.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/controller/PolicyEngineServices.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/ConfigFirewallPolicyAPIRequest.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/ConfigNameRequest.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/ConfigPolicyAPIRequest.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/PDPResponse.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/PolicyConfig.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ActionPolicyService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/BRMSParamPolicyService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/BRMSRawPolicyService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ConfigPolicyService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DecisionPolicyService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/FirewallPolicyService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetConfigService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDecisionService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDictionaryService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetMetricsService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ListConfigService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/MicroServicesPolicyService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/NotificationService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PushPolicyService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/SendEventService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/utils/PolicyApiUtils.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPApiAuth.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestConfig.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestInitializer.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/impl/XACMLPdpPIPFinderFactory.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/impl/XACMLPdpPolicyFinderFactory.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/jmx/PdpRestMBeanListener.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/jmx/PdpRestMonitor.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/jmx/PdpRestMonitorMBean.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/Notification.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationController.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationServer.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/Removed.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/Updated.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/package-info.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/AuthenticationService.java create mode 100644 ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java create mode 100644 ONAP-PDP-REST/src/main/resources/log4j.properties create mode 100644 ONAP-PDP-REST/src/main/resources/logback.xml create mode 100644 ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/PapUrlResolverTest.java create mode 100644 ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/XACMLPdpServletTest.java create mode 100644 ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/services/PDPServicesTest.java create mode 100644 ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/NotificationAPITest.java create mode 100644 ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java create mode 100644 ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/getConfigTest.java create mode 100644 ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/getDictionaryTest.java create mode 100644 ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/FilterTests.java rename {ECOMP-PDP-REST => ONAP-PDP-REST}/src/test/resources/client.properties (100%) create mode 100644 ONAP-PDP-REST/src/test/resources/fail.xacml.pdp.properties create mode 100644 ONAP-PDP-REST/src/test/resources/pass.xacml.pdp.properties create mode 100644 ONAP-PDP-REST/src/test/resources/test.drl create mode 100644 ONAP-PDP-REST/xacml.pdp.properties rename {ECOMP-PDP => ONAP-PDP}/.gitignore (100%) create mode 100644 ONAP-PDP/config_testing/test_PolicyEngine.xml create mode 100644 ONAP-PDP/config_testing/xacml.pip.properties create mode 100644 ONAP-PDP/config_testing/xacml.policy.properties create mode 100644 ONAP-PDP/logging.properties create mode 100644 ONAP-PDP/policyLogger.properties create mode 100644 ONAP-PDP/pom.xml rename {ECOMP-PDP => ONAP-PDP}/sql/xacmlTest.mv.db (100%) create mode 100644 ONAP-PDP/src/main/java/org/onap/policy/xacml/action/FindAction.java create mode 100644 ONAP-PDP/src/main/java/org/onap/policy/xacml/action/package-info.java create mode 100644 ONAP-PDP/src/main/java/org/onap/policy/xacml/custom/OnapFunctionDefinitionFactory.java create mode 100644 ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/ONAPPDPEngine.java create mode 100644 ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/ONAPPDPEngineFactory.java create mode 100644 ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatch.java create mode 100644 ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/std/functions/PolicyList.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionAccessPermittedTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionArithmeticTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagIsInTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagOneAndOnlyTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagSizeTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBaseTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionComparisonTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionDateTimeArithmeticTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionEqualityTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionHigherOrderBagTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionHomogeneousSimpleTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionLogicalTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionNumberTypeConversionTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionRegexpMatchTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionSetTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionSpecialMatchTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringConversionTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringEqualIgnoreCaseTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringFunctionsTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringNormalizeTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionURIStringConcatenateTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionXPathTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/PDPTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/TestRunner.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/Conformance.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformancePIPEngine.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceRepository.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceScopeResolver.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTest.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTestEngine.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTestResult.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTestSet.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ResponseMatchResult.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ResultMatchResult.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/CustomDataTypeFactory.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/CustomFunctionDefinitionFactory.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/DataTypePrivateKey.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/DataTypePublicKey.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/FunctionDefinitionDecrypt.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/TestBase.java create mode 100644 ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/TestCustom.java create mode 100644 ONAP-PDP/src/test/resources/CSVPolicy.xml create mode 100644 ONAP-PDP/src/test/resources/log4j.properties create mode 100644 ONAP-PDP/src/test/resources/logback.xml create mode 100644 ONAP-PDP/src/test/resources/logging.properties create mode 100644 ONAP-PDP/src/test/resources/xacml.pip.properties create mode 100644 ONAP-PDP/src/test/resources/xacml.policy.properties create mode 100644 ONAP-PDP/testclient.properties create mode 100644 ONAP-PDP/testpdp.properties create mode 100644 ONAP-PDP/xacml.pap.properties create mode 100644 ONAP-PDP/xacml.pdp.properties create mode 100644 ONAP-PDP/xacml.properties rename {ECOMP-REST => ONAP-REST}/.gitignore (100%) create mode 100644 ONAP-REST/policyLogger.properties create mode 100644 ONAP-REST/pom.xml create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRest.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRestProperties.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/XacmlAdminAuthorization.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AddressGroupJson.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AddressJson.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AddressMembers.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AutoPushTabAdapter.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopFaultBody.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopFaultTriggerUISignatures.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPMBody.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPerformanceMetrics.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPolicy.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPolicyConditions.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPolicyStatus.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopSignatures.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/DeletePolicyCondition.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/DeployNowJson.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/GridData.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/IdMap.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyExportAdapter.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PrefixIPList.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/RainyDayParams.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServiceGroupJson.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServiceListJson.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServiceMembers.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServicesJson.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/TagDefines.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/Tags.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/Term.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/TermCollector.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/VendorSpecificData.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/YAMLParams.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/adapter/package-info.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/dao/CommonClassDao.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/dao/package-info.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionBodyEntity.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionList.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionPolicyDict.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/AddressGroup.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Attribute.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/AttributeAssignment.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BRMSController.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BRMSDependency.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BRMSParamTemplate.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Category.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ClosedLoopD2Services.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ClosedLoopSite.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ClosedLoops.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConfigurationDataEntity.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConstraintType.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConstraintValue.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DCAEUsers.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DCAEuuid.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DatabaseLockEntity.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Datatype.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DecisionSettings.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DescriptiveScope.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/EnforcingType.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FWTag.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FWTagPicker.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FirewallDictionaryList.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FunctionArgument.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FunctionDefinition.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GlobalRoleSettings.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GroupEntity.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GroupPolicyScopeList.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GroupServiceList.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceAttribute.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceConfigName.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceLocation.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceModels.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Obadvice.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ObadviceExpression.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/OnapName.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PEPOptions.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPConfigParam.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPConfiguration.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPResolver.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPResolverParam.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPType.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PdpEntity.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyAlgorithms.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyDBDaoEntity.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyEditorScopes.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyEntity.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyGroupEntity.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyManagement.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyRoles.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeClosedLoop.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeResource.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeService.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeType.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScore.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyVersion.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PortList.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PrefixList.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ProtocolList.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RainyDayTreatments.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RemoteCatalogValues.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RiskType.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RuleAlgorithms.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SafePolicyWarning.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SecurityZone.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ServiceList.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SystemLogDB.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/TermList.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/UserInfo.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VMType.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VNFType.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VSCLAction.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VarbindDictionary.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/WatchPolicyNotificationTable.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Zone.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/jpa/package-info.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/util/LockdownListener.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeObject.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeValue.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/util/MSModelUtils.java create mode 100644 ONAP-REST/src/main/java/org/onap/policy/rest/util/Webapps.java create mode 100644 ONAP-REST/src/test/java/org/onap/policy/rest/XACMLRestTest.java rename {ECOMP-SDK-APP => ONAP-SDK-APP}/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/.gitignore (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/JSONConfig.json (100%) create mode 100644 ONAP-SDK-APP/README.md rename {ECOMP-SDK-APP => ONAP-SDK-APP}/distribution.xml (100%) create mode 100644 ONAP-SDK-APP/policyLogger.properties create mode 100644 ONAP-SDK-APP/pom.xml create mode 100644 ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java create mode 100644 ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java create mode 100644 ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/HibernateMappingLocations.java create mode 100644 ONAP-SDK-APP/src/main/java/org/onap/portalapp/lm/FusionLicenseManagerImpl.java create mode 100644 ONAP-SDK-APP/src/main/java/org/onap/portalapp/lm/LicenseableClassImpl.java create mode 100644 ONAP-SDK-APP/src/main/java/org/onap/portalapp/login/LoginStrategyImpl.java create mode 100644 ONAP-SDK-APP/src/main/java/org/onap/portalapp/scheduler/Register.java create mode 100644 ONAP-SDK-APP/src/main/java/org/onap/portalapp/scheduler/RegistryAdapter.java create mode 100644 ONAP-SDK-APP/src/main/java/org/onap/portalapp/service/AdminAuthExtension.java create mode 100644 ONAP-SDK-APP/src/main/resources/logback.xml create mode 100644 ONAP-SDK-APP/src/main/resources/portal.properties create mode 100644 ONAP-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/WEB-INF/defs/definitions.xml (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/WEB-INF/fusion/conf/fusion.properties (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/WEB-INF/fusion/jsp/ds2/footer.jsp (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/WEB-INF/fusion/jsp/ds2/header.jsp (100%) create mode 100644 ONAP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/left-menu.jsp create mode 100644 ONAP-SDK-APP/src/main/webapp/WEB-INF/fusion/orm/RNoteBookIntegration.hbm.xml create mode 100644 ONAP-SDK-APP/src/main/webapp/WEB-INF/index.jsp create mode 100644 ONAP-SDK-APP/src/main/webapp/WEB-INF/jsp/login.jsp create mode 100644 ONAP-SDK-APP/src/main/webapp/WEB-INF/jsp/login_external.jsp create mode 100644 ONAP-SDK-APP/src/main/webapp/WEB-INF/web.xml rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/font_icons.css (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/app/fusion/external/ds2/css/digital-ng-library/ionicons.css (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.eot (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.svg (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.ttf (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.woff (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/app/fusion/scripts/DS2-controllers/ds-profile/post-controller.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/app/fusion/scripts/DS2-controllers/samplePage-route.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/app/fusion/scripts/DS2-services/postSearch.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-profile/post.html (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-profile/profile_searchDS2.html (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-profile/self_profile.html (100%) create mode 100644 ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-samplePages/samplePage.html create mode 100644 ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/footer.html create mode 100644 ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/utils/page-resource-ds2.js create mode 100644 ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/view-models/footer.html rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/css/att_angular_gridster/sandbox-gridster.css (100%) create mode 100644 ONAP-SDK-APP/src/main/webapp/static/fusion/css/att_angular_gridster/ui-gridster.css rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/css/fusion-sunny.css (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/images/att_angular_gridster/grips.png (100%) rename ECOMP-SDK-APP/src/main/webapp/static/fusion/images/ecomp-login-550x360.jpg => ONAP-SDK-APP/src/main/webapp/static/fusion/images/onap-login-550x360.jpg (100%) rename ECOMP-SDK-APP/src/main/webapp/static/fusion/images/ecomp-login.jpg => ONAP-SDK-APP/src/main/webapp/static/fusion/images/onap-login.jpg (100%) rename ECOMP-SDK-APP/src/main/webapp/static/fusion/images/ecomp.png => ONAP-SDK-APP/src/main/webapp/static/fusion/images/onap.png (100%) rename ECOMP-SDK-APP/src/main/webapp/static/fusion/images/ecomp_trans.png => ONAP-SDK-APP/src/main/webapp/static/fusion/images/onap_trans.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/js/att_angular_gridster/angular-gridster.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/js/att_angular_gridster/ui-gridster-tpls.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/css/images/blank.gif (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/css/scribble.css (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/css/slider.css (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/css/spacegallery.css (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/css/welcome.css (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/html/area_chart.html (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/html/bar_chart.html (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/html/d3_gauges_demo.html (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/html/data/speedometer2.csv (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/html/data/speedometer3.csv (100%) create mode 100644 ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/worddata.csv rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/html/donut_d3.html (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/html/js/area_chart.min.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/html/js/donut.min.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/html/js/gauges.min.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/html/js/line_chart.min.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/html/js/pie_chart.min.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/html/js/worddata.min.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/html/line_chart.html (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/html/pie_chart.html (100%) create mode 100644 ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/wordcloud.html rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/Calendar-16x16.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/arrow-next.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/arrow-prev.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/carousel/slide_b_drive_test_map.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/carousel/slide_b_eppt_county.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/carousel/slide_b_eppt_regression.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/carousel/slide_b_ios_throughput.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/carousel/slide_b_lata_map.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/carousel/slide_b_lata_map_legend.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/carousel/slide_b_nova_sdn_map.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/copyicon.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/deleteicon.gif (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/example-frame.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/loading.gif (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/tunnels/1_mon.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/tunnels/2_tue.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/tunnels/3_wed.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/tunnels/4_thu.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/tunnels/5_fri.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/tunnels/6_sat.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/tunnels/7_sun.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/tunnels/BH_DLSTX_IN.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/tunnels/BH_DLSTX_OUT.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/tunnels/BH_Nat.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/tunnels/BH_Nat_Def.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/images/tunnels/BH_Nat_Priority.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/js/FusionCharts.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/js/charts.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/js/jquery.flexslider-min.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/js/scribble.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/js/slides.min.jquery.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/js/spacegallery.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/org_chart/css/bootstrap.min.css (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/org_chart/css/custom.css (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/org_chart/css/jquery.jOrgChart.css (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/org_chart/css/prettify.css (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/org_chart/example.html (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/org_chart/example_vsp.html (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/org_chart/images/bkgd.png (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/org_chart/images/raspberry.jpg (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/org_chart/jquery.jOrgChart.js (100%) rename {ECOMP-SDK-APP => ONAP-SDK-APP}/src/main/webapp/static/fusion/sample/org_chart/prettify.js (100%) create mode 100644 ONAP-SDK-APP/xacml.admin.properties rename {ECOMP-XACML => ONAP-XACML}/.gitignore (100%) create mode 100644 ONAP-XACML/config_testing/test_PolicyEngine.xml create mode 100644 ONAP-XACML/config_testing/xacml.pip.properties create mode 100644 ONAP-XACML/config_testing/xacml.policy.properties create mode 100644 ONAP-XACML/policyLogger.properties create mode 100644 ONAP-XACML/pom.xml rename {ECOMP-XACML => ONAP-XACML}/sql/xacmlTest.mv.db (100%) create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/api/XACMLErrorConstants.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactory.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPAPPolicy.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDP.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDPGroup.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/PAPPolicyEngine.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngine.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngineFactory.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDP.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroup.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroupStatus.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPIPConfig.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicy.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPStatus.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/OperationHistoryEngine.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/aaf/AAFEngine.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/util/MetricsUtil.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyScanner.java create mode 100644 ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyWriter.java rename {ECOMP-XACML => ONAP-XACML}/src/main/resources/META-INF/operationHistoryPU.xml (100%) create mode 100644 ONAP-XACML/src/main/resources/xacml.properties create mode 100644 ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdEngineFactoryTest.java create mode 100644 ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/AAFEngineTest.java create mode 100644 ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/MetricsUtilTest.java create mode 100644 ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/XACMLPolicyScannerTest.java create mode 100644 ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/XACMLPolicyWriterTest.java create mode 100644 ONAP-XACML/src/test/resources/Action_TestActionPolicy.1.xml create mode 100644 ONAP-XACML/src/test/resources/CSVPolicy.xml create mode 100644 ONAP-XACML/src/test/resources/Config_SampleTest1206.1.xml create mode 100644 ONAP-XACML/src/test/resources/log4j.properties create mode 100644 ONAP-XACML/src/test/resources/logback.xml create mode 100644 ONAP-XACML/src/test/resources/logging.properties create mode 100644 ONAP-XACML/src/test/resources/pdps/default/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml create mode 100644 ONAP-XACML/src/test/resources/pdps/default/xacml.pip.properties rename {ECOMP-XACML => ONAP-XACML}/src/test/resources/pdps/default/xacml.policy.properties (100%) rename {ECOMP-XACML => ONAP-XACML}/src/test/resources/pdps/xacml.properties (100%) create mode 100644 ONAP-XACML/src/test/resources/xacml.pip.properties create mode 100644 ONAP-XACML/src/test/resources/xacml.policy.properties create mode 100644 ONAP-XACML/testclient.properties create mode 100644 ONAP-XACML/testpdp.properties rename {ECOMP-XACML => ONAP-XACML}/testsets/conformance/xacml3.0-ct-v.0.4/IIA001Response.xml (100%) create mode 100644 ONAP-XACML/xacml.pap.properties create mode 100644 ONAP-XACML/xacml.pdp.properties create mode 100644 ONAP-XACML/xacml.properties 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 create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/AttributeType.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/ConfigRequestParameters.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/DecisionRequestParameters.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/DecisionResponse.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/DeletePolicyCondition.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/DeletePolicyParameters.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/DictionaryParameters.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/DictionaryResponse.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/DictionaryType.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/EventRequestParameters.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/ImportParameters.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/MetricsRequestParameters.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/MetricsResponse.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/NotificationScheme.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyChangeResponse.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyClass.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyConfig.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyConfigException.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyConfigStatus.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyConfigType.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyDecision.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyDecisionException.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyEngine.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyEngineException.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyEventException.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyException.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyParameters.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyResponse.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyResponseStatus.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PolicyType.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/PushPolicyParameters.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/RuleProvider.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/api/package-info.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/models/APIConfigResponse.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/models/APIDictionaryResponse.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/models/APIPolicyConfigResponse.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientDMAAP.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientEnd.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/AutoClientUEB.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEnd.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndDMAAP.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/ManualClientEndUEB.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/MatchStore.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/Matches.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/NotificationUnMarshal.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/StdDecisionResponse.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/StdDictionaryResponse.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/StdMetricsResponse.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyChangeResponse.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyConfig.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyResponse.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/StdStatus.java create mode 100644 PolicyEngineAPI/src/main/java/org/onap/policy/std/package-info.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/AttributeType.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/ConfigRequestParameters.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/DecisionRequestParameters.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/DecisionResponse.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/DeletePolicyCondition.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/DeletePolicyParameters.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/DictionaryParameters.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/DictionaryResponse.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/DictionaryType.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/EventRequestParameters.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/ImportParameters.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/MetricsRequestParameters.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/MetricsResponse.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/NotificationScheme.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyChangeResponse.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyClass.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyConfig.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyConfigException.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyConfigStatus.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyConfigType.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyDecision.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyDecisionException.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyEngine.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyEngineException.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyEventException.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyException.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyParameters.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyResponse.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyResponseStatus.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PolicyType.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/PushPolicyParameters.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/RuleProvider.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/api/package-info.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/models/APIConfigResponse.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/models/APIDictionaryResponse.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/models/APIPolicyConfigResponse.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/AutoClientDMAAP.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/AutoClientEnd.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/AutoClientUEB.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/ManualClientEnd.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/ManualClientEndDMAAP.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/ManualClientEndUEB.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/MatchStore.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/Matches.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/NotificationUnMarshal.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/StdDecisionResponse.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/StdDictionaryResponse.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/StdMetricsResponse.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/StdPolicyChangeResponse.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/StdPolicyConfig.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/StdPolicyEngine.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/StdPolicyResponse.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/StdStatus.java delete mode 100644 PolicyEngineAPI/src/main/java/org/openecomp/policy/std/package-info.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientEndTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientUEBTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/Handler.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndUEBTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/MatchStoreTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/MatchesTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/NotificationStoreTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/NotificationUnMarshalTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdLoadedPolicyTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPDPNotificationTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPolicyChangeResponseTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPolicyConfigTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPolicyResponseTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdRemovedPolicyTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdStatusTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/std/test/package-info.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/ActionPolicyApiTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/AttributeTypeTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigBasePolicyTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigFirewallPolicyTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigRequestParametersTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/DecisionPolicyApiTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/DecisionRequestParametersTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/DeletePolicyConditionTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/DeletePolicyParametersTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/EventRequestParametersTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigByPolicyNameTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigStringStringMapTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigStringStringTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigStringTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/ImportParametersTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/LoadedPolicyTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/NotificationHandlerTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/NotificationSchemeTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/NotificationTypeTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PDPNotificationTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyChangeResponseTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyClassTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigExceptionTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigStatusTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigTypeTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyDecisionExceptionTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyDecisionTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineExceptionTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineInterfaceTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEventExceptionTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyParametersTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyResponseStatusTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyResponseTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyTypeTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/PushPolicyParametersTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/RemovedPolicyTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/SendEventTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/TestRunner.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/UpdateTypeTest.java create mode 100644 PolicyEngineAPI/src/test/java/org/onap/policy/test/package-info.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/AutoClientEndTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/AutoClientUEBTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/Handler.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/ManualClientEndTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/ManualClientEndUEBTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/MatchStoreTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/MatchesTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/NotificationStoreTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/NotificationUnMarshalTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdLoadedPolicyTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPDPNotificationTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPolicyChangeResponseTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPolicyConfigTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPolicyResponseTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdRemovedPolicyTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdStatusTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/package-info.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ActionPolicyApiTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/AttributeTypeTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ConfigBasePolicyTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ConfigFirewallPolicyTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ConfigRequestParametersTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DecisionPolicyApiTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DecisionRequestParametersTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DeletePolicyConditionTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DeletePolicyParametersTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/EventRequestParametersTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigByPolicyNameTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigStringStringMapTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigStringStringTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigStringTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ImportParametersTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/LoadedPolicyTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/NotificationHandlerTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/NotificationSchemeTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/NotificationTypeTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PDPNotificationTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyChangeResponseTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyClassTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigExceptionTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigStatusTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigTypeTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyDecisionExceptionTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyDecisionTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEngineExceptionTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEngineInterfaceTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEngineTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEventExceptionTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyParametersTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyResponseStatusTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyResponseTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyTypeTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PushPolicyParametersTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/RemovedPolicyTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/SendEventTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/TestRunner.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/UpdateTypeTest.java delete mode 100644 PolicyEngineAPI/src/test/java/org/openecomp/policy/test/package-info.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/ActionPolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/BrmsParamPolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/BrmsRawPolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/ClosedLoopPolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/ClosedLoopPolicyPerformanceMetricClient.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/ConfigBasePolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/ConfigFirewallPolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/DecisionPolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/DeletePolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/GeneralTestClient.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/GetConfigSample.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/Handler.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/ImportBRMSTemplate.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/ImportMicroServiceClient.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/ListConfigPoliciesClient.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/MainClient.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/MicroServicesPolicyClient.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/PolicyEngineTestClient.java create mode 100644 PolicyEngineClient/src/main/java/org/onap/policyEngine/PushPoliciesToPDP.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ActionPolicyClient.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/BrmsParamPolicyClient.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/BrmsRawPolicyClient.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyClient.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ClosedLoopPolicyPerformanceMetricClient.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ConfigBasePolicyClient.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ConfigFirewallPolicyClient.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/DecisionPolicyClient.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/DeletePolicyClient.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/GeneralTestClient.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/GetConfigSample.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/Handler.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ImportBRMSTemplate.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ImportMicroServiceClient.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/ListConfigPoliciesClient.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/MainClient.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/MicroServicesPolicyClient.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/PolicyEngineTestClient.java delete mode 100644 PolicyEngineClient/src/main/java/org/openecomp/policyEngine/PushPoliciesToPDP.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/api/LoadedPolicy.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/api/NotificationHandler.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/api/NotificationType.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/api/PDPNotification.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/api/PEDependency.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/api/RemovedPolicy.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/api/UpdateType.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/jpa/BackUpMonitorEntity.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/std/NotificationStore.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/std/StdLoadedPolicy.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/std/StdPDPNotification.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/std/StdRemovedPolicy.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFEnvironment.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClient.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClientImpl.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyException.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpHandler.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/utils/BackUpMonitor.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusConsumer.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/utils/BusPublisher.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyAccess.java create mode 100644 PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/api/LoadedPolicy.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/api/NotificationHandler.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/api/NotificationType.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/api/PDPNotification.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/api/PEDependency.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/api/RemovedPolicy.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/api/UpdateType.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/jpa/BackUpMonitorEntity.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/std/NotificationStore.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/std/StdLoadedPolicy.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/std/StdPDPNotification.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/std/StdRemovedPolicy.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFEnvironment.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyClient.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyClientImpl.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/AAFPolicyException.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpHandler.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BackUpMonitor.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BusConsumer.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/BusPublisher.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyAccess.java delete mode 100644 PolicyEngineUtils/src/main/java/org/openecomp/policy/utils/PolicyUtils.java create mode 100644 PolicyEngineUtils/src/test/java/org/onap/policy/test/Handler.java create mode 100644 PolicyEngineUtils/src/test/java/org/onap/policy/test/PolicyUtilsTest.java create mode 100644 PolicyEngineUtils/src/test/java/org/onap/policy/test/testBackUpMonitor.java delete mode 100644 PolicyEngineUtils/src/test/java/org/openecomp/policy/test/Handler.java delete mode 100644 PolicyEngineUtils/src/test/java/org/openecomp/policy/test/PolicyUtilsTest.java delete mode 100644 PolicyEngineUtils/src/test/java/org/openecomp/policy/test/testBackUpMonitor.java delete mode 100644 packages/base/src/files/install/servers/ecomp/WEB-INF/classes/portal.properties delete mode 100644 packages/base/src/files/install/servers/ecomp/WEB-INF/conf/system.properties create mode 100644 packages/base/src/files/install/servers/onap/WEB-INF/classes/portal.properties create mode 100644 packages/base/src/files/install/servers/onap/WEB-INF/conf/system.properties diff --git a/BRMSGateway/config.properties b/BRMSGateway/config.properties index 3f6f6f63c..762f0ff1f 100644 --- a/BRMSGateway/config.properties +++ b/BRMSGateway/config.properties @@ -1,6 +1,6 @@ ### # ============LICENSE_START======================================================= -# ECOMP Policy Engine +# ONAP Policy Engine # ================================================================================ # Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. # ================================================================================ @@ -48,11 +48,11 @@ policyKeyID = controller ## GroupNames can be comma separated values. groupNames = default, vFW , vDNS -default.groupID = org.openecomp.policy-engine +default.groupID = org.onap.policy-engine default.artifactID = drlPDPGroup -vFW.groupID= org.openecomp.policy-engine.drools.vFW +vFW.groupID= org.onap.policy-engine.drools.vFW vFW.artifactID= policy-vFW-rules -vDNS.groupID= org.openecomp.policy-engine.drools.vDNS +vDNS.groupID= org.onap.policy-engine.drools.vDNS vDNS.artifactID= policy-vDNS-rules #Integrity Monitor values diff --git a/BRMSGateway/config/policyLogger.properties b/BRMSGateway/config/policyLogger.properties index d3d477256..d6b0b39e7 100644 --- a/BRMSGateway/config/policyLogger.properties +++ b/BRMSGateway/config/policyLogger.properties @@ -1,6 +1,6 @@ ### # ============LICENSE_START======================================================= -# ECOMP Policy Engine +# ONAP Policy Engine # ================================================================================ # Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. # ================================================================================ diff --git a/BRMSGateway/policyLogger.properties b/BRMSGateway/policyLogger.properties index d3d477256..d6b0b39e7 100644 --- a/BRMSGateway/policyLogger.properties +++ b/BRMSGateway/policyLogger.properties @@ -1,6 +1,6 @@ ### # ============LICENSE_START======================================================= -# ECOMP Policy Engine +# ONAP Policy Engine # ================================================================================ # Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. # ================================================================================ diff --git a/BRMSGateway/pom.xml b/BRMSGateway/pom.xml index 5512f7ae3..b398f373d 100644 --- a/BRMSGateway/pom.xml +++ b/BRMSGateway/pom.xml @@ -1,6 +1,6 @@ + ::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" --> diff --git a/ECOMP-ASDC/pom.xml b/ECOMP-ASDC/pom.xml deleted file mode 100644 index 10531f3e9..000000000 --- a/ECOMP-ASDC/pom.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - 4.0.0 - asdc - - org.openecomp.policy.engine - PolicyEngineSuite - 1.1.0-SNAPSHOT - - - - junit - junit - 4.12 - provided - - - \ No newline at end of file diff --git a/ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/Resource.java b/ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/Resource.java deleted file mode 100644 index af57afa00..000000000 --- a/ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/Resource.java +++ /dev/null @@ -1,159 +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.asdc; - -import java.io.Serializable; -import java.util.UUID; - -public class Resource implements Serializable { - - private static final long serialVersionUID = -913729158733348027L; - - private UUID resourceUUID; - private UUID resourceInvariantUUID; - private String resourceName; - private String resourceVersion; - private ResourceType resourceType; - - public Resource() { - //Empty Constructor - } - - public Resource(Resource resource) { - this.resourceUUID = resource.resourceUUID; - this.resourceInvariantUUID = resource.resourceInvariantUUID; - this.resourceName = resource.resourceName; - this.resourceVersion = resource.resourceVersion; - this.resourceType = resource.resourceType; - } - - public Resource(UUID uuid) { - this.resourceUUID = uuid; - } - - public Resource(String name, ResourceType type) { - this.resourceName = name; - this.resourceType = type; - } - - public Resource(UUID uuid, UUID invariantUUID, String name, String version, ResourceType type) { - this.resourceUUID = uuid; - this.resourceInvariantUUID = invariantUUID; - this.resourceName = name; - this.resourceVersion = version; - this.resourceType = type; - } - - public UUID getResourceUUID() { - return resourceUUID; - } - - public void setResourceUUID(UUID resourceUUID) { - this.resourceUUID = resourceUUID; - } - - public UUID getResourceInvariantUUID() { - return resourceInvariantUUID; - } - - public void setResourceInvariantUUID(UUID resourceInvariantUUID) { - this.resourceInvariantUUID = resourceInvariantUUID; - } - - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - public String getResourceVersion() { - return resourceVersion; - } - - public void setResourceVersion(String resourceVersion) { - this.resourceVersion = resourceVersion; - } - - public ResourceType getResourceType() { - return resourceType; - } - - public void setResourceType(ResourceType resourceType) { - this.resourceType = resourceType; - } - - @Override - public String toString() { - return "Resource [resourceUUID=" + resourceUUID + ", resourceInvariantUUID=" + resourceInvariantUUID - + ", resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resourceType=" - + resourceType + "]"; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((resourceInvariantUUID == null) ? 0 : resourceInvariantUUID.hashCode()); - result = prime * result + ((resourceName == null) ? 0 : resourceName.hashCode()); - result = prime * result + ((resourceType == null) ? 0 : resourceType.hashCode()); - result = prime * result + ((resourceUUID == null) ? 0 : resourceUUID.hashCode()); - result = prime * result + ((resourceVersion == null) ? 0 : resourceVersion.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Resource other = (Resource) obj; - if (resourceInvariantUUID == null) { - if (other.resourceInvariantUUID != null) - return false; - } else if (!resourceInvariantUUID.equals(other.resourceInvariantUUID)) - return false; - if (resourceName == null) { - if (other.resourceName != null) - return false; - } else if (!resourceName.equals(other.resourceName)) - return false; - if (resourceType == null) { - if (other.resourceType != null) - return false; - } else if (!resourceType.equals(other.resourceType)) - return false; - if (resourceUUID == null) { - if (other.resourceUUID != null) - return false; - } else if (!resourceUUID.equals(other.resourceUUID)) - return false; - if (resourceVersion == null) { - if (other.resourceVersion != null) - return false; - } else if (!resourceVersion.equals(other.resourceVersion)) - return false; - return true; - } - -} diff --git a/ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/ResourceInstance.java b/ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/ResourceInstance.java deleted file mode 100644 index 40d48d9f0..000000000 --- a/ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/ResourceInstance.java +++ /dev/null @@ -1,157 +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.asdc; - -import java.io.Serializable; -import java.util.UUID; - -public class ResourceInstance implements Serializable { - private static final long serialVersionUID = -5506162340393802424L; - - private String resourceInstanceName; - private String resourceName; - private UUID resourceInvariantUUID; - private String resourceVersion; - private ResourceType resourceType; - private UUID resourceUUID; - - public ResourceInstance() { - //Empty Constructor - } - - public ResourceInstance(ResourceInstance instance) { - if (instance == null) { - return; - } - this.resourceInstanceName = instance.resourceInstanceName; - this.resourceName = instance.resourceName; - this.resourceInvariantUUID = instance.resourceInvariantUUID; - this.resourceVersion = instance.resourceVersion; - this.resourceType = instance.resourceType; - this.resourceUUID = instance.resourceUUID; - } - - public String getResourceInstanceName() { - return resourceInstanceName; - } - - public void setResourceInstanceName(String resourceInstanceName) { - this.resourceInstanceName = resourceInstanceName; - } - - public String getResourceName() { - return resourceName; - } - - public void setResourceName(String resourceName) { - this.resourceName = resourceName; - } - - public UUID getResourceInvariantUUID() { - return resourceInvariantUUID; - } - - public void setResourceInvariantUUID(UUID resourceInvariantUUID) { - this.resourceInvariantUUID = resourceInvariantUUID; - } - - public String getResourceVersion() { - return resourceVersion; - } - - public void setResourceVersion(String resourceVersion) { - this.resourceVersion = resourceVersion; - } - - public ResourceType getResourceType() { - return resourceType; - } - - public void setResourceType(ResourceType resourceType) { - this.resourceType = resourceType; - } - - public UUID getResourceUUID() { - return resourceUUID; - } - - public void setResourceUUID(UUID resourceUUID) { - this.resourceUUID = resourceUUID; - } - - @Override - public String toString() { - return "ResourceInstance [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + resourceName - + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceVersion=" + resourceVersion - + ", resourceType=" + resourceType + ", resourceUUID=" + resourceUUID + "]"; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((resourceInstanceName == null) ? 0 : resourceInstanceName.hashCode()); - result = prime * result + ((resourceInvariantUUID == null) ? 0 : resourceInvariantUUID.hashCode()); - result = prime * result + ((resourceName == null) ? 0 : resourceName.hashCode()); - result = prime * result + ((resourceType == null) ? 0 : resourceType.hashCode()); - result = prime * result + ((resourceUUID == null) ? 0 : resourceUUID.hashCode()); - result = prime * result + ((resourceVersion == null) ? 0 : resourceVersion.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ResourceInstance other = (ResourceInstance) obj; - if (resourceInstanceName == null) { - if (other.resourceInstanceName != null) - return false; - } else if (!resourceInstanceName.equals(other.resourceInstanceName)) - return false; - if (resourceInvariantUUID == null) { - if (other.resourceInvariantUUID != null) - return false; - } else if (!resourceInvariantUUID.equals(other.resourceInvariantUUID)) - return false; - if (resourceName == null) { - if (other.resourceName != null) - return false; - } else if (!resourceName.equals(other.resourceName)) - return false; - if (resourceType != other.resourceType) - return false; - if (resourceUUID == null) { - if (other.resourceUUID != null) - return false; - } else if (!resourceUUID.equals(other.resourceUUID)) - return false; - if (resourceVersion == null) { - if (other.resourceVersion != null) - return false; - } else if (!resourceVersion.equals(other.resourceVersion)) - return false; - return true; - } - -} diff --git a/ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/ResourceType.java b/ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/ResourceType.java deleted file mode 100644 index 426b3907c..000000000 --- a/ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/ResourceType.java +++ /dev/null @@ -1,40 +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.asdc; - -public enum ResourceType { - VF("VF"), - VFC("VFC"), - VL("VL"), - CP("CP") - ; - - private String type; - - private ResourceType(String type) { - this.type = type; - } - - public String toString() { - return this.type; - } - -} diff --git a/ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/Service.java b/ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/Service.java deleted file mode 100644 index b7b5d3cb5..000000000 --- a/ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/Service.java +++ /dev/null @@ -1,140 +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.asdc; - -import java.io.Serializable; -import java.util.UUID; - -public class Service implements Serializable { - - private static final long serialVersionUID = -1249276698549996806L; - - private UUID serviceUUID; - private UUID serviceInvariantUUID; - private String serviceName; - private String serviceVersion; - - public Service() { - //Empty Constructor - } - - public Service(UUID uuid) { - this.serviceUUID = uuid; - } - - public Service(String name) { - this.serviceName = name; - } - - public Service(UUID uuid, UUID invariantUUID, String name, String version) { - this.serviceUUID = uuid; - this.serviceInvariantUUID = invariantUUID; - this.serviceName = name; - this.serviceVersion = version; - } - - public Service(Service service) { - this.serviceUUID = service.serviceUUID; - this.serviceInvariantUUID = service.serviceInvariantUUID; - this.serviceName = service.serviceName; - this.serviceVersion = service.serviceVersion; - } - - public UUID getServiceUUID() { - return serviceUUID; - } - - public void setServiceUUID(UUID serviceUUID) { - this.serviceUUID = serviceUUID; - } - - public UUID getServiceInvariantUUID() { - return serviceInvariantUUID; - } - - public void setServiceInvariantUUID(UUID serviceInvariantUUID) { - this.serviceInvariantUUID = serviceInvariantUUID; - } - - public String getServiceName() { - return serviceName; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - - public String getServiceVersion() { - return serviceVersion; - } - - public void setServiceVersion(String serviceVersion) { - this.serviceVersion = serviceVersion; - } - - @Override - public String toString() { - return "Service [serviceUUID=" + serviceUUID + ", serviceInvariantUUID=" + serviceInvariantUUID - + ", serviceName=" + serviceName + ", serviceVersion=" + serviceVersion + "]"; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((serviceInvariantUUID == null) ? 0 : serviceInvariantUUID.hashCode()); - result = prime * result + ((serviceName == null) ? 0 : serviceName.hashCode()); - result = prime * result + ((serviceUUID == null) ? 0 : serviceUUID.hashCode()); - result = prime * result + ((serviceVersion == null) ? 0 : serviceVersion.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Service other = (Service) obj; - if (serviceInvariantUUID == null) { - if (other.serviceInvariantUUID != null) - return false; - } else if (!serviceInvariantUUID.equals(other.serviceInvariantUUID)) - return false; - if (serviceName == null) { - if (other.serviceName != null) - return false; - } else if (!serviceName.equals(other.serviceName)) - return false; - if (serviceUUID == null) { - if (other.serviceUUID != null) - return false; - } else if (!serviceUUID.equals(other.serviceUUID)) - return false; - if (serviceVersion == null) { - if (other.serviceVersion != null) - return false; - } else if (!serviceVersion.equals(other.serviceVersion)) - return false; - return true; - } - -} diff --git a/ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/ServiceInstance.java b/ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/ServiceInstance.java deleted file mode 100644 index 40a08fd93..000000000 --- a/ECOMP-ASDC/src/main/java/org/openecomp/policy/asdc/ServiceInstance.java +++ /dev/null @@ -1,177 +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.asdc; - -import java.io.Serializable; -import java.util.UUID; - -public class ServiceInstance implements Serializable { - private static final long serialVersionUID = 6285260780966679625L; - - private UUID personaModelUUID; - private UUID serviceUUID; - private UUID serviceInstanceUUID; - private UUID widgetModelUUID; - private String widgetModelVersion; - private String serviceName; - private String serviceInstanceName; - - public ServiceInstance() { - //Empty Constructor - } - - public ServiceInstance(ServiceInstance instance) { - if (instance == null) { - return; - } - this.personaModelUUID = instance.personaModelUUID; - this.serviceUUID = instance.serviceUUID; - this.serviceInstanceUUID = instance.serviceInstanceUUID; - this.widgetModelUUID = instance.widgetModelUUID; - this.widgetModelVersion = instance.widgetModelVersion; - this.serviceName = instance.serviceName; - this.serviceInstanceName = instance.serviceInstanceName; - } - - public UUID getPersonaModelUUID() { - return personaModelUUID; - } - - public void setPersonaModelUUID(UUID personaModelUUID) { - this.personaModelUUID = personaModelUUID; - } - - public UUID getServiceUUID() { - return serviceUUID; - } - - public void setServiceUUID(UUID serviceUUID) { - this.serviceUUID = serviceUUID; - } - - public UUID getServiceInstanceUUID() { - return serviceInstanceUUID; - } - - public void setServiceInstanceUUID(UUID serviceInstanceUUID) { - this.serviceInstanceUUID = serviceInstanceUUID; - } - - public UUID getWidgetModelUUID() { - return widgetModelUUID; - } - - public void setWidgetModelUUID(UUID widgetModelUUID) { - this.widgetModelUUID = widgetModelUUID; - } - - public String getWidgetModelVersion() { - return widgetModelVersion; - } - - public void setWidgetModelVersion(String widgetModelVersion) { - this.widgetModelVersion = widgetModelVersion; - } - - public String getServiceName() { - return serviceName; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - - public String getServiceInstanceName() { - return serviceInstanceName; - } - - public void setServiceInstanceName(String serviceInstanceName) { - this.serviceInstanceName = serviceInstanceName; - } - - @Override - public String toString() { - return "ServiceInstance [personaModelUUID=" + personaModelUUID + ", serviceUUID=" + serviceUUID - + ", serviceInstanceUUID=" + serviceInstanceUUID + ", widgetModelUUID=" + widgetModelUUID - + ", widgetModelVersion=" + widgetModelVersion + ", serviceName=" + serviceName - + ", serviceInstanceName=" + serviceInstanceName + "]"; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((personaModelUUID == null) ? 0 : personaModelUUID.hashCode()); - result = prime * result + ((serviceInstanceName == null) ? 0 : serviceInstanceName.hashCode()); - result = prime * result + ((serviceInstanceUUID == null) ? 0 : serviceInstanceUUID.hashCode()); - result = prime * result + ((serviceName == null) ? 0 : serviceName.hashCode()); - result = prime * result + ((serviceUUID == null) ? 0 : serviceUUID.hashCode()); - result = prime * result + ((widgetModelUUID == null) ? 0 : widgetModelUUID.hashCode()); - result = prime * result + ((widgetModelVersion == null) ? 0 : widgetModelVersion.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ServiceInstance other = (ServiceInstance) obj; - if (personaModelUUID == null) { - if (other.personaModelUUID != null) - return false; - } else if (!personaModelUUID.equals(other.personaModelUUID)) - return false; - if (serviceInstanceName == null) { - if (other.serviceInstanceName != null) - return false; - } else if (!serviceInstanceName.equals(other.serviceInstanceName)) - return false; - if (serviceInstanceUUID == null) { - if (other.serviceInstanceUUID != null) - return false; - } else if (!serviceInstanceUUID.equals(other.serviceInstanceUUID)) - return false; - if (serviceName == null) { - if (other.serviceName != null) - return false; - } else if (!serviceName.equals(other.serviceName)) - return false; - if (serviceUUID == null) { - if (other.serviceUUID != null) - return false; - } else if (!serviceUUID.equals(other.serviceUUID)) - return false; - if (widgetModelUUID == null) { - if (other.widgetModelUUID != null) - return false; - } else if (!widgetModelUUID.equals(other.widgetModelUUID)) - return false; - if (widgetModelVersion == null) { - if (other.widgetModelVersion != null) - return false; - } else if (!widgetModelVersion.equals(other.widgetModelVersion)) - return false; - return true; - } - -} diff --git a/ECOMP-ControlloopPolicy/pom.xml b/ECOMP-ControlloopPolicy/pom.xml deleted file mode 100644 index 870ba148f..000000000 --- a/ECOMP-ControlloopPolicy/pom.xml +++ /dev/null @@ -1,62 +0,0 @@ - - - 4.0.0 - ControlloopPolicy - - org.openecomp.policy.engine - PolicyEngineSuite - 1.1.0-SNAPSHOT - - - - org.openecomp.policy.engine - asdc - ${project.version} - - - junit - junit - 4.12 - provided - - - org.yaml - snakeyaml - 1.17 - - - org.jgrapht - jgrapht-core - 0.9.2 - - - com.google.guava - guava - 19.0 - - - org.openecomp.policy.common - ECOMP-Logging - ${common-modules.version} - - - diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/CompilerException.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/CompilerException.java deleted file mode 100644 index 78f30570c..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/CompilerException.java +++ /dev/null @@ -1,47 +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.controlloop.compiler; - -public class CompilerException extends Exception { - - private static final long serialVersionUID = -7262217239867898601L; - - public CompilerException() { - //Empty Constructor - } - - public CompilerException(String message) { - super(message); - } - - public CompilerException(Throwable cause) { - super(cause); - } - - public CompilerException(String message, Throwable cause) { - super(message, cause); - } - - public CompilerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompiler.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompiler.java deleted file mode 100644 index e0000c02d..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompiler.java +++ /dev/null @@ -1,617 +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.controlloop.compiler; - -import java.io.InputStream; -import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.jgrapht.DirectedGraph; -import org.jgrapht.graph.ClassBasedEdgeFactory; -import org.jgrapht.graph.DefaultEdge; -import org.jgrapht.graph.DirectedMultigraph; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.controlloop.policy.ControlLoop; -import org.openecomp.policy.controlloop.policy.ControlLoopPolicy; -import org.openecomp.policy.controlloop.policy.FinalResult; -import org.openecomp.policy.controlloop.policy.Policy; -import org.openecomp.policy.controlloop.policy.PolicyResult; -import org.openecomp.policy.controlloop.policy.TargetType; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -public class ControlLoopCompiler implements Serializable{ - /** - * - */ - private static final long serialVersionUID = 1L; - private static Logger LOGGER = FlexLogger.getLogger(ControlLoopCompiler.class.getName()); - - public static ControlLoopPolicy compile(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException { - // - // Ensure the control loop is sane - // - validateControlLoop(policy.getControlLoop(), callback); - // - // Validate the policies - // - validatePolicies(policy, callback); - - return policy; - } - - public static ControlLoopPolicy compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException { - Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - Object obj = yaml.load(yamlSpecification); - if (obj == null) { - throw new CompilerException("Could not parse yaml specification."); - } - if (! (obj instanceof ControlLoopPolicy)) { - throw new CompilerException("Yaml could not parse specification into required ControlLoopPolicy object"); - } - return ControlLoopCompiler.compile((ControlLoopPolicy) obj, callback); - } - - private static void validateControlLoop(ControlLoop controlLoop, ControlLoopCompilerCallback callback) throws CompilerException { - if (controlLoop == null && callback != null) { - callback.onError("controlLoop cannot be null"); - } - if (controlLoop!=null){ - if ((controlLoop.getControlLoopName() == null || controlLoop.getControlLoopName().length() < 1) && callback != null) { - callback.onError("Missing controlLoopName"); - } - if ((!controlLoop.getVersion().contentEquals(ControlLoop.getVERSION())) && callback != null) { - callback.onError("Unsupported version for this compiler"); - } - if (controlLoop.getTrigger_policy() == null || controlLoop.getTrigger_policy().length() < 1) { - throw new CompilerException("trigger_policy is not valid"); - } - } - } - - private static void validatePolicies(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException { - if (policy == null) { - throw new CompilerException("policy cannot be null"); - } - // - // verify controlLoop overall timeout should be no less than the sum of operational policy timeouts - // - if (policy.getPolicies() == null) { - callback.onWarning("controlLoop is an open loop."); - } - else{ - int sum = 0; - for (Policy operPolicy : policy.getPolicies()) { - sum += operPolicy.getTimeout().intValue(); - } - if (policy.getControlLoop().getTimeout().intValue() < sum && callback != null) { - callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts."); - } - // - // For this version we can use a directed multigraph, in the future we may not be able to - // - DirectedGraph graph = new DirectedMultigraph<>(new ClassBasedEdgeFactory(LabeledEdge.class)); - // - // Check to see if the trigger Event is for OpenLoop, we do so by - // attempting to create a FinalResult object from it. If its a policy id, this should - // return null. - // - FinalResult triggerResult = FinalResult.toResult(policy.getControlLoop().getTrigger_policy()); - TriggerNodeWrapper triggerNode; - // - // Did this turn into a FinalResult object? - // - if (triggerResult != null) { - // - // Ensure they didn't use some other FinalResult code - // - if (triggerResult != FinalResult.FINAL_OPENLOOP) { - throw new CompilerException("Unexpected Final Result for trigger_policy, should only be " + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID"); - } - // - // They really shouldn't have any policies attached. - // - if ((policy.getPolicies() != null || policy.getPolicies().isEmpty())&& callback != null ) { - callback.onWarning("Open Loop policy contains policies. The policies will never be invoked."); - } - return; - // - } else { - // - // Ok, not a FinalResult object so let's assume that it is a Policy. Which it should be. - // - triggerNode = new TriggerNodeWrapper(policy.getControlLoop().getControlLoopName()); - } - // - // Add in the trigger node - // - graph.addVertex(triggerNode); - // - // Add in our Final Result nodes. All paths should end to these nodes. - // - FinalResultNodeWrapper finalSuccess = new FinalResultNodeWrapper(FinalResult.FINAL_SUCCESS); - FinalResultNodeWrapper finalFailure = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE); - FinalResultNodeWrapper finalFailureTimeout = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT); - FinalResultNodeWrapper finalFailureRetries = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_RETRIES); - FinalResultNodeWrapper finalFailureException = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION); - FinalResultNodeWrapper finalFailureGuard = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_GUARD); - graph.addVertex(finalSuccess); - graph.addVertex(finalFailure); - graph.addVertex(finalFailureTimeout); - graph.addVertex(finalFailureRetries); - graph.addVertex(finalFailureException); - graph.addVertex(finalFailureGuard); - // - // Work through the policies and add them in as nodes. - // - Map mapNodes = new HashMap<>(); - for (Policy operPolicy : policy.getPolicies()) { - // - // Is it still ok to add? - // - if (!okToAdd(operPolicy, callback)) { - // - // Do not add it in - // - continue; - } - // - // Create wrapper policy node and save it into our map so we can - // easily retrieve it. - // - PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy); - mapNodes.put(operPolicy, node); - graph.addVertex(node); - // - // Is this the trigger policy? - // - if (operPolicy.getId().equals(policy.getControlLoop().getTrigger_policy())) { - // - // Yes add an edge from our trigger event node to this policy - // - graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET"))); - } - } - // - // last sweep to connect remaining edges for policy results - // - for (Policy operPolicy : policy.getPolicies()) { - PolicyNodeWrapper node = mapNodes.get(operPolicy); - // - // Just ensure this has something - // - if (node == null) { - continue; - } - if (FinalResult.isResult(operPolicy.getSuccess(), FinalResult.FINAL_SUCCESS)) { - graph.addEdge(node, finalSuccess, new LabeledEdge(node, finalSuccess, new FinalResultEdgeWrapper(FinalResult.FINAL_SUCCESS))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getSuccess()); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.getId() + " success is connected to unknown policy " + operPolicy.getSuccess()); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.SUCCESS))); - } - } - if (FinalResult.isResult(operPolicy.getFailure(), FinalResult.FINAL_FAILURE)) { - graph.addEdge(node, finalFailure, new LabeledEdge(node, finalFailure, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure()); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure is connected to unknown policy " + operPolicy.getFailure()); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE))); - } - } - if (FinalResult.isResult(operPolicy.getFailure_timeout(), FinalResult.FINAL_FAILURE_TIMEOUT)) { - graph.addEdge(node, finalFailureTimeout, new LabeledEdge(node, finalFailureTimeout, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_timeout()); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_timeout is connected to unknown policy " + operPolicy.getFailure_timeout()); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_TIMEOUT))); - } - } - if (FinalResult.isResult(operPolicy.getFailure_retries(), FinalResult.FINAL_FAILURE_RETRIES)) { - graph.addEdge(node, finalFailureRetries, new LabeledEdge(node, finalFailureRetries, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_RETRIES))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_retries()); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_retries is connected to unknown policy " + operPolicy.getFailure_retries()); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_RETRIES))); - } - } - if (FinalResult.isResult(operPolicy.getFailure_exception(), FinalResult.FINAL_FAILURE_EXCEPTION)) { - graph.addEdge(node, finalFailureException, new LabeledEdge(node, finalFailureException, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_exception()); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_exception is connected to unknown policy " + operPolicy.getFailure_exception()); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_EXCEPTION))); - } - } - if (FinalResult.isResult(operPolicy.getFailure_guard(), FinalResult.FINAL_FAILURE_GUARD)) { - graph.addEdge(node, finalFailureGuard, new LabeledEdge(node, finalFailureGuard, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_GUARD))); - } else { - PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_guard()); - if (toNode == null) { - throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_guard is connected to unknown policy " + operPolicy.getFailure_guard()); - } else { - graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_GUARD))); - } - } - } - // - // Now validate all the nodes/edges - // - for (NodeWrapper node : graph.vertexSet()) { - if (node instanceof TriggerNodeWrapper) { - LOGGER.info("Trigger Node " + node.toString()); - if (graph.inDegreeOf(node) > 0 ) { - // - // Really should NEVER get here unless someone messed up the code above. - // - throw new CompilerException("No inputs to event trigger"); - } - // - // Should always be 1, except in the future we may support multiple events - // - if (graph.outDegreeOf(node) > 1) { - throw new CompilerException("The event trigger should only go to ONE node"); - } - } else if (node instanceof FinalResultNodeWrapper) { - LOGGER.info("FinalResult Node " + node.toString()); - // - // FinalResult nodes should NEVER have an out edge - // - if (graph.outDegreeOf(node) > 0) { - throw new CompilerException("FinalResult nodes should never have any out edges."); - } - } else if (node instanceof PolicyNodeWrapper) { - LOGGER.info("Policy Node " + node.toString()); - // - // All Policy Nodes should have the 5 out degrees defined. - // - if (graph.outDegreeOf(node) != 6) { - throw new CompilerException("Policy node should ALWAYS have 6 out degrees."); - } - // - // All Policy Nodes should have at least 1 in degrees - // - if (graph.inDegreeOf(node) == 0 && callback != null) { - callback.onWarning("Policy " + node.getID() + " is not reachable."); - } - } - for (LabeledEdge edge : graph.outgoingEdgesOf(node)){ - LOGGER.info(edge.from.getID() + " invokes " + edge.to.getID() + " upon " + edge.edge.getID()); - } - } - } - } - - private static boolean okToAdd(Policy operPolicy, ControlLoopCompilerCallback callback) { - // - // Check the policy id and make sure its sane - // - boolean okToAdd = true; - if (operPolicy.getId() == null || operPolicy.getId().length() < 1) { - if (callback != null) { - callback.onError("Operational Policy has an bad ID"); - } - okToAdd = false; - } - // - // Check if they decided to make the ID a result object - // - if (PolicyResult.toResult(operPolicy.getId()) != null) { - if (callback != null) { - callback.onError("Policy id is set to a PolicyResult " + operPolicy.getId()); - } - okToAdd = false; - } - if (FinalResult.toResult(operPolicy.getId()) != null) { - if (callback != null) { - callback.onError("Policy id is set to a FinalResult " + operPolicy.getId()); - } - okToAdd = false; - } - // - // Check that the actor/recipe/target are valid - // - if (operPolicy.getActor() == null) { - if (callback != null) { - callback.onError("Policy actor is null"); - } - okToAdd = false; - } - // - // Construct a list for all valid actors - // - ImmutableList actors = ImmutableList.of("APPC", "AOTS", "MSO", "SDNO", "SDNR", "AAI"); - // - if (operPolicy.getActor() != null && (!actors.contains(operPolicy.getActor())) ) { - if (callback != null) { - callback.onError("Policy actor is invalid"); - } - okToAdd = false; - } - if (operPolicy.getRecipe() == null) { - if (callback != null) { - callback.onError("Policy recipe is null"); - } - okToAdd = false; - } - // - // NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these) - // - ImmutableMap> recipes = new ImmutableMap.Builder>() - .put("APPC", ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig")) - .put("AOTS", ImmutableList.of("checkMaintenanceWindow", "checkENodeBTicketHours", "checkEquipmentStatus", "checkEimStatus", "checkEquipmentMaintenance")) - .put("MSO", ImmutableList.of("VF Module Create")) - .put("SDNO", ImmutableList.of("health-diagnostic-type", "health-diagnostic", "health-diagnostic-history", "health-diagnostic-commands", "health-diagnostic-aes")) - .put("SDNR", ImmutableList.of("Restart", "Reboot")) - .build(); - // - if (operPolicy.getRecipe() != null && (!recipes.getOrDefault(operPolicy.getActor(), Collections.emptyList()).contains(operPolicy.getRecipe()))) { - if (callback != null) { - callback.onError("Policy recipe is invalid"); - } - okToAdd = false; - } - if (operPolicy.getTarget() == null) { - if (callback != null) { - callback.onError("Policy target is null"); - } - okToAdd = false; - } - if (operPolicy.getTarget() != null && operPolicy.getTarget().getType() != TargetType.VM && operPolicy.getTarget().getType() != TargetType.VFC && operPolicy.getTarget().getType() != TargetType.PNF) { - if (callback != null) { - callback.onError("Policy target is invalid"); - } - okToAdd = false; - } - // - // Check that policy results are connected to either default final * or another policy - // - if (FinalResult.toResult(operPolicy.getSuccess()) != null && operPolicy.getSuccess() != FinalResult.FINAL_SUCCESS.toString()) { - if (callback != null) { - callback.onError("Policy success is neither another policy nor FINAL_SUCCESS"); - } - okToAdd = false; - } - if (FinalResult.toResult(operPolicy.getFailure()) != null && operPolicy.getFailure() != FinalResult.FINAL_FAILURE.toString()) { - if (callback != null) { - callback.onError("Policy failure is neither another policy nor FINAL_FAILURE"); - } - okToAdd = false; - } - if (FinalResult.toResult(operPolicy.getFailure_retries()) != null && operPolicy.getFailure_retries() != FinalResult.FINAL_FAILURE_RETRIES.toString()) { - if (callback != null) { - callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES"); - } - okToAdd = false; - } - if (FinalResult.toResult(operPolicy.getFailure_timeout()) != null && operPolicy.getFailure_timeout() != FinalResult.FINAL_FAILURE_TIMEOUT.toString()) { - if (callback != null) { - callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT"); - } - okToAdd = false; - } - if (FinalResult.toResult(operPolicy.getFailure_exception()) != null && operPolicy.getFailure_exception() != FinalResult.FINAL_FAILURE_EXCEPTION.toString()) { - if (callback != null) { - callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION"); - } - okToAdd = false; - } - if (FinalResult.toResult(operPolicy.getFailure_guard()) != null && operPolicy.getFailure_guard() != FinalResult.FINAL_FAILURE_GUARD.toString()) { - if (callback != null) { - callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD"); - } - okToAdd = false; - } - return okToAdd; - } - - private static PolicyNodeWrapper findPolicyNode(Map mapNodes, String id) { - for (Entry entry : mapNodes.entrySet()) { - if (entry.getKey().getId().equals(id)) { - return entry.getValue(); - } - } - return null; - } - - @FunctionalInterface - private interface NodeWrapper extends Serializable{ - public String getID(); - } - - private static class TriggerNodeWrapper implements NodeWrapper { - private static final long serialVersionUID = -187644087811478349L; - private String closedLoopControlName; - - public TriggerNodeWrapper(String closedLoopControlName) { - this.closedLoopControlName = closedLoopControlName; - } - - @Override - public String toString() { - return "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]"; - } - - @Override - public String getID() { - return closedLoopControlName; - } - - } - - private static class FinalResultNodeWrapper implements NodeWrapper { - private static final long serialVersionUID = 8540008796302474613L; - private FinalResult result; - - public FinalResultNodeWrapper(FinalResult result) { - this.result = result; - } - - @Override - public String toString() { - return "FinalResultNodeWrapper [result=" + result + "]"; - } - - @Override - public String getID() { - return result.toString(); - } - } - - private static class PolicyNodeWrapper implements NodeWrapper { - private static final long serialVersionUID = 8170162175653823082L; - private Policy policy; - - public PolicyNodeWrapper(Policy operPolicy) { - this.policy = operPolicy; - } - - @Override - public String toString() { - return "PolicyNodeWrapper [policy=" + policy + "]"; - } - - @Override - public String getID() { - return policy.getId(); - } - } - - @FunctionalInterface - private interface EdgeWrapper extends Serializable{ - public String getID(); - - } - - private static class TriggerEdgeWrapper implements EdgeWrapper { - private static final long serialVersionUID = 2678151552623278863L; - private String trigger; - - public TriggerEdgeWrapper(String trigger) { - this.trigger = trigger; - } - - @Override - public String getID() { - return trigger; - } - - @Override - public String toString() { - return "TriggerEdgeWrapper [trigger=" + trigger + "]"; - } - - } - - private static class PolicyResultEdgeWrapper implements EdgeWrapper { - private static final long serialVersionUID = 6078569477021558310L; - private PolicyResult policyResult; - - public PolicyResultEdgeWrapper(PolicyResult policyResult) { - super(); - this.policyResult = policyResult; - } - - @Override - public String toString() { - return "PolicyResultEdgeWrapper [policyResult=" + policyResult + "]"; - } - - @Override - public String getID() { - return policyResult.toString(); - } - - - } - - private static class FinalResultEdgeWrapper implements EdgeWrapper { - private static final long serialVersionUID = -1486381946896779840L; - private FinalResult finalResult; - public FinalResultEdgeWrapper(FinalResult result) { - this.finalResult = result; - } - - @Override - public String toString() { - return "FinalResultEdgeWrapper [finalResult=" + finalResult + "]"; - } - - @Override - public String getID() { - return finalResult.toString(); - } - } - - - private static class LabeledEdge extends DefaultEdge { - private static final long serialVersionUID = 579384429573385524L; - - private NodeWrapper from; - private NodeWrapper to; - private EdgeWrapper edge; - - public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) { - this.from = from; - this.to = to; - this.edge = edge; - } - - @SuppressWarnings("unused") - public NodeWrapper from() { - return from; - } - - @SuppressWarnings("unused") - public NodeWrapper to() { - return to; - } - - @SuppressWarnings("unused") - public EdgeWrapper edge() { - return edge; - } - - @Override - public String toString() { - return "LabeledEdge [from=" + from + ", to=" + to + ", edge=" + edge + "]"; - } - } - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompilerCallback.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompilerCallback.java deleted file mode 100644 index bb6cebde4..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompilerCallback.java +++ /dev/null @@ -1,29 +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.controlloop.compiler; - -public interface ControlLoopCompilerCallback { - - public boolean onWarning(String message); - - public boolean onError(String message); - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java deleted file mode 100644 index aa2bbfd8a..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java +++ /dev/null @@ -1,133 +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.controlloop.guard.compiler; - - -import java.io.InputStream; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.openecomp.policy.controlloop.compiler.CompilerException; -import org.openecomp.policy.controlloop.compiler.ControlLoopCompilerCallback; -import org.openecomp.policy.controlloop.policy.guard.Constraint; -import org.openecomp.policy.controlloop.policy.guard.ControlLoopGuard; -import org.openecomp.policy.controlloop.policy.guard.GuardPolicy; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; - -public class ControlLoopGuardCompiler { - - private ControlLoopGuardCompiler(){ - // Private Constructor - } - - public static ControlLoopGuard compile(ControlLoopGuard cLGuard, ControlLoopCompilerCallback callback) throws CompilerException { - // - // Ensure ControlLoopGuard has at least one guard policies - // - validateControlLoopGuard(cLGuard, callback); - // - // Ensure each guard policy has at least one constraints and all guard policies are unique - // - validateGuardPolicies(cLGuard.getGuards(), callback); - // - // Ensure constraints for each guard policy are unique - // - validateConstraints(cLGuard.getGuards(), callback); - - return cLGuard; - } - - public static ControlLoopGuard compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException { - Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); - Object obj = yaml.load(yamlSpecification); - if (obj == null) { - throw new CompilerException("Could not parse yaml specification."); - } - if (! (obj instanceof ControlLoopGuard)) { - throw new CompilerException("Yaml could not parse specification into required ControlLoopGuard object"); - } - return ControlLoopGuardCompiler.compile((ControlLoopGuard) obj, callback); - } - - private static void validateControlLoopGuard(ControlLoopGuard cLGuard, ControlLoopCompilerCallback callback) throws CompilerException { - if (cLGuard == null) { - if (callback != null) { - callback.onError("ControlLoop Guard cannot be null"); - } - throw new CompilerException("ControlLoop Guard cannot be null"); - } - if (cLGuard.getGuard() == null && callback != null) { - callback.onError("Guard version cannot be null"); - } - if (cLGuard.getGuards() == null) { - if (callback != null) { - callback.onError("ControlLoop Guard should have at least one guard policies"); - } - } else if (cLGuard.getGuards().isEmpty() && callback != null) { - callback.onError("ControlLoop Guard should have at least one guard policies"); - } - } - - private static void validateGuardPolicies(List policies, ControlLoopCompilerCallback callback) throws CompilerException { - if (policies == null) { - if (callback != null) { - callback.onError("Guard policies should not be null"); - } - throw new CompilerException("Guard policies should not be null"); - } - // - // Ensure all guard policies are unique - // - Set newSet = new HashSet<>(policies); - if (newSet.size() != policies.size() && callback != null) { - callback.onWarning("There are duplicate guard policies"); - } - // - // Ensure each guard policy has at least one constraints - // - for (GuardPolicy policy : policies) { - if (policy.getLimit_constraints() == null || policy.getLimit_constraints().isEmpty()) { - if (callback != null) { - callback.onError("Guard policy " + policy.getName() + " does not have any limit constraint"); - } - throw new CompilerException("Guard policy " + policy.getName() + " does not have any limit constraint"); - } - } - } - - private static void validateConstraints(List policies, ControlLoopCompilerCallback callback) throws CompilerException { - if (policies == null) { - if (callback != null) { - callback.onError("Guard policies should not be null"); - } - throw new CompilerException("Guard policies should not be null"); - } - for (GuardPolicy policy : policies) { - Set newSet = new HashSet<>(policy.getLimit_constraints()); - if (newSet.size() != policy.getLimit_constraints().size() && callback != null) { - callback.onWarning("Guard policy " + policy.getName() + " has duplicate limit constraints"); - } - } - } - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/ControlLoop.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/ControlLoop.java deleted file mode 100644 index ec25ab3db..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/ControlLoop.java +++ /dev/null @@ -1,189 +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.controlloop.policy; - -import java.util.LinkedList; -import java.util.List; - -import org.openecomp.policy.asdc.Resource; -import org.openecomp.policy.asdc.Service; - -public class ControlLoop { - - private static String VERSION = "2.0.0"; - - private String controlLoopName; - private String version = VERSION; - private List services; - private List resources; - private String trigger_policy = FinalResult.FINAL_OPENLOOP.toString(); - private Integer timeout; - private Boolean abatement = false; - - public ControlLoop() { - // Empty Constructor. - } - - public static String getVERSION(){ - return ControlLoop.VERSION; - } - - public String getControlLoopName() { - return controlLoopName; - } - - public void setControlLoopName(String controlLoopName) { - this.controlLoopName = controlLoopName; - } - - public List getServices() { - return services; - } - - public void setServices(List services) { - this.services = services; - } - - public List getResources() { - return resources; - } - - public void setResources(List resources) { - this.resources = resources; - } - - public String getTrigger_policy() { - return trigger_policy; - } - - public void setTrigger_policy(String trigger_policy) { - this.trigger_policy = trigger_policy; - } - - public Integer getTimeout() { - return timeout; - } - - public void setTimeout(Integer timeout) { - this.timeout = timeout; - } - - public Boolean getAbatement() { - return abatement; - } - - public void setAbatement(Boolean abatement) { - this.abatement = abatement; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version){ - this.version = version; - } - - public ControlLoop(ControlLoop controlLoop) { - this.controlLoopName = controlLoop.controlLoopName; - this.services = new LinkedList<>(); - if (controlLoop.services != null) { - for (Service service : controlLoop.services) { - this.services.add(service); - } - } - this.resources = new LinkedList<>(); - if (controlLoop.resources != null) { - for (Resource resource: controlLoop.resources) { - this.resources.add(resource); - } - } - this.trigger_policy = controlLoop.trigger_policy; - this.timeout = controlLoop.timeout; - this.abatement = controlLoop.abatement; - } - @Override - public String toString() { - return "ControlLoop [controlLoopName=" + controlLoopName + ", version=" + version + ", services=" + services - + ", resources=" + resources + ", trigger_policy=" + trigger_policy + ", timeout=" - + timeout + ", abatement=" + abatement + "]"; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((controlLoopName == null) ? 0 : controlLoopName.hashCode()); - result = prime * result + ((resources == null) ? 0 : resources.hashCode()); - result = prime * result + ((services == null) ? 0 : services.hashCode()); - result = prime * result + ((timeout == null) ? 0 : timeout.hashCode()); - result = prime * result + ((trigger_policy == null) ? 0 : trigger_policy.hashCode()); - result = prime * result + ((version == null) ? 0 : version.hashCode()); - result = prime * result + ((abatement == null) ? 0 : abatement.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ControlLoop other = (ControlLoop) obj; - if (controlLoopName == null) { - if (other.controlLoopName != null) - return false; - } else if (!controlLoopName.equals(other.controlLoopName)) - return false; - if (resources == null) { - if (other.resources != null) - return false; - } else if (!resources.equals(other.resources)) - return false; - if (services == null) { - if (other.services != null) - return false; - } else if (!services.equals(other.services)) - return false; - if (timeout == null) { - if (other.timeout != null) - return false; - } else if (!timeout.equals(other.timeout)) - return false; - if (trigger_policy == null) { - if (other.trigger_policy != null) - return false; - } else if (!trigger_policy.equals(other.trigger_policy)) - return false; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - if (abatement == null) { - if (other.abatement != null) - return false; - } else if (!abatement.equals(other.abatement)) - return false; - return true; - } - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/ControlLoopPolicy.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/ControlLoopPolicy.java deleted file mode 100644 index 82a9d964e..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/ControlLoopPolicy.java +++ /dev/null @@ -1,83 +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.controlloop.policy; - -import java.util.List; - -public class ControlLoopPolicy { - - private ControlLoop controlLoop; - - private List policies; - - public ControlLoop getControlLoop() { - return controlLoop; - } - - public void setControlLoop(ControlLoop controlLoop) { - this.controlLoop = controlLoop; - } - - public List getPolicies() { - return policies; - } - - public void setPolicies(List policies) { - this.policies = policies; - } - - @Override - public String toString() { - return "ControlLoopPolicy [controlLoop=" + controlLoop + ", policies=" + policies + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((controlLoop == null) ? 0 : controlLoop.hashCode()); - result = prime * result + ((policies == null) ? 0 : policies.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ControlLoopPolicy other = (ControlLoopPolicy) obj; - if (controlLoop == null) { - if (other.controlLoop != null) - return false; - } else if (!controlLoop.equals(other.controlLoop)) - return false; - if (policies == null) { - if (other.policies != null) - return false; - } else if (!policies.equals(other.policies)) - return false; - return true; - } - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/FinalResult.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/FinalResult.java deleted file mode 100644 index f64e44939..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/FinalResult.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.controlloop.policy; - -public enum FinalResult { - /** - * The Control Loop Policy successfully completed its Operations. - */ - FINAL_SUCCESS("Final_Success"), - /** - * The Control Loop Policy was an Open Loop and is finished. - */ - FINAL_OPENLOOP("Final_OpenLoop"), - /** - * The Control Loop Policy failed in its last Operation Policy. NOTE: Previous Operation Policies may have been successful. - */ - FINAL_FAILURE("Final_Failure"), - /** - * The Control Loop Policy failed because the overall timeout was met. - */ - FINAL_FAILURE_TIMEOUT("Final_Failure_Timeout"), - /** - * The Control Loop Policy failed because an Operation Policy met its retry limit. - */ - FINAL_FAILURE_RETRIES("Final_Failure_Retries"), - /** - * The Control Loop Policy failed due to an exception. - */ - FINAL_FAILURE_EXCEPTION("Final_Failure_Exception"), - /** - * The Control Loop Policy failed due to guard denied - */ - FINAL_FAILURE_GUARD("Final_Failure_Guard") - ; - - String result; - - private FinalResult(String result) { - this.result = result; - } - - public static FinalResult toResult(String result) { - if (result.equalsIgnoreCase(FINAL_SUCCESS.toString())) { - return FINAL_SUCCESS; - } - if (result.equalsIgnoreCase(FINAL_OPENLOOP.toString())) { - return FINAL_OPENLOOP; - } - if (result.equalsIgnoreCase(FINAL_FAILURE.toString())) { - return FINAL_FAILURE; - } - if (result.equalsIgnoreCase(FINAL_FAILURE_TIMEOUT.toString())) { - return FINAL_FAILURE_TIMEOUT; - } - if (result.equalsIgnoreCase(FINAL_FAILURE_RETRIES.toString())) { - return FINAL_FAILURE_RETRIES; - } - if (result.equalsIgnoreCase(FINAL_FAILURE_EXCEPTION.toString())) { - return FINAL_FAILURE_EXCEPTION; - } - if (result.equalsIgnoreCase(FINAL_FAILURE_GUARD.toString())) { - return FINAL_FAILURE_GUARD; - } - return null; - } - - public static boolean isResult(String result, FinalResult finalResult) { - FinalResult toResult = FinalResult.toResult(result); - if (toResult == null) { - return false; - } - return toResult.equals(finalResult); - } - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/OperationsAccumulateParams.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/OperationsAccumulateParams.java deleted file mode 100644 index b7424dd33..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/OperationsAccumulateParams.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.controlloop.policy; - -import java.io.Serializable; - -public class OperationsAccumulateParams implements Serializable { - - /** - * - */ - private static final long serialVersionUID = -3597358159130168247L; - - private String period; - private Integer limit; - - public OperationsAccumulateParams() { - // Does Nothing - } - - public OperationsAccumulateParams(OperationsAccumulateParams ops) { - this.period = ops.period; - this.limit = ops.limit; - } - - public OperationsAccumulateParams(String period, Integer limit) { - this.period = period; - this.limit = limit; - } - - public String getPeriod() { - return period; - } - - public void setPeriod(String period) { - this.period = period; - } - - public Integer getLimit() { - return limit; - } - - public void setLimit(Integer limit) { - this.limit = limit; - } - - @Override - public String toString() { - return "OperationsAccumulateParams [period=" + period + ", limit=" + limit + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((period == null) ? 0 : period.hashCode()); - result = prime * result + ((limit == null) ? 0 : limit.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - OperationsAccumulateParams other = (OperationsAccumulateParams) obj; - if (period == null) { - if (other.period != null) - return false; - } else if (!period.equals(other.period)) - return false; - if (limit == null) { - if (other.limit != null) - return false; - } else if (!limit.equals(other.limit)) - return false; - return true; - } - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/Policy.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/Policy.java deleted file mode 100644 index dcbc8937b..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/Policy.java +++ /dev/null @@ -1,353 +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.controlloop.policy; - -import java.util.Collections; -import java.util.Map; -import java.util.UUID; - -public class Policy { - - private String id = UUID.randomUUID().toString(); - private String name; - private String description; - private String actor; - private String recipe; - private Map payload; - private Target target; - private OperationsAccumulateParams operationsAccumulateParams; - private Integer retry = 0; - private Integer timeout = 300; - private String success = FinalResult.FINAL_SUCCESS.toString(); - private String failure = FinalResult.FINAL_FAILURE.toString(); - private String failure_retries = FinalResult.FINAL_FAILURE_RETRIES.toString(); - private String failure_timeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString(); - private String failure_exception = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); - private String failure_guard = FinalResult.FINAL_FAILURE_GUARD.toString(); - - - public Policy() { - //Does Nothing Empty Constructor - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - 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; - } - - public String getActor() { - return actor; - } - - public void setActor(String actor) { - this.actor = actor; - } - - public String getRecipe() { - return recipe; - } - - public void setRecipe(String recipe) { - this.recipe = recipe; - } - - public Map getPayload() { - return payload; - } - - public void setPayload(Map payload) { - this.payload = payload; - } - - public Target getTarget() { - return target; - } - - public void setTarget(Target target) { - this.target = target; - } - - public OperationsAccumulateParams getOperationsAccumulateParams() { - return operationsAccumulateParams; - } - - public void setOperationsAccumulateParams(OperationsAccumulateParams operationsAccumulateParams) { - this.operationsAccumulateParams = operationsAccumulateParams; - } - - public Integer getRetry() { - return retry; - } - - public void setRetry(Integer retry) { - this.retry = retry; - } - - public Integer getTimeout() { - return timeout; - } - - public void setTimeout(Integer timeout) { - this.timeout = timeout; - } - - public String getSuccess() { - return success; - } - - public void setSuccess(String success) { - this.success = success; - } - - public String getFailure() { - return failure; - } - - public void setFailure(String failure) { - this.failure = failure; - } - - public String getFailure_retries() { - return failure_retries; - } - - public void setFailure_retries(String failure_retries) { - this.failure_retries = failure_retries; - } - - public String getFailure_timeout() { - return failure_timeout; - } - - public void setFailure_timeout(String failure_timeout) { - this.failure_timeout = failure_timeout; - } - - public String getFailure_exception() { - return failure_exception; - } - - public void setFailure_exception(String failure_exception) { - this.failure_exception = failure_exception; - } - - public String getFailure_guard() { - return failure_guard; - } - - public void setFailure_guard(String failure_guard) { - this.failure_guard = failure_guard; - } - - public Policy(String id) { - this.id = id; - } - - public Policy(String name, String actor, String recipe, Map payload, Target target) { - this.name = name; - this.actor = actor; - this.recipe = recipe; - this.target = target; - if (payload != null) { - this.payload = Collections.unmodifiableMap(payload); - } - } - - public Policy(String name, String actor, String recipe, Map payload, Target target, Integer retries, Integer timeout) { - this(name, actor, recipe, payload, target); - this.retry = retries; - this.timeout = timeout; - } - - public Policy(String id, String name, String description, String actor, Map payload, Target target, String recipe, Integer retries, Integer timeout) { - this(name, actor, recipe, payload, target, retries, timeout); - this.id = id; - this.description = description; - } - - public Policy(Policy policy) { - this.id = policy.id; - this.name = policy.name; - this.description = policy.description; - this.actor = policy.actor; - this.recipe = policy.recipe; - if (policy.payload != null) { - this.payload = Collections.unmodifiableMap(policy.payload); - } - this.target = policy.target; - this.operationsAccumulateParams = policy.operationsAccumulateParams; - this.retry = policy.retry; - this.timeout = policy.timeout; - this.success = policy.success; - this.failure = policy.failure; - this.failure_exception = policy.failure_exception; - this.failure_guard = policy.failure_guard; - this.failure_retries = policy.failure_retries; - this.failure_timeout = policy.failure_timeout; - } - - public boolean isValid() { - if(id==null || name==null || actor==null|| recipe==null || target==null){ - return false; - } - return true; - } - - @Override - public String toString() { - return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", actor=" + actor + ", recipe=" - + recipe + ", payload=" + payload + ", target=" + target + ", operationsAccumulateParams=" + operationsAccumulateParams + ", retry=" + retry + ", timeout=" + timeout - + ", success=" + success + ", failure=" + failure + ", failure_retries=" + failure_retries - + ", failure_timeout=" + failure_timeout + ", failure_exception=" + failure_exception + ", failure_guard=" + failure_guard + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((actor == null) ? 0 : actor.hashCode()); - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((failure == null) ? 0 : failure.hashCode()); - result = prime * result + ((failure_exception == null) ? 0 : failure_exception.hashCode()); - result = prime * result + ((failure_guard == null) ? 0 : failure_guard.hashCode()); - result = prime * result + ((failure_retries == null) ? 0 : failure_retries.hashCode()); - result = prime * result + ((failure_timeout == null) ? 0 : failure_timeout.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((payload == null) ? 0 : payload.hashCode()); - result = prime * result + ((recipe == null) ? 0 : recipe.hashCode()); - result = prime * result + ((retry == null) ? 0 : retry.hashCode()); - result = prime * result + ((success == null) ? 0 : success.hashCode()); - result = prime * result + ((target == null) ? 0 : target.hashCode()); - result = prime * result + ((operationsAccumulateParams == null) ? 0 : operationsAccumulateParams.hashCode()); - result = prime * result + ((timeout == null) ? 0 : timeout.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Policy other = (Policy) obj; - if (actor != other.actor) - return false; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - if (failure == null) { - if (other.failure != null) - return false; - } else if (!failure.equals(other.failure)) - return false; - if (failure_exception == null) { - if (other.failure_exception != null) - return false; - } else if (!failure_exception.equals(other.failure_exception)) - return false; - if (failure_guard == null) { - if (other.failure_guard != null) - return false; - } else if (!failure_guard.equals(other.failure_guard)) - return false; - if (failure_retries == null) { - if (other.failure_retries != null) - return false; - } else if (!failure_retries.equals(other.failure_retries)) - return false; - if (failure_timeout == null) { - if (other.failure_timeout != null) - return false; - } else if (!failure_timeout.equals(other.failure_timeout)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (payload == null) { - if (other.payload != null) - return false; - } else if (!payload.equals(other.payload)) - return false; - if (recipe == null) { - if (other.recipe != null) - return false; - } else if (!recipe.equals(other.recipe)) - return false; - if (retry == null) { - if (other.retry != null) - return false; - } else if (!retry.equals(other.retry)) - return false; - if (success == null) { - if (other.success != null) - return false; - } else if (!success.equals(other.success)) - return false; - if (operationsAccumulateParams == null) { - if (other.operationsAccumulateParams != null) - return false; - } else if (!operationsAccumulateParams.equals(other.operationsAccumulateParams)) - return false; - if (target == null) { - if (other.target != null) - return false; - } else if (!target.equals(other.target)) - return false; - if (timeout == null) { - if (other.timeout != null) - return false; - } else if (!timeout.equals(other.timeout)) - return false; - return true; - } - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/PolicyResult.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/PolicyResult.java deleted file mode 100644 index 7d0334125..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/PolicyResult.java +++ /dev/null @@ -1,82 +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.controlloop.policy; - -public enum PolicyResult { - /** - * Operation was successful. - */ - SUCCESS("Success"), - /** - * Operation failed. - */ - FAILURE("Failure"), - /** - * Operation failed due to maximum retries being met. - */ - FAILURE_RETRIES("Failure_Retries"), - /** - * Operation failed due to timeout occurring. - */ - FAILURE_TIMEOUT("Failure_Timeout"), - /** - * Operation failed due to an exception. - */ - FAILURE_EXCEPTION("Failure_Exception"), - /** - * Operation failed since Guard did not permit. - */ - FAILURE_GUARD("Failure_Guard") - ; - - private String result; - - private PolicyResult(String result) { - this.result = result; - } - - @Override - public String toString() { - return this.result; - } - - public static PolicyResult toResult(String result) { - if (result.equalsIgnoreCase(SUCCESS.toString())) { - return SUCCESS; - } - if (result.equalsIgnoreCase(FAILURE.toString())) { - return FAILURE; - } - if (result.equalsIgnoreCase(FAILURE_RETRIES.toString())) { - return FAILURE_RETRIES; - } - if (result.equalsIgnoreCase(FAILURE_TIMEOUT.toString())) { - return FAILURE_TIMEOUT; - } - if (result.equalsIgnoreCase(FAILURE_EXCEPTION.toString())) { - return FAILURE_EXCEPTION; - } - if (result.equalsIgnoreCase(FAILURE_GUARD.toString())) { - return FAILURE_GUARD; - } - return null; - } - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/Target.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/Target.java deleted file mode 100644 index 1625c2968..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/Target.java +++ /dev/null @@ -1,106 +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.controlloop.policy; - -import java.io.Serializable; - -public class Target implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 2180988443264988319L; - - private String resourceID; - private TargetType type; - - public Target() { - //Does Nothing Empty Constructor - } - - public String getResourceID() { - return resourceID; - } - - public void setResourceID(String resourceID) { - this.resourceID = resourceID; - } - - public TargetType getType() { - return type; - } - - public void setType(TargetType type) { - this.type = type; - } - - public Target(TargetType type) { - this.type = type; - } - - public Target(String resourceID) { - this.resourceID = resourceID; - } - - public Target(TargetType type, String resourceID) { - this.type = type; - this.resourceID = resourceID; - } - - public Target(Target target) { - this.type = target.type; - this.resourceID = target.resourceID; - } - - @Override - public String toString() { - return "Target [type=" + type + ", resourceID=" + resourceID + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((type == null) ? 0 : type.hashCode()); - result = prime * result + ((resourceID == null) ? 0 : resourceID.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Target other = (Target) obj; - if (type == null) { - if (other.type != null) - return false; - } else if (!type.equals(other.type)) - return false; - if (resourceID == null) { - if (other.resourceID != null) - return false; - } else if (!resourceID.equals(other.resourceID)) - return false; - return true; - } -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/TargetType.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/TargetType.java deleted file mode 100644 index e43fa615e..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/TargetType.java +++ /dev/null @@ -1,39 +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.controlloop.policy; - -public enum TargetType { - VM("VM"), - PNF("PNF"), - VFC("VFC") - ; - - private String target; - - private TargetType(String targetType) { - this.target = targetType; - } - - @Override - public String toString() { - return this.target; - } - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/BuilderException.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/BuilderException.java deleted file mode 100644 index 273af85e3..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/BuilderException.java +++ /dev/null @@ -1,31 +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.controlloop.policy.builder; - -public class BuilderException extends Exception { - - private static final long serialVersionUID = 610064813684337895L; - - public BuilderException(String string) { - super(string); - } - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java deleted file mode 100644 index 2fdb6d9df..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java +++ /dev/null @@ -1,287 +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.controlloop.policy.builder; - -import java.util.Map; - -import org.openecomp.policy.asdc.Resource; -import org.openecomp.policy.asdc.Service; -import org.openecomp.policy.controlloop.policy.ControlLoop; -import org.openecomp.policy.controlloop.policy.OperationsAccumulateParams; -import org.openecomp.policy.controlloop.policy.Policy; -import org.openecomp.policy.controlloop.policy.PolicyResult; -import org.openecomp.policy.controlloop.policy.Target; -import org.openecomp.policy.controlloop.policy.builder.impl.ControlLoopPolicyBuilderImpl; - -public interface ControlLoopPolicyBuilder { - - /** - * Adds one or more services to the ControlLoop - * - * - * @param service - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException; - - /** - * @param services - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException; - - /** - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder removeAllServices() throws BuilderException; - - /** - * Adds one or more resources to the ControlLoop - * - * - * @param resource - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException; - - /** - * @param resources - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException; - - /** - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder removeAllResources() throws BuilderException; - - /** - * @param abatement - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException; - - - /** - * Sets the overall timeout value for the Control Loop. If any operational policies have retries and timeouts, - * then this overall timeout value should exceed all those values. - * - * @param timeout - * @return - * @throws BuilderException - */ - public ControlLoopPolicyBuilder setTimeout(Integer timeout) throws BuilderException; - - /** - * Scans the operational policies and calculate an minimum overall timeout for the Control Loop. - * - * - * @return Integer - */ - public Integer calculateTimeout(); - - /** - * Sets the initial trigger policy when a DCAE Closed Loop Event arrives in the ECOMP Policy Platform. - * - * - * @param name - * @param description - * @param actor - * @param target - * @param recipe - * @param retries - * @param timeout - * @return Policy - * @throws BuilderException - */ - public Policy setTriggerPolicy(String name, String description, String actor, Target target, String recipe, Map payload, Integer retries, Integer timeout) throws BuilderException; - - /** - * - * Changes the trigger policy to point to another existing Policy. - * - * - * @param id - * @return ControlLoop - * @throws BuilderException - */ - public ControlLoop setTriggerPolicy(String id) throws BuilderException; - - /** - * @return - */ - public boolean isOpenLoop(); - - /** - * @return - * @throws BuilderException - */ - public Policy getTriggerPolicy() throws BuilderException; - - /** - * Simply returns a copy of the ControlLoop information. - * - * - * @return ControlLoop - */ - public ControlLoop getControlLoop(); - - /** - * Creates a policy that is chained to the result of another Policy. - * - * - * @param name - * @param description - * @param actor - * @param target - * @param recipe - * @param retries - * @param timeout - * @param policyID - * @param results - * @return - * @throws BuilderException - */ - public Policy setPolicyForPolicyResult(String name, String description, String actor, - Target target, String recipe, Map payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) throws BuilderException; - - - /** - * Sets the policy result(s) to an existing Operational Policy. - * - * - * @param policyResultID - * @param policyID - * @param results - * @return - * @throws BuilderException - */ - public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results) throws BuilderException; - - /** - * Removes an Operational Policy. Be mindful that if any other Operational Policies have results that point to this policy, any - * policies that have results pointing to this policy will have their result reset to the appropriate default FINAL_* result. - * - * - * @param policyID - * @return - * @throws BuilderException - */ - public boolean removePolicy(String policyID) throws BuilderException; - - /** - * Resets a policy's results to defualt FINAL_* codes. - * - * - * @return Policy - * @throws BuilderException - Policy does not exist - */ - public Policy resetPolicyResults(String policyID) throws BuilderException; - - /** - * Removes all existing Operational Policies and reverts back to an Open Loop. - * - * @return - */ - public ControlLoopPolicyBuilder removeAllPolicies(); - - /** - * Adds an operationsAccumulateParams to an existing operational policy - * - * @return Policy - * @throws BuilderException - Policy does not exist - */ - public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException; - - /** - * This will compile and build the YAML specification for the Control Loop Policy. Please iterate the Results object for details. - * The Results object will contains warnings and errors. If the specification compiled successfully, you will be able to retrieve the - * YAML. - * - * @return Results - */ - public Results buildSpecification(); - - /** - * The Factory is used to build a ControlLoopPolicyBuilder implementation. - * - * @author pameladragosh - * - */ - public static class Factory { - private Factory(){ - // Private Constructor. - } - - /** - * Builds a basic Control Loop with an overall timeout. Use this method if you wish to create an OpenLoop, or if you - * want to interactively build a Closed Loop. - * - * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. - * @param timeout - Overall timeout for the Closed Loop to execute. - * @return ControlLoopPolicyBuilder object - * @throws BuilderException - */ - public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout) throws BuilderException { - return new ControlLoopPolicyBuilderImpl(controlLoopName, timeout); - } - - /** - * Build a Control Loop for a resource and services associated with the resource. - * - * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. - * @param timeout - Overall timeout for the Closed Loop to execute. - * @param resource - Resource this closed loop is for. Should come from ASDC, but if not available use resourceName to distinguish. - * @param services - Zero or more services associated with this resource. Should come from ASDC, but if not available use serviceName to distinguish. - * @return ControlLoopPolicyBuilder object - * @throws BuilderException - */ - public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout, Resource resource, Service... services) throws BuilderException { - - ControlLoopPolicyBuilder builder = new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, resource, services); - - return builder; - } - - /** - * @param controlLoopName - * @param timeout - * @param service - * @param resources - * @return - * @throws BuilderException - */ - public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout, Service service, Resource... resources) throws BuilderException { - - ControlLoopPolicyBuilder builder = new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, service, resources); - - return builder; - } - } - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/Message.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/Message.java deleted file mode 100644 index 35aa3666f..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/Message.java +++ /dev/null @@ -1,29 +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.controlloop.policy.builder; - -public interface Message { - - public String getMessage(); - - public MessageLevel getLevel(); - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/MessageLevel.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/MessageLevel.java deleted file mode 100644 index 3c09d3813..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/MessageLevel.java +++ /dev/null @@ -1,29 +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.controlloop.policy.builder; - -public enum MessageLevel { - INFO, - WARNING, - ERROR, - EXCEPTION - ; - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/Results.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/Results.java deleted file mode 100644 index 172524a78..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/Results.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.controlloop.policy.builder; - -import java.util.List; - -public interface Results { - - public List getMessages(); - - public String getSpecification(); - - public boolean isValid(); - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java deleted file mode 100644 index 036fd75d2..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java +++ /dev/null @@ -1,496 +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.controlloop.policy.builder.impl; - -import java.util.LinkedList; -import java.util.Map; -import java.util.UUID; - -import org.openecomp.policy.asdc.Resource; -import org.openecomp.policy.asdc.Service; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.controlloop.compiler.CompilerException; -import org.openecomp.policy.controlloop.compiler.ControlLoopCompiler; -import org.openecomp.policy.controlloop.compiler.ControlLoopCompilerCallback; -import org.openecomp.policy.controlloop.policy.ControlLoop; -import org.openecomp.policy.controlloop.policy.ControlLoopPolicy; -import org.openecomp.policy.controlloop.policy.FinalResult; -import org.openecomp.policy.controlloop.policy.OperationsAccumulateParams; -import org.openecomp.policy.controlloop.policy.Policy; -import org.openecomp.policy.controlloop.policy.PolicyResult; -import org.openecomp.policy.controlloop.policy.Target; -import org.openecomp.policy.controlloop.policy.builder.BuilderException; -import org.openecomp.policy.controlloop.policy.builder.ControlLoopPolicyBuilder; -import org.openecomp.policy.controlloop.policy.builder.MessageLevel; -import org.openecomp.policy.controlloop.policy.builder.Results; -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.DumperOptions.FlowStyle; -import org.yaml.snakeyaml.Yaml; - -public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { - private static Logger logger = FlexLogger.getLogger(ControlLoopPolicyBuilderImpl.class.getName()); - private ControlLoopPolicy policy; - - public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout) throws BuilderException { - policy = new ControlLoopPolicy(); - ControlLoop controlLoop = new ControlLoop(); - controlLoop.setControlLoopName(controlLoopName); - controlLoop.setTimeout(timeout); - policy.setControlLoop(controlLoop); - } - - public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Resource resource, Service... services) throws BuilderException { - this(controlLoopName, timeout); - this.addResource(resource); - this.addService(services); - } - - public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Service service, Resource[] resources) throws BuilderException { - this(controlLoopName, timeout); - this.addService(service); - this.addResource(resources); - } - - @Override - public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException { - if (services == null) { - throw new BuilderException("Service must not be null"); - } - for (Service service : services) { - if (service.getServiceUUID() == null) { - if (service.getServiceName() == null || service.getServiceName().length() < 1) { - throw new BuilderException("Invalid service - need either a serviceUUID or serviceName"); - } - if(policy.getControlLoop().getServices()==null){ - policy.getControlLoop().setServices(new LinkedList<>()); - } - policy.getControlLoop().getServices().add(service); - } - } - return this; - } - - @Override - public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException { - if (services == null) { - throw new BuilderException("Service must not be null"); - } - if (policy.getControlLoop().getServices() == null) { - throw new BuilderException("No existing services to remove"); - } - for (Service service : services) { - if (service.getServiceUUID() == null) { - if (service.getServiceName() == null || service.getServiceName().length() < 1) { - throw new BuilderException("Invalid service - need either a serviceUUID or serviceName"); - } - } - boolean removed = policy.getControlLoop().getServices().remove(service); - if (!removed) { - throw new BuilderException("Unknown service " + service.getServiceName()); - } - } - return this; - } - - @Override - public ControlLoopPolicyBuilder removeAllServices() throws BuilderException { - policy.getControlLoop().getServices().clear(); - return this; - } - - - @Override - public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException { - if (resources == null) { - throw new BuilderException("resources must not be null"); - } - for (Resource resource : resources) { - if (resource.getResourceUUID() == null) { - if (resource.getResourceName() == null || resource.getResourceName().length() <= 0) { - throw new BuilderException("Invalid resource - need either resourceUUID or resourceName"); - } - } - if(policy.getControlLoop().getResources()==null){ - policy.getControlLoop().setResources(new LinkedList<>()); - } - policy.getControlLoop().getResources().add(resource); - } - return this; - } - - @Override - public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException{ - if (abatement == null) { - throw new BuilderException("abatement must not be null"); - } - policy.getControlLoop().setAbatement(abatement); - return this; - } - - @Override - public ControlLoopPolicyBuilder setTimeout(Integer timeout) { - policy.getControlLoop().setTimeout(timeout); - return this; - } - - @Override - public Policy setTriggerPolicy(String name, String description, String actor, Target target, String recipe, - Map payload, Integer retries, Integer timeout) throws BuilderException { - - Policy trigger = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout); - - policy.getControlLoop().setTrigger_policy(trigger.getId()); - - this.addNewPolicy(trigger); - // - // Return a copy of the policy - // - return new Policy(trigger); - } - - @Override - public Policy setPolicyForPolicyResult(String name, String description, String actor, - Target target, String recipe, Map payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) throws BuilderException { - // - // Find the existing policy - // - Policy existingPolicy = this.findPolicy(policyID); - if (existingPolicy == null) { - throw new BuilderException("Unknown policy " + policyID); - } - // - // Create the new Policy - // - Policy newPolicy = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout); - // - // Connect the results - // - for (PolicyResult result : results) { - switch (result) { - case FAILURE: - existingPolicy.setFailure(newPolicy.getId()); - break; - case FAILURE_EXCEPTION: - existingPolicy.setFailure_exception(newPolicy.getId()); - break; - case FAILURE_RETRIES: - existingPolicy.setFailure_retries(newPolicy.getId()); - break; - case FAILURE_TIMEOUT: - existingPolicy.setFailure_timeout(newPolicy.getId()); - break; - case FAILURE_GUARD: - existingPolicy.setFailure_guard(newPolicy.getId()); - break; - case SUCCESS: - existingPolicy.setSuccess(newPolicy.getId()); - break; - default: - throw new BuilderException("Invalid PolicyResult " + result); - } - } - // - // Add it to our list - // - this.policy.getPolicies().add(newPolicy); - // - // Return a policy to them - // - return new Policy(newPolicy); - } - - private class BuilderCompilerCallback implements ControlLoopCompilerCallback { - - private ResultsImpl results = new ResultsImpl(); - - @Override - public boolean onWarning(String message) { - results.addMessage(new MessageImpl(message, MessageLevel.WARNING)); - return false; - } - - @Override - public boolean onError(String message) { - results.addMessage(new MessageImpl(message, MessageLevel.ERROR)); - return false; - } - } - - @Override - public Results buildSpecification() { - // - // Dump the specification - // - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - options.setPrettyFlow(true); - Yaml yaml = new Yaml(options); - String dumpedYaml = yaml.dump(policy); - // - // This is our callback class for our compiler - // - BuilderCompilerCallback callback = new BuilderCompilerCallback(); - // - // Compile it - // - try { - ControlLoopCompiler.compile(policy, callback); - } catch (CompilerException e) { - logger.error(e.getMessage() + e); - callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION)); - } - // - // Save the spec - // - callback.results.setSpecification(dumpedYaml); - return callback.results; - } - - private void addNewPolicy(Policy policy) { - if (this.policy.getPolicies() == null) { - this.policy.setPolicies(new LinkedList<>()); - } - this.policy.getPolicies().add(policy); - } - - private Policy findPolicy(String id) { - for (Policy policy : this.policy.getPolicies()) { - if (policy.getId().equals(id)) { - return policy; - } - } - return null; - } - - @Override - public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException { - if (resources == null) { - throw new BuilderException("Resource must not be null"); - } - if (policy.getControlLoop().getResources() == null) { - throw new BuilderException("No existing resources to remove"); - } - for (Resource resource : resources) { - if (resource.getResourceUUID() == null) { - if (resource.getResourceName() == null || resource.getResourceName().length() < 1) { - throw new BuilderException("Invalid resource - need either a resourceUUID or resourceName"); - } - } - boolean removed = policy.getControlLoop().getResources().remove(resource); - if (!removed) { - throw new BuilderException("Unknown resource " + resource.getResourceName()); - } - } - return this; - } - - @Override - public ControlLoopPolicyBuilder removeAllResources() throws BuilderException { - policy.getControlLoop().getResources().clear(); - return this; - } - - @Override - public Integer calculateTimeout() { - int sum = 0; - for (Policy policy : this.policy.getPolicies()) { - sum += policy.getTimeout().intValue(); - } - return new Integer(sum); - } - - @Override - public ControlLoop setTriggerPolicy(String id) throws BuilderException { - if (id == null) { - throw new BuilderException("Id must not be null"); - } - Policy trigger = this.findPolicy(id); - if (trigger == null) { - throw new BuilderException("Unknown policy " + id); - } - else { - this.policy.getControlLoop().setTrigger_policy(id); - } - return new ControlLoop(this.policy.getControlLoop()); - } - - @Override - public boolean isOpenLoop() { - if (this.policy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())) { - return true; - } - else { - return false; - } - } - - @Override - public Policy getTriggerPolicy() throws BuilderException { - if (this.policy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())) { - return null; - } - else { - Policy trigger = new Policy(this.findPolicy(this.policy.getControlLoop().getTrigger_policy())); - return trigger; - } - } - - @Override - public ControlLoop getControlLoop() { - ControlLoop loop = new ControlLoop(this.policy.getControlLoop()); - return loop; - } - - @Override - public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results) - throws BuilderException { - // - // Find the existing policy - // - Policy existingPolicy = this.findPolicy(policyID); - if (existingPolicy == null) { - throw new BuilderException(policyID + " does not exist"); - } - if (this.findPolicy(policyResultID) == null) { - throw new BuilderException("Operational policy " + policyResultID + " does not exist"); - } - // - // Connect the results - // - for (PolicyResult result : results) { - switch (result) { - case FAILURE: - existingPolicy.setFailure(policyResultID); - break; - case FAILURE_EXCEPTION: - existingPolicy.setFailure_exception(policyResultID); - break; - case FAILURE_RETRIES: - existingPolicy.setFailure_retries(policyResultID); - break; - case FAILURE_TIMEOUT: - existingPolicy.setFailure_timeout(policyResultID); - break; - case FAILURE_GUARD: - existingPolicy.setFailure_guard(policyResultID); - break; - case SUCCESS: - existingPolicy.setSuccess(policyResultID); - break; - default: - throw new BuilderException("Invalid PolicyResult " + result); - } - } - return new Policy(this.findPolicy(policyResultID)); - } - - @Override - public boolean removePolicy(String policyID) throws BuilderException { - Policy existingPolicy = this.findPolicy(policyID); - if (existingPolicy == null) { - throw new BuilderException("Unknown policy " + policyID); - } - // - // Check if the policy to remove is trigger_policy - // - if (this.policy.getControlLoop().getTrigger_policy().equals(policyID)) { - this.policy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString()); - } - else { - // - // Update policies - // - for (Policy policy : this.policy.getPolicies()) { - int index = this.policy.getPolicies().indexOf(policy); - if (policy.getSuccess().equals(policyID)) { - policy.setSuccess(FinalResult.FINAL_SUCCESS.toString()); - } - if (policy.getFailure().equals(policyID)) { - policy.setFailure(FinalResult.FINAL_FAILURE.toString()); - } - if (policy.getFailure_retries().equals(policyID)) { - policy.setFailure_retries(FinalResult.FINAL_FAILURE_RETRIES.toString()); - } - if (policy.getFailure_timeout().equals(policyID)) { - policy.setFailure_timeout(FinalResult.FINAL_FAILURE_TIMEOUT.toString()); - } - if (policy.getFailure_exception().equals(policyID)) { - policy.setFailure_exception(FinalResult.FINAL_FAILURE_EXCEPTION.toString()); - } - if (policy.getFailure_guard().equals(policyID)) { - policy.setFailure_guard(FinalResult.FINAL_FAILURE_GUARD.toString()); - } - this.policy.getPolicies().set(index, policy); - } - } - // - // remove the policy - // - boolean removed = this.policy.getPolicies().remove(existingPolicy); - return removed; - } - - @Override - public Policy resetPolicyResults(String policyID) throws BuilderException { - Policy existingPolicy = this.findPolicy(policyID); - if (existingPolicy == null) { - throw new BuilderException("Unknown policy " + policyID); - } - // - // reset policy results - // - existingPolicy.setSuccess(FinalResult.FINAL_SUCCESS.toString()); - existingPolicy.setFailure(FinalResult.FINAL_FAILURE.toString()); - existingPolicy.setFailure_retries(FinalResult.FINAL_FAILURE_RETRIES.toString()); - existingPolicy.setFailure_timeout(FinalResult.FINAL_FAILURE_TIMEOUT.toString()); - existingPolicy.setFailure_exception(FinalResult.FINAL_FAILURE_EXCEPTION.toString()); - existingPolicy.setFailure_guard(FinalResult.FINAL_FAILURE_GUARD.toString()); - return new Policy(existingPolicy); - } - - @Override - public ControlLoopPolicyBuilder removeAllPolicies() { - // - // Remove all existing operational policies - // - this.policy.getPolicies().clear(); - // - // Revert controlLoop back to an open loop - // - this.policy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString()); - return this; - } - - @Override - public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException { - Policy existingPolicy = this.findPolicy(policyID); - if (existingPolicy == null) { - throw new BuilderException("Unknown policy " + policyID); - } - // - // Add operationsAccumulateParams to existingPolicy - // - existingPolicy.setOperationsAccumulateParams(operationsAccumulateParams); - return new Policy(existingPolicy); - } - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/MessageImpl.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/MessageImpl.java deleted file mode 100644 index 3938aa899..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/MessageImpl.java +++ /dev/null @@ -1,46 +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.controlloop.policy.builder.impl; - -import org.openecomp.policy.controlloop.policy.builder.Message; -import org.openecomp.policy.controlloop.policy.builder.MessageLevel; - -public class MessageImpl implements Message { - - private String message; - private MessageLevel level; - - public MessageImpl(String message, MessageLevel level) { - this.message = message; - this.level = level; - } - - @Override - public String getMessage() { - return message; - } - - @Override - public MessageLevel getLevel() { - return level; - } - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/ResultsImpl.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/ResultsImpl.java deleted file mode 100644 index 9ab78566e..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/builder/impl/ResultsImpl.java +++ /dev/null @@ -1,55 +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.controlloop.policy.builder.impl; - -import java.util.LinkedList; -import java.util.List; - -import org.openecomp.policy.controlloop.policy.builder.Message; -import org.openecomp.policy.controlloop.policy.builder.Results; - -public class ResultsImpl implements Results { - - private String specification; - private List messages = new LinkedList<>(); - - @Override - public List getMessages() { - return messages; - } - - @Override - public String getSpecification() { - return specification; - } - - @Override - public boolean isValid() { - return this.specification != null; - } - - public void addMessage(Message message) { - this.messages.add(message); - } - - public void setSpecification(String spec) { - this.specification = spec; - } -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java deleted file mode 100644 index 89526c5fd..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Constraint.java +++ /dev/null @@ -1,171 +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.controlloop.policy.guard; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -public class Constraint { - - private Integer freq_limit_per_target; - private Map time_window; - private Map active_time_range; - - private List blacklist; - - public Constraint() { - // Do Nothing empty constructor. - } - - public Integer getFreq_limit_per_target() { - return freq_limit_per_target; - } - - - public void setFreq_limit_per_target(Integer freq_limit_per_target) { - this.freq_limit_per_target = freq_limit_per_target; - } - - - public Map getTime_window() { - return time_window; - } - - - public void setTime_window(Map time_window) { - this.time_window = time_window; - } - - - public Map getActive_time_range() { - return active_time_range; - } - - - public void setActive_time_range(Map active_time_range) { - this.active_time_range = active_time_range; - } - - - public List getBlacklist() { - return blacklist; - } - - public void setBlacklist(List blacklist) { - this.blacklist = blacklist; - } - - public Constraint(Integer freq_limit_per_target, Map time_window) { - this.freq_limit_per_target = freq_limit_per_target; - if(time_window!=null){ - this.time_window = Collections.unmodifiableMap(time_window); - } - } - - public Constraint(List blacklist) { - this.blacklist = new LinkedList<>(blacklist); - } - - public Constraint(Integer freq_limit_per_target, Map time_window, List blacklist) { - this.freq_limit_per_target = freq_limit_per_target; - this.time_window = Collections.unmodifiableMap(time_window); - this.blacklist = new LinkedList<>(blacklist); - } - - public Constraint(Integer freq_limit_per_target, Map time_window, Map active_time_range) { - this(freq_limit_per_target, time_window); - if (active_time_range != null) { - this.active_time_range = Collections.unmodifiableMap(active_time_range); - } - } - - public Constraint(Integer freq_limit_per_target, Map time_window, Map active_time_range, List blacklist) { - this(freq_limit_per_target, time_window); - if (active_time_range != null) { - this.active_time_range = Collections.unmodifiableMap(active_time_range); - } - if(blacklist!=null){ - this.blacklist = new LinkedList<>(blacklist); - } - } - - public Constraint(Constraint constraint) { - this.freq_limit_per_target = constraint.freq_limit_per_target; - this.time_window = constraint.time_window; - if (constraint.active_time_range != null) { - this.active_time_range = Collections.unmodifiableMap(constraint.active_time_range); - } - this.blacklist = new LinkedList<>(constraint.blacklist); - } - - public boolean isValid() { - return ((freq_limit_per_target == null && time_window != null)|| (time_window == null && freq_limit_per_target != null))? false : true; - } - - @Override - public String toString() { - return "Constraint [freq_limit_per_target=" + freq_limit_per_target + ", time_window=" + time_window + ", active_time_range=" + active_time_range + ", blacklist=" + blacklist + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((freq_limit_per_target == null) ? 0 : freq_limit_per_target.hashCode()); - result = prime * result + ((time_window == null) ? 0 : time_window.hashCode()); - result = prime * result + ((active_time_range == null) ? 0 : active_time_range.hashCode()); - result = prime * result + ((blacklist == null) ? 0 : blacklist.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Constraint other = (Constraint) obj; - if (freq_limit_per_target == null) { - if (other.freq_limit_per_target != null) - return false; - } else if (!freq_limit_per_target.equals(other.freq_limit_per_target)) - return false; - if (time_window == null) { - if (other.time_window != null) - return false; - } else if (!time_window.equals(other.time_window)) - return false; - if (active_time_range == null) { - if (other.active_time_range != null) - return false; - } else if (!active_time_range.equals(other.active_time_range)) - return false; - if (blacklist == null) { - if (other.blacklist != null) - return false; - } else if (!blacklist.equals(other.blacklist)) - return false; - return true; - } -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java deleted file mode 100644 index 3df2a0885..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuard.java +++ /dev/null @@ -1,92 +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.controlloop.policy.guard; - -import java.util.LinkedList; - -public class ControlLoopGuard { - - private Guard guard; - - private LinkedList guards; - - public ControlLoopGuard() { - //DO Nothing Empty Constructor - } - - public Guard getGuard() { - return guard; - } - - public void setGuard(Guard guard) { - this.guard = guard; - } - - public LinkedList getGuards() { - return guards; - } - - public void setGuards(LinkedList guards) { - this.guards = guards; - } - - public ControlLoopGuard(ControlLoopGuard cLGuard) { - this.guard = new Guard(); - this.guards = new LinkedList<>(cLGuard.guards); - } - - @Override - public String toString() { - return "Guard [guard=" + guard + ", GuardPolicies=" + guards + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((guard == null) ? 0 : guard.hashCode()); - result = prime * result + ((guards == null) ? 0 : guards.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ControlLoopGuard other = (ControlLoopGuard) obj; - if (guard == null) { - if (other.guard != null) - return false; - } else if (!guard.equals(other.guard)) - return false; - if (guards == null) { - if (other.guards != null) - return false; - } else if (!guards.equals(other.guards)) - return false; - return true; - } - - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopParameter.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopParameter.java deleted file mode 100644 index e65b9810f..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopParameter.java +++ /dev/null @@ -1,89 +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.controlloop.policy.guard; - -public class ControlLoopParameter { - private String controlLoopName; - private String version; - - public String getControlLoopName() { - return controlLoopName; - } - - public void setControlLoopName(String controlLoopName) { - this.controlLoopName = controlLoopName; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public ControlLoopParameter(String controlLoopName, String version) { - super(); - this.controlLoopName = controlLoopName; - this.version = version; - } - - public ControlLoopParameter(ControlLoopParameter cl) { - - this.controlLoopName = cl.controlLoopName; - this.version = cl.version; - } - - @Override - public String toString() { - return "ControlLoopParameter [controlLoopName=" + controlLoopName + ", version=" + version + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((controlLoopName == null) ? 0 : controlLoopName.hashCode()); - result = prime * result + ((version == null) ? 0 : version.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ControlLoopParameter other = (ControlLoopParameter) obj; - if (controlLoopName == null) { - if (other.controlLoopName != null) - return false; - } else if (!controlLoopName.equals(other.controlLoopName)) - return false; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - return true; - } -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Guard.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Guard.java deleted file mode 100644 index ee0327c3d..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/Guard.java +++ /dev/null @@ -1,67 +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.controlloop.policy.guard; - -public class Guard { - - private static final String DEFAULTVERSION = "2.0.0"; - - private String version = DEFAULTVERSION; - - public Guard() { - //DO Nothing empty Constructor. - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - @Override - public String toString() { - return "Guard [version=" + version + "]"; - } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((version == null) ? 0 : version.hashCode()); - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Guard other = (Guard) obj; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - return true; - } -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.java deleted file mode 100644 index 830736b42..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/GuardPolicy.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.controlloop.policy.guard; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.UUID; - -public class GuardPolicy { - - private String id = UUID.randomUUID().toString(); - private String name; - private String description; - private MatchParameters match_parameters; - private LinkedList limit_constraints; - - public GuardPolicy() { - //Do Nothing Empty Constructor. - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - 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; - } - - public MatchParameters getMatch_parameters() { - return match_parameters; - } - - public void setMatch_parameters(MatchParameters match_parameters) { - this.match_parameters = match_parameters; - } - - public LinkedList getLimit_constraints() { - return limit_constraints; - } - - public void setLimit_constraints(LinkedList limit_constraints) { - this.limit_constraints = limit_constraints; - } - - public GuardPolicy(String id) { - this.id = id; - } - - public GuardPolicy(String name, MatchParameters matchParameters) { - this.name = name; - this.match_parameters = matchParameters; - } - - public GuardPolicy(String id, String name, String description, MatchParameters matchParameters) { - this(name, matchParameters); - this.id = id; - this.description = description; - } - - public GuardPolicy(String name, MatchParameters matchParameters, List limitConstraints) { - this(name, matchParameters); - if (limit_constraints != null) { - this.limit_constraints = (LinkedList) Collections.unmodifiableList(limitConstraints); - } - } - - public GuardPolicy(String name, String description, MatchParameters matchParameters, List limitConstraints) { - this(name, matchParameters, limitConstraints); - this.description = description; - } - - public GuardPolicy(String id, String name, String description, MatchParameters matchParameters, List limitConstraints) { - this(name, description, matchParameters, limitConstraints); - this.id = id; - } - - public GuardPolicy(GuardPolicy policy) { - this.id = policy.id; - this.name = policy.name; - this.description = policy.description; - this.match_parameters = new MatchParameters(policy.match_parameters); - if (policy.limit_constraints != null) { - this.limit_constraints = (LinkedList) Collections.unmodifiableList(policy.limit_constraints); - } - } - - public boolean isValid() { - return (id==null || name ==null)? false : true; - } - - @Override - public String toString() { - return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", match_parameters=" - +match_parameters + ", limitConstraints=" + limit_constraints + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((limit_constraints == null) ? 0 : limit_constraints.hashCode()); - result = prime * result + ((match_parameters == null) ? 0 : match_parameters.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - GuardPolicy other = (GuardPolicy) obj; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (limit_constraints == null) { - if (other.limit_constraints != null) - return false; - } else if (!limit_constraints.equals(other.limit_constraints)) - return false; - if (match_parameters==null){ - if(other.match_parameters !=null) - return false; - } else if(!match_parameters.equals(other.match_parameters)) - return false; - return true; - } - - -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/MatchParameters.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/MatchParameters.java deleted file mode 100644 index 3696ab438..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/MatchParameters.java +++ /dev/null @@ -1,142 +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.controlloop.policy.guard; - -import java.util.LinkedList; -import java.util.List; - -public class MatchParameters { - private String controlLoopName; - private String actor; - private String recipe; - private List targets; - - public MatchParameters() { - // Do Nothing Empty Constructor. - } - - public String getControlLoopName() { - return controlLoopName; - } - - public void setControlLoopName(String controlLoopName) { - this.controlLoopName = controlLoopName; - } - - public String getActor() { - return actor; - } - - public void setActor(String actor) { - this.actor = actor; - } - - public String getRecipe() { - return recipe; - } - - public void setRecipe(String recipe) { - this.recipe = recipe; - } - - public List getTargets() { - return targets; - } - - public void setTargets(List targets) { - this.targets = targets; - } - - public MatchParameters(String actor, String recipe) { - this.actor = actor; - this.recipe = recipe; - } - - public MatchParameters(String actor, String recipe, List targets) { - this(actor, recipe); - if (targets != null) { - this.targets = new LinkedList<>(targets); - } - } - - public MatchParameters(String controlLoopName, String actor, String recipe, List targets) { - this(actor, recipe, targets); - this.controlLoopName = controlLoopName; - } - - public MatchParameters(MatchParameters matchParameters) { - - this.controlLoopName = matchParameters.controlLoopName; - this.actor = matchParameters.actor; - this.recipe = matchParameters.recipe; - if (matchParameters.targets != null) { - this.targets = new LinkedList<>(matchParameters.targets); - } - } - - @Override - public String toString() { - return "MatchParameters [controlLoopName=" + controlLoopName + ", actor=" + actor + ", recipe=" + recipe - + ", targets=" + targets + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((actor == null) ? 0 : actor.hashCode()); - result = prime * result + ((controlLoopName == null) ? 0 : controlLoopName.hashCode()); - result = prime * result + ((recipe == null) ? 0 : recipe.hashCode()); - result = prime * result + ((targets == null) ? 0 : targets.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - MatchParameters other = (MatchParameters) obj; - if (actor == null) { - if (other.actor != null) - return false; - } else if (!actor.equals(other.actor)) - return false; - if (controlLoopName == null) { - if (other.controlLoopName != null) - return false; - } else if (!controlLoopName.equals(other.controlLoopName)) - return false; - if (recipe == null) { - if (other.recipe != null) - return false; - } else if (!recipe.equals(other.recipe)) - return false; - if (targets == null) { - if (other.targets != null) - return false; - } else if (!targets.equals(other.targets)) - return false; - return true; - } -} \ No newline at end of file diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java deleted file mode 100644 index d55510709..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java +++ /dev/null @@ -1,130 +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.controlloop.policy.guard.builder; - -import org.openecomp.policy.controlloop.policy.builder.BuilderException; -import org.openecomp.policy.controlloop.policy.builder.Results; -import org.openecomp.policy.controlloop.policy.guard.Constraint; -import org.openecomp.policy.controlloop.policy.guard.ControlLoopGuard; -import org.openecomp.policy.controlloop.policy.guard.Guard; -import org.openecomp.policy.controlloop.policy.guard.GuardPolicy; -import org.openecomp.policy.controlloop.policy.guard.builder.impl.ControlLoopGuardBuilderImpl; - -public interface ControlLoopGuardBuilder { - - /** - * Adds one or more guard policies to the Control Loop Guard - * - * - * @param policies - * @return - * @throws BuilderException - */ - public ControlLoopGuardBuilder addGuardPolicy(GuardPolicy... policies) throws BuilderException; - - /** - * Removes one or more guard policies from the Control Loop Guard - * - * - * @param policies - * @return - * @throws BuilderException - */ - public ControlLoopGuardBuilder removeGuardPolicy(GuardPolicy... policies) throws BuilderException; - - /** - * Removes all guard policies from the Control Loop Guard - * - * - * @param - * @return - * @throws BuilderException - */ - public ControlLoopGuardBuilder removeAllGuardPolicies() throws BuilderException; - - /** - * Adds one or more time limit constraints to the guard policy - * - * - * @param id (guard policy id) - * @param constraints - * @return - * @throws BuilderException - */ - public ControlLoopGuardBuilder addLimitConstraint(String id, Constraint... constraints) throws BuilderException; - - /** - * Removes one or more time limit constraints from the guard policy - * - * - * @param id (guard policy id) - * @param constraints - * @return - * @throws BuilderException - */ - public ControlLoopGuardBuilder removeLimitConstraint(String id, Constraint... constraints) throws BuilderException; - - /** - * Removes all time limit constraints from the guard policy - * - * - * @param id (guard policy id) - * @return - * @throws BuilderException - */ - public ControlLoopGuardBuilder removeAllLimitConstraints(String id) throws BuilderException; - - /** - * Simply return a copy of control loop guard - * - * @return ControlLoopGuard - */ - public ControlLoopGuard getControlLoopGuard(); - - /** - * This will compile and build the YAML specification for the Control Loop Guard. Please iterate the Results object for details. - * The Results object will contains warnings and errors. If the specification compiled successfully, you will be able to retrieve the - * YAML. - * - * @return Results - */ - public Results buildSpecification(); - - /** - * The Factory is used to build a ControlLoopGuardBuilder implementation. - * - */ - public static class Factory { - - private Factory(){ - //Do Nothing Private Constructor. - } - /** - * @param guard - * @return ControlLoopGuardBuilder object - * @throws BuilderException - */ - public static ControlLoopGuardBuilder buildControlLoopGuard (Guard guard) throws BuilderException { - - return new ControlLoopGuardBuilderImpl(guard); - - } - } -} diff --git a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java b/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java deleted file mode 100644 index 2e5711914..000000000 --- a/ECOMP-ControlloopPolicy/src/main/java/org/openecomp/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java +++ /dev/null @@ -1,244 +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.controlloop.policy.guard.builder.impl; - -import java.util.LinkedList; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.controlloop.compiler.CompilerException; -import org.openecomp.policy.controlloop.compiler.ControlLoopCompilerCallback; -import org.openecomp.policy.controlloop.guard.compiler.ControlLoopGuardCompiler; -import org.openecomp.policy.controlloop.policy.builder.BuilderException; -import org.openecomp.policy.controlloop.policy.builder.MessageLevel; -import org.openecomp.policy.controlloop.policy.builder.Results; -import org.openecomp.policy.controlloop.policy.builder.impl.MessageImpl; -import org.openecomp.policy.controlloop.policy.builder.impl.ResultsImpl; -import org.openecomp.policy.controlloop.policy.guard.Constraint; -import org.openecomp.policy.controlloop.policy.guard.ControlLoopGuard; -import org.openecomp.policy.controlloop.policy.guard.Guard; -import org.openecomp.policy.controlloop.policy.guard.GuardPolicy; -import org.openecomp.policy.controlloop.policy.guard.builder.ControlLoopGuardBuilder; -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.DumperOptions.FlowStyle; -import org.yaml.snakeyaml.Yaml; - -public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { - private static Logger logger = FlexLogger.getLogger(ControlLoopGuardBuilderImpl.class.getName()); - private ControlLoopGuard cLGuard; - - public ControlLoopGuardBuilderImpl(Guard guard) { - cLGuard = new ControlLoopGuard(); - cLGuard.setGuard(guard); - } - - @Override - public ControlLoopGuardBuilder addGuardPolicy(GuardPolicy... policies) throws BuilderException { - if (policies == null) { - throw new BuilderException("GuardPolicy must not be null"); - } - for (GuardPolicy policy : policies) { - if (!policy.isValid()) { - throw new BuilderException("Invalid guard policy - some required fields are missing"); - } - if (cLGuard.getGuards() == null) { - cLGuard.setGuards(new LinkedList<>()); - } - cLGuard.getGuards().add(policy); - } - return this; - } - - @Override - public ControlLoopGuardBuilder removeGuardPolicy(GuardPolicy... policies) throws BuilderException { - if (policies == null) { - throw new BuilderException("GuardPolicy must not be null"); - } - if (cLGuard.getGuards() == null) { - throw new BuilderException("No existing guard policies to remove"); - } - for (GuardPolicy policy : policies) { - if (!policy.isValid()) { - throw new BuilderException("Invalid guard policy - some required fields are missing"); - } - boolean removed = cLGuard.getGuards().remove(policy); - if (!removed) { - throw new BuilderException("Unknown guard policy: " + policy.getName()); - } - } - return this; - } - - @Override - public ControlLoopGuardBuilder removeAllGuardPolicies() throws BuilderException { - cLGuard.getGuards().clear(); - return this; - } - - @Override - public ControlLoopGuardBuilder addLimitConstraint(String id, Constraint... constraints) throws BuilderException { - if (id == null) { - throw new BuilderException("The id of target guard policy must not be null"); - } - if (constraints == null) { - throw new BuilderException("Constraint much not be null"); - } - if (!addLimitConstraints(id,constraints)) { - throw new BuilderException("No existing guard policy matching the id: " + id); - } - return this; - } - - private boolean addLimitConstraints(String id, Constraint... constraints) throws BuilderException { - boolean exist = false; - for (GuardPolicy policy: cLGuard.getGuards()) { - // - // We could have only one guard policy matching the id - // - if (policy.getId().equals(id)) { - exist = true; - for (Constraint cons: constraints) { - if (!cons.isValid()) { - throw new BuilderException("Invalid guard constraint - some required fields are missing"); - } - if (policy.getLimit_constraints() == null) { - policy.setLimit_constraints(new LinkedList<>()); - } - policy.getLimit_constraints().add(cons); - } - break; - } - } - return exist; - } - - @Override - public ControlLoopGuardBuilder removeLimitConstraint(String id, Constraint... constraints) throws BuilderException { - if (id == null) { - throw new BuilderException("The id of target guard policy must not be null"); - } - if (constraints == null) { - throw new BuilderException("Constraint much not be null"); - } - if (!removeConstraints(id, constraints)) { - throw new BuilderException("No existing guard policy matching the id: " + id); - } - return this; - } - - private boolean removeConstraints(String id, Constraint... constraints) throws BuilderException { - boolean exist = false; - for (GuardPolicy policy: cLGuard.getGuards()) { - // - // We could have only one guard policy matching the id - // - if (policy.getId().equals(id)) { - exist = true; - for (Constraint cons: constraints) { - if (!cons.isValid()) { - throw new BuilderException("Invalid guard constraint - some required fields are missing"); - } - boolean removed = policy.getLimit_constraints().remove(cons); - if (!removed) { - throw new BuilderException("Unknown guard constraint: " + cons); - } - } - break; - } - } - return exist; - } - - @Override - public ControlLoopGuardBuilder removeAllLimitConstraints(String id) throws BuilderException { - if (cLGuard.getGuards() == null || cLGuard.getGuards().isEmpty()) { - throw new BuilderException("No guard policies exist"); - } - if (id == null) { - throw new BuilderException("The id of target guard policy must not be null"); - } - boolean exist = false; - for (GuardPolicy policy: cLGuard.getGuards()) { - if (policy.getId().equals(id)) { - exist = true; - policy.getLimit_constraints().clear(); - } - } - if (!exist) { - throw new BuilderException("No existing guard policy matching the id: " + id); - } - return this; - } - - - private class BuilderCompilerCallback implements ControlLoopCompilerCallback { - - private ResultsImpl results = new ResultsImpl(); - - @Override - public boolean onWarning(String message) { - results.addMessage(new MessageImpl(message, MessageLevel.WARNING)); - return false; - } - - @Override - public boolean onError(String message) { - results.addMessage(new MessageImpl(message, MessageLevel.ERROR)); - return false; - } - } - - @Override - public ControlLoopGuard getControlLoopGuard() { - return new ControlLoopGuard(this.cLGuard); - } - - - @Override - public Results buildSpecification() { - // - // Dump the specification - // - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - options.setPrettyFlow(true); - Yaml yaml = new Yaml(options); - String dumpedYaml = yaml.dump(cLGuard); - // - // This is our callback class for our compiler - // - BuilderCompilerCallback callback = new BuilderCompilerCallback(); - // - // Compile it - // - try { - ControlLoopGuardCompiler.compile(cLGuard, callback); - } catch (CompilerException e) { - logger.error(e.getMessage() + e); - callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION)); - } - // - // Save the spec - // - callback.results.setSpecification(dumpedYaml); - return callback.results; - } - -} diff --git a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompilerTest.java b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompilerTest.java deleted file mode 100644 index d26d094c6..000000000 --- a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopCompilerTest.java +++ /dev/null @@ -1,80 +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.controlloop.compiler; - -import static org.junit.Assert.*; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; - -import org.junit.Test; - -public class ControlLoopCompilerTest { - - @Test - public void testTest() { - try { - this.test("src/test/resources/v1.0.0/test.yaml"); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testBad1() { - try { - this.test("src/test/resources/v1.0.0/bad_trigger_1.yaml"); - } catch (Exception e) { - e.printStackTrace(); - } - } - @Test - public void testBad2() { - try { - this.test("src/test/resources/v1.0.0/bad_trigger_2.yaml"); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testBad() { - try { - this.test("src/test/resources/v1.0.0/bad_policies_1.yaml"); - } catch (Exception e) { - } - } - - public void test(String testFile) throws Exception { - try (InputStream is = new FileInputStream(new File(testFile))) { - ControlLoopCompiler.compile(is, null); - } catch (FileNotFoundException e) { - fail(e.getMessage()); - } catch (IOException e) { - fail(e.getMessage()); - } catch (Exception e) { - throw e; - } - } - -} diff --git a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java deleted file mode 100644 index e2701eefb..000000000 --- a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java +++ /dev/null @@ -1,101 +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.controlloop.compiler; - -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; - -import org.junit.Test; -import org.openecomp.policy.controlloop.guard.compiler.ControlLoopGuardCompiler; - -public class ControlLoopGuardCompilerTest { - - @Test - public void testTest1() { - try { - this.test("src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml"); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testTest2() { - try { - this.test("src/test/resources/v2.0.0-guard/policy_guard_1707_appc.yaml"); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testBad1() { - try { - this.test("src/test/resources/v2.0.0-guard/no_guard_policy.yaml"); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testBad2() { - try { - this.test("src/test/resources/v2.0.0-guard/duplicate_guard_policy.yaml"); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testBad3() { - try { - this.test("src/test/resources/v2.0.0-guard/no_guard_constraint.yaml"); - } catch (Exception e) { - e.printStackTrace(); - } - } - - @Test - public void testBad4() { - try { - this.test("src/test/resources/v2.0.0-guard/duplicate_guard_constraint.yaml"); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public void test(String testFile) throws Exception { - try (InputStream is = new FileInputStream(new File(testFile))) { - ControlLoopGuardCompiler.compile(is, null); - } catch (FileNotFoundException e) { - fail(e.getMessage()); - } catch (IOException e) { - fail(e.getMessage()); - } catch (Exception e) { - throw e; - } - } - -} diff --git a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java deleted file mode 100644 index 713f35787..000000000 --- a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java +++ /dev/null @@ -1,516 +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.controlloop.policy; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.UUID; - -import org.junit.Test; -import org.openecomp.policy.asdc.Resource; -import org.openecomp.policy.asdc.ResourceType; -import org.openecomp.policy.asdc.Service; -import org.openecomp.policy.controlloop.policy.builder.BuilderException; -import org.openecomp.policy.controlloop.policy.builder.ControlLoopPolicyBuilder; -import org.openecomp.policy.controlloop.policy.builder.Message; -import org.openecomp.policy.controlloop.policy.builder.MessageLevel; -import org.openecomp.policy.controlloop.policy.builder.Results; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; -import org.yaml.snakeyaml.error.YAMLException; - - -public class ControlLoopPolicyBuilderTest { - - @Test - public void testControlLoop() { - try { - // - // Create a builder for our policy - // - ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); - // - // Test add services - // - Service vSCP = new Service("vSCP"); - Service vUSP = new Service("vUSP"); - Service vTrinity = new Service("Trinity"); - builder = builder.addService(vSCP, vUSP, vTrinity); - assertTrue(builder.getControlLoop().getServices().size() == 3); - // - // Test remove services - // - builder = builder.removeService(vSCP); - assertTrue(builder.getControlLoop().getServices().size() == 2); - builder = builder.removeAllServices(); - assertTrue(builder.getControlLoop().getServices().size() == 0); - // - // Test add resources - // - Resource vCTS = new Resource("vCTS", ResourceType.VF); - Resource vCOM = new Resource("vCTS", ResourceType.VF); - Resource vRAR = new Resource("vCTS", ResourceType.VF); - builder = builder.addResource(vCTS, vCOM, vRAR); - assertTrue(builder.getControlLoop().getResources().size() == 3); - // - // Test remove resources - // - builder = builder.removeResource(vCTS); - assertTrue(builder.getControlLoop().getResources().size() == 2); - builder = builder.removeAllResources(); - assertTrue(builder.getControlLoop().getResources().size() == 0); - // - // Test set abatement - // - assertFalse(builder.getControlLoop().getAbatement()); - builder = builder.setAbatement(true); - assertTrue(builder.getControlLoop().getAbatement()); - } catch (BuilderException e) { - fail(e.getMessage()); - } - } - - @Test - public void testTimeout() { - try { - // - // Create a builder for our policy - // - ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); - // - // Test setTimeout - // - assertTrue(builder.getControlLoop().getTimeout() == 2400); - builder = builder.setTimeout(800); - assertTrue(builder.getControlLoop().getTimeout() == 800); - // - // Test calculateTimeout - // - Policy trigger = builder.setTriggerPolicy( - "Restart the VM", - "Upon getting the trigger event, restart the VM", - "APPC", - new Target(TargetType.VM), - "Restart", - null, - 2, - 300); - @SuppressWarnings("unused") - Policy onRestartFailurePolicy = builder.setPolicyForPolicyResult( - "Rebuild VM", - "If the restart fails, rebuild it", - "APPC", - new Target(TargetType.VM), - "Rebuild", - null, - 1, - 600, - trigger.getId(), - PolicyResult.FAILURE, - PolicyResult.FAILURE_RETRIES, - PolicyResult.FAILURE_TIMEOUT); - assertTrue(builder.calculateTimeout().equals(new Integer(300 + 600))); - // - } catch (BuilderException e) { - fail(e.getMessage()); - } - } - - @Test - public void testTriggerPolicyMethods() { - try { - ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); - // - // Test isOpenLoop - // - assertTrue(builder.isOpenLoop()); - // - // Test set initial trigger policy - // - Policy triggerPolicy1 = builder.setTriggerPolicy( - "Restart the VM", - "Upon getting the trigger event, restart the VM", - "APPC", - new Target(TargetType.VM), - "Restart", - null, - 2, - 300); - assertTrue(builder.isOpenLoop() == false); - assertTrue(builder.getControlLoop().getTrigger_policy().equals(triggerPolicy1.getId())); - // - // Set trigger policy to a new policy - // - @SuppressWarnings("unused") - Policy triggerPolicy2 = builder.setTriggerPolicy( - "Rebuild the VM", - "Upon getting the trigger event, rebuild the VM", - "APPC", - new Target(TargetType.VM), - "Rebuild", - null, - 2, - 300); - // - // Test set trigger policy to another existing policy - // - @SuppressWarnings("unused") - ControlLoop cl = builder.setTriggerPolicy(triggerPolicy1.getId()); - assertTrue(builder.getControlLoop().getTrigger_policy().equals(triggerPolicy1.getId())); - // - // Test get trigger policy - // - assertTrue(builder.getTriggerPolicy().equals(triggerPolicy1)); - // - } catch (BuilderException e) { - fail(e.getMessage()); - } - } - - @Test - public void testAddRemovePolicies() { - try { - ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); - Policy triggerPolicy = builder.setTriggerPolicy( - "Restart the VM", - "Upon getting the trigger event, restart the VM", - "APPC", - new Target(TargetType.VM), - "Restart", - null, - 2, - 300); - // - // Test create a policy and chain it to the results of trigger policy - // - Policy onRestartFailurePolicy1 = builder.setPolicyForPolicyResult( - "Rebuild VM", - "If the restart fails, rebuild it.", - "APPC", - new Target(TargetType.VM), - "Rebuild", - null, - 1, - 600, - triggerPolicy.getId(), - PolicyResult.FAILURE, - PolicyResult.FAILURE_RETRIES, - PolicyResult.FAILURE_TIMEOUT, - PolicyResult.FAILURE_GUARD); - // - assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy1.getId())); - assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy1.getId())); - assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy1.getId())); - assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(onRestartFailurePolicy1.getId())); - // - // Test remove policy - // - boolean removed = builder.removePolicy(onRestartFailurePolicy1.getId()); - assertTrue(removed); - assertTrue(builder.getTriggerPolicy().getFailure().equals(FinalResult.FINAL_FAILURE.toString())); - assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(FinalResult.FINAL_FAILURE_RETRIES.toString())); - assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())); - assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString())); - // - // Create another policy and chain it to the results of trigger policy - // - Policy onRestartFailurePolicy2 = builder.setPolicyForPolicyResult( - "Rebuild VM", - "If the restart fails, rebuild it.", - "APPC", - new Target(TargetType.VM), - "Rebuild", - null, - 2, - 600, - triggerPolicy.getId(), - PolicyResult.FAILURE, - PolicyResult.FAILURE_RETRIES, - PolicyResult.FAILURE_TIMEOUT); - // - // Test reset policy results - // - triggerPolicy = builder.resetPolicyResults(triggerPolicy.getId()); - assertTrue(builder.getTriggerPolicy().getFailure().equals(FinalResult.FINAL_FAILURE.toString())); - assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(FinalResult.FINAL_FAILURE_RETRIES.toString())); - assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())); - // - // Test set the policy results to an existing operational policy - // - onRestartFailurePolicy2 = builder.setPolicyForPolicyResult( - onRestartFailurePolicy2.getId(), - triggerPolicy.getId(), - PolicyResult.FAILURE, - PolicyResult.FAILURE_RETRIES, - PolicyResult.FAILURE_TIMEOUT); - assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy2.getId())); - assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy2.getId())); - assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy2.getId())); - - // - // Test remove all existing operational policies - // - builder = builder.removeAllPolicies(); - assertTrue(builder.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())); - // - } catch (BuilderException e) { - fail(e.getMessage()); - } - } - - @Test - public void testAddOperationsAccumulateParams() { - try { - ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); - Policy triggerPolicy = builder.setTriggerPolicy( - "Restart the eNodeB", - "Upon getting the trigger event, restart the eNodeB", - "SDNR", - new Target(TargetType.PNF), - "Restart", - null, - 2, - 300); - // - // Add the operationsAccumulateParams - // - triggerPolicy = builder.addOperationsAccumulateParams(triggerPolicy.getId(), new OperationsAccumulateParams("15m", 5)); - assertNotNull(builder.getTriggerPolicy().getOperationsAccumulateParams()); - assertTrue(builder.getTriggerPolicy().getOperationsAccumulateParams().getPeriod().equals("15m")); - assertTrue(builder.getTriggerPolicy().getOperationsAccumulateParams().getLimit() == 5); - // - } catch (BuilderException e) { - fail(e.getMessage()); - } - } - - - @Test - public void testBuildSpecification() { - try { - // - // Create the builder - // - ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 800); - // - // Set the first invalid trigger policy - // - Policy policy1 = builder.setTriggerPolicy( - "Restart the VM", - "Upon getting the trigger event, restart the VM", - null, - null, - "Instantiate", - null, - 2, - 300); - Results results = builder.buildSpecification(); - // - // Check that ERRORs are in results for invalid policy arguments - // - boolean invalid_actor = false; - boolean invalid_recipe = false; - boolean invalid_target = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("Policy actor is null") && m.getLevel() == MessageLevel.ERROR) { - invalid_actor = true; - } - if (m.getMessage().equals("Policy recipe is invalid") && m.getLevel() == MessageLevel.ERROR) { - invalid_recipe = true; - } - if (m.getMessage().equals("Policy target is null") && m.getLevel() == MessageLevel.ERROR) { - invalid_target = true; - } - } - // - assertTrue(invalid_actor); - assertTrue(invalid_recipe); - assertTrue(invalid_target); - // - // Remove the invalid policy - // - //@SuppressWarnings("unused") - boolean removed = builder.removePolicy(policy1.getId()); - assertTrue(removed); - assertTrue(builder.getTriggerPolicy() == null); - // - // Set a valid trigger policy - // - policy1 = builder.setTriggerPolicy( - "Rebuild VM", - "If the restart fails, rebuild it.", - "APPC", - new Target(TargetType.VM), - "Rebuild", - null, - 1, - 600); - // - // Set a second valid trigger policy - // - Policy policy2 = builder.setTriggerPolicy( - "Restart the VM", - "Upon getting the trigger event, restart the VM", - "APPC", - new Target(TargetType.VM), - "Restart", - null, - 2, - 300); - // - // Now, we have policy1 unreachable - // - results = builder.buildSpecification(); - boolean unreachable = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("Policy " + policy1.getId() + " is not reachable.") && m.getLevel() == MessageLevel.WARNING) { - unreachable = true; - break; - } - } - assertTrue(unreachable); - // - // Set policy1 for the failure results of policy2 - // - policy1 = builder.setPolicyForPolicyResult( - policy1.getId(), - policy2.getId(), - PolicyResult.FAILURE, - PolicyResult.FAILURE_RETRIES, - PolicyResult.FAILURE_TIMEOUT); - results = builder.buildSpecification(); - boolean invalid_timeout = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("controlLoop overall timeout is less than the sum of operational policy timeouts.") && m.getLevel() == MessageLevel.ERROR) { - invalid_timeout = true; - break; - } - } - assertTrue(invalid_timeout); - // - // Remove policy2 (revert controlLoop back to open loop) - // - removed = builder.removePolicy(policy2.getId()); - // - // ControlLoop is open loop now, but it still has policies (policy1) - // - results = builder.buildSpecification(); - unreachable = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("Open Loop policy contains policies. The policies will never be invoked.") && m.getLevel() == MessageLevel.WARNING) { - unreachable = true; - break; - } - } - assertTrue(unreachable); - // - } catch (BuilderException e) { - fail(e.getMessage()); - } - } - - - @Test - public void test() { - this.test("src/test/resources/v1.0.0/policy_Test.yaml"); - } - - @Test - public void testEvilYaml() { - try (InputStream is = new FileInputStream(new File("src/test/resources/v1.0.0/test_evil.yaml"))) { - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - yaml.load(is); - } catch (FileNotFoundException e) { - fail(e.getLocalizedMessage()); - } catch (IOException e) { - fail(e.getLocalizedMessage()); - } catch (YAMLException e) { - // - // Should have this - // - } - } - - public void test(String testFile) { - try (InputStream is = new FileInputStream(new File(testFile))) { - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - Object obj = yaml.load(is); - assertNotNull(obj); - assertTrue(obj instanceof ControlLoopPolicy); - ControlLoopPolicy policyTobuild = (ControlLoopPolicy) obj; - // - // Now we're going to try to use the builder to build this. - // - ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop( - policyTobuild.getControlLoop().getControlLoopName(), - policyTobuild.getControlLoop().getTimeout()); - // - // Add services - // - if (policyTobuild.getControlLoop().getServices() != null) { - builder = builder.addService(policyTobuild.getControlLoop().getServices().toArray(new Service[policyTobuild.getControlLoop().getServices().size()])); - } - // - // Add resources - // - if (policyTobuild.getControlLoop().getResources() != null) { - builder = builder.addResource(policyTobuild.getControlLoop().getResources().toArray(new Resource[policyTobuild.getControlLoop().getResources().size()])); - } - // - // Add the policies and be sure to set the trigger policy - // - if (policyTobuild.getPolicies() != null) { - for (Policy policy : policyTobuild.getPolicies()) { - if (policy.getId() == policyTobuild.getControlLoop().getTrigger_policy()) { - builder.setTriggerPolicy(policy.getName(), policy.getDescription(), policy.getActor(), policy.getTarget(), policy.getRecipe(), null, policy.getRetry(), policy.getTimeout()); - } - } - } - - // Question : how to change policy ID and results by using builder ?? - - @SuppressWarnings("unused") - Results results = builder.buildSpecification(); - - } catch (FileNotFoundException e) { - fail(e.getLocalizedMessage()); - } catch (IOException e) { - fail(e.getLocalizedMessage()); - } catch (BuilderException e) { - fail(e.getLocalizedMessage()); - } - - } - -} diff --git a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/ControlLoopPolicyTest.java b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/ControlLoopPolicyTest.java deleted file mode 100644 index 15d327087..000000000 --- a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/ControlLoopPolicyTest.java +++ /dev/null @@ -1,101 +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.controlloop.policy; - -import static org.junit.Assert.*; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; - -import org.junit.Test; -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.DumperOptions.FlowStyle; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; - - -public class ControlLoopPolicyTest { - - @Test - public void test() { - this.test("src/test/resources/v1.0.0/policy_Test.yaml"); - } - - @Test - public void testMultipleService() { - this.test("src/test/resources/v1.0.0/policy_Test_MultipleService.yaml"); - } - - @Test - public void testOpenLoop() { - this.test("src/test/resources/v1.0.0/policy_OpenLoop_1610.yaml"); - } - - @Test - public void testOpenECOMPvDNS() { - this.test("src/test/resources/v2.0.0/policy_OpenECOMP_demo_vDNS.yaml"); - } - - public void test(String testFile) { - try (InputStream is = new FileInputStream(new File(testFile))) { - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); - Object obj = yaml.load(is); - assertNotNull(obj); - assertTrue(obj instanceof ControlLoopPolicy); - dump(obj); - // - // Now dump it to a yaml string - // - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - options.setPrettyFlow(true); - yaml = new Yaml(options); - String dumpedYaml = yaml.dump(obj); - System.out.println(dumpedYaml); - // - // Read that string back into our java object - // - Object newObject = yaml.load(dumpedYaml); - dump(newObject); - assertNotNull(newObject); - assertTrue(newObject instanceof ControlLoopPolicy); - // - // Have to comment it out tentatively since it causes junit to fail. - // Seems we cannot use assertEquals here. Need advice. - // - //assertEquals(newObject, obj); - } catch (FileNotFoundException e) { - fail(e.getLocalizedMessage()); - } catch (IOException e) { - fail(e.getLocalizedMessage()); - } - } - - public void dump(Object obj) { - System.out.println("Dumping " + obj.getClass().getCanonicalName()); - System.out.println(obj.toString()); - } -} diff --git a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java deleted file mode 100644 index 9dff9f33c..000000000 --- a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java +++ /dev/null @@ -1,202 +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.controlloop.policy.guard; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.junit.Test; -import org.openecomp.policy.controlloop.policy.builder.BuilderException; -import org.openecomp.policy.controlloop.policy.builder.Message; -import org.openecomp.policy.controlloop.policy.builder.MessageLevel; -import org.openecomp.policy.controlloop.policy.builder.Results; -import org.openecomp.policy.controlloop.policy.guard.builder.ControlLoopGuardBuilder; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; - -public class ControlLoopGuardBuilderTest { - - @Test - public void testControlLoopGuard() { - try { - // - // Create a builder - // - ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard()); - // - // Assert there is no guard policies yet - // - Results results = builder.buildSpecification(); - boolean no_guard_policies = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("ControlLoop Guard should have at least one guard policies") && m.getLevel() == MessageLevel.ERROR) { - no_guard_policies = true; - break; - } - } - assertTrue(no_guard_policies); - // - // Add a guard policy without limit constraint - // - String clname = "CL_vUSP123"; - LinkedList targets = new LinkedList(); - targets.add("s1"); - targets.add("s2"); - targets.add("s3"); - MatchParameters matchParameters = new MatchParameters(clname, "APPC", "Restart", targets); - GuardPolicy policy1 = new GuardPolicy("id123", "guardpolicy1", "description aaa", matchParameters); - builder = builder.addGuardPolicy(policy1); - // - // Assert there is no limit constraint associated with the only guard policy - // - results = builder.buildSpecification(); - boolean no_constraint = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("Guard policy guardpolicy1 does not have any limit constraint") && m.getLevel() == MessageLevel.ERROR) { - no_constraint = true; - break; - } - } - assertTrue(no_constraint); - // - // Add a constraint to policy1 - // - Map active_time_range = new HashMap(); - active_time_range.put("start", "00:00:00-05:00"); - active_time_range.put("end", "23:59:59-05:00"); - List blacklist = new LinkedList(); - blacklist.add("eNodeB_common_id1"); - blacklist.add("eNodeB_common_id2"); - Map time_window = new HashMap(); - time_window.put("value", "10"); - time_window.put("units", "minute"); - Constraint cons = new Constraint(5, time_window, active_time_range, blacklist); - builder = builder.addLimitConstraint(policy1.getId(), cons); - // - // Add a duplicate constraint to policy1 - // - builder = builder.addLimitConstraint(policy1.getId(), cons); - // - // Assert there are duplicate constraints associated with the only guard policy - // - results = builder.buildSpecification(); - boolean duplicate_constraint = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("Guard policy guardpolicy1 has duplicate limit constraints") && m.getLevel() == MessageLevel.WARNING) { - duplicate_constraint = true; - break; - } - } - assertTrue(duplicate_constraint); - // - // Remove the duplicate constraint - // - builder = builder.removeLimitConstraint(policy1.getId(), cons); - // - // Add a duplicate guard policy - // - builder = builder.addGuardPolicy(policy1); - builder = builder.addLimitConstraint(policy1.getId(), cons); - // - // Assert there are duplicate guard policies - // - results = builder.buildSpecification(); - boolean duplicate_guard_policy = false; - for (Message m : results.getMessages()) { - if (m.getMessage().equals("There are duplicate guard policies") && m.getLevel() == MessageLevel.WARNING) { - duplicate_guard_policy = true; - break; - } - } - assertTrue(duplicate_guard_policy); - // - // Remove the duplicate guard policy - // - builder = builder.removeGuardPolicy(policy1); - // - // Assert there are no Error/Warning message - // - results = builder.buildSpecification(); - assertTrue(results.getMessages().size() == 1); - // - } catch (BuilderException e) { - fail(e.getMessage()); - } - } - - @Test - public void test1() { - this.test("src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml"); - } - - @Test - public void test2() { - this.test("src/test/resources/v2.0.0-guard/policy_guard_1707_appc.yaml"); - } - - public void test(String testFile) { - try (InputStream is = new FileInputStream(new File(testFile))) { - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); - Object obj = yaml.load(is); - assertNotNull(obj); - assertTrue(obj instanceof ControlLoopGuard); - ControlLoopGuard guardTobuild = (ControlLoopGuard) obj; - // - // Now we're going to try to use the builder to build this. - // - ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(guardTobuild.getGuard()); - // - // Add guard policy - // - if (guardTobuild.getGuards() != null) { - builder = builder.addGuardPolicy(guardTobuild.getGuards().toArray(new GuardPolicy[guardTobuild.getGuards().size()])); - } - // - // Build the specification - // - Results results = builder.buildSpecification(); - // - // Print out the specification - // - System.out.println(results.getSpecification()); - // - } catch (FileNotFoundException e) { - fail(e.getLocalizedMessage()); - } catch (IOException e) { - fail(e.getLocalizedMessage()); - } catch (BuilderException e) { - fail(e.getLocalizedMessage()); - } - } -} diff --git a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardTest.java b/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardTest.java deleted file mode 100644 index 4575e594f..000000000 --- a/ECOMP-ControlloopPolicy/src/test/java/org/openecomp/policy/controlloop/policy/guard/ControlLoopGuardTest.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.controlloop.policy.guard; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; - -import org.junit.Test; -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.DumperOptions.FlowStyle; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; - - -public class ControlLoopGuardTest { - - @Test - public void testGuardvDNS() { - this.test("src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml"); - } - - @Test - public void testGuardvUSP() { - this.test("src/test/resources/v2.0.0-guard/policy_guard_1707_appc.yaml"); - } - - public void test(String testFile) { - try (InputStream is = new FileInputStream(new File(testFile))) { - // - // Read the yaml into our Java Object - // - Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); - Object obj = yaml.load(is); - assertNotNull(obj); - assertTrue(obj instanceof ControlLoopGuard); - dump(obj); - // - // Now dump it to a yaml string - // - DumperOptions options = new DumperOptions(); - options.setDefaultFlowStyle(FlowStyle.BLOCK); - options.setPrettyFlow(true); - yaml = new Yaml(options); - String dumpedYaml = yaml.dump(obj); - System.out.println(dumpedYaml); - // - // Read that string back into our java object - // - Object newObject = yaml.load(dumpedYaml); - dump(newObject); - assertNotNull(newObject); - assertTrue(newObject instanceof ControlLoopGuard); - // - // Have to comment it out tentatively since it causes junit to fail. - // Seems we cannot use assertEquals here. Need advice. - // - //assertEquals(newObject, obj); - } catch (FileNotFoundException e) { - fail(e.getLocalizedMessage()); - } catch (IOException e) { - fail(e.getLocalizedMessage()); - } - } - - public void dump(Object obj) { - System.out.println("Dumping " + obj.getClass().getCanonicalName()); - System.out.println(obj.toString()); - } -} diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-59a2ee3fB58045feB5a1-template.yml b/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-59a2ee3fB58045feB5a1-template.yml deleted file mode 100644 index f3e9bc4e4..000000000 --- a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-59a2ee3fB58045feB5a1-template.yml +++ /dev/null @@ -1,1698 +0,0 @@ -tosca_definitions_version: tosca_simple_yaml_1_0 -metadata: - invariantUUID: 4b8d4018-068b-4c33-b9bb-d980798e52c2 - UUID: d7d28881-b24d-4512-bfee-1e2eb335591f - name: 59a2ee3f-b580-45fe-b5a1 - description: vendor software product - type: VF - category: Generic - subcategory: Abstract - resourceVendor: 185c637a-3885-463e-8fd0 - resourceVendorRelease: '1.0' -imports: -- NeutronNet: - file: resource-Neutronnet-template.yml -- NeutronPort: - file: resource-Neutronport-template.yml -- 59a2ee3fB58045feB5a1.nodes.heat.vlb: - file: resource-59a2ee3fb58045feb5a1NodesHeatVlb-template.yml -- 59a2ee3fB58045feB5a1.nodes.heat.vdns: - file: resource-59a2ee3fb58045feb5a1NodesHeatVdns-template.yml -topology_template: - inputs: - vf_module_id: - type: string - description: The vLoadBalancer Module ID is provided by ECOMP - ecomp_private_subnet_id: - type: string - description: Private sub-network that connects ECOMP component and the VNF - repo_url_blob: - type: string - description: URL of the repository that hosts the demo packages - vlb_private_net_cidr: - type: string - description: The CIDR of the vLoadBalancer private network - vlb_private_net_id: - type: string - description: Private network that connects vLoadBalancer with vDNSs - public_net_id: - type: string - default: 00000000-0000-0000-0000-000000000000 - description: Public network that enables remote connection to VNF - demo_artifacts_version: - type: string - description: Artifacts (jar, tar.gz) version used in demo vnfs - ecomp_private_net_id: - type: string - description: Private network that connects ECOMP component and the VNF - pub_key: - type: string - description: Public key to be installed on the compute instance - vlb_private_ip_1: - type: string - description: Private IP address that is assigned to the vLoadBalancer to communicate with ECOMP components - key_name: - type: string - description: Public/Private key pair name - vdns_name_0: - type: string - description: Name of the vDNS - repo_url_artifacts: - type: string - description: URL of the repository that hosts the demo packages - vlb_name_0: - type: string - description: Name of the vLoadBalancer - vdns_private_ip_0: - type: string - description: Private IP address that is assigned to the vDNS to communicate with the vLoadBalancer - vnf_id: - type: string - description: The VNF ID is provided by ECOMP - dcae_collector_ip: - type: string - description: IP address of the DCAE collector - vdns_private_ip_1: - type: string - description: Private IP address that is assigned to the vDNS to communicate with ECOMP components - dcae_collector_port: - type: string - description: Port of the DCAE collector - vlb_image_name: - type: string - default: Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM) - description: Image to be used for compute instance - vlb_flavor_name: - type: string - default: 4 GB General Purpose v1 - description: Type of instance (flavor) to be used - vlb_private_ip_0: - type: string - description: Private IP address that is assigned to the vLoadBalancer to communicate with the vDNSs - ecomp_private_net_cidr: - type: string - description: The CIDR of the protected private network - node_templates: - vdns_private_1_port: - type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port - metadata: - invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 - UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 - version: '1.0' - name: NeutronPort - description: Represents a logical entity that associates between Compute and Network normative types. - type: CP - category: Generic - subcategory: Network Elements - properties: - fixed_ips: - - subnet: - get_input: ecomp_private_subnet_id - ip_address: - get_input: vdns_private_ip_1 - network: - get_input: ecomp_private_net_id - requirements: - - binding: - capability: tosca.capabilities.network.Bindable - node: vdns_0 - relationship: tosca.relationships.network.BindsTo - vlb_private_network: - type: org.openecomp.resource.vl.nodes.heat.network.neutron.Net - metadata: - invariantUUID: 2870cc3a-d6cd-4423-b7f6-2d63619b0eeb - UUID: b7e764ba-17f9-4f0a-ad29-29877766ef21 - version: '1.0' - name: NeutronNet - description: Represents a network service with optional subnets and advanced configurations. - type: VL - category: Generic - subcategory: Network Elements - properties: - network_name: - get_input: vlb_private_net_id - subnets: - vlb_private_subnet: - name: - get_input: vlb_private_net_id - cidr: - get_input: vlb_private_net_cidr - vlb_private_1_port: - type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port - metadata: - invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 - UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 - version: '1.0' - name: NeutronPort - description: Represents a logical entity that associates between Compute and Network normative types. - type: CP - category: Generic - subcategory: Network Elements - properties: - fixed_ips: - - subnet: - get_input: ecomp_private_subnet_id - ip_address: - get_input: vlb_private_ip_1 - network: - get_input: ecomp_private_net_id - requirements: - - binding: - capability: tosca.capabilities.network.Bindable - node: vlb_0 - relationship: tosca.relationships.network.BindsTo - vdns_0: - type: org.openecomp.resource.vfc.59a2ee3fB58045feB5a1.abstact.nodes.heat.vdns - metadata: - invariantUUID: ee585c30-127b-492e-b2c1-871dc61d1dde - UUID: d816cb01-b5d0-4bbb-b614-f7c3e230ab19 - version: '1.0' - name: 59a2ee3fB58045feB5a1.nodes.heat.vdns - description: Not reusable inner VFC - type: VFC - category: Generic - subcategory: Abstract - properties: - key_name: UNSUPPORTED_RESOURCE_my_keypair - flavor: - get_input: vlb_flavor_name - image: - get_input: vlb_image_name - metadata: - vf_module_id: - get_input: vf_module_id - vnf_id: - get_input: vnf_id - user_data_format: RAW - name: - get_input: vdns_name_0 - vlb_private_0_port: - type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port - metadata: - invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 - UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 - version: '1.0' - name: NeutronPort - description: Represents a logical entity that associates between Compute and Network normative types. - type: CP - category: Generic - subcategory: Network Elements - properties: - fixed_ips: - - subnet: vlb_private_network - ip_address: - get_input: vlb_private_ip_0 - network: vlb_private_network - requirements: - - link: - capability: tosca.capabilities.network.Linkable - node: vlb_private_network - relationship: tosca.relationships.network.LinksTo - - binding: - capability: tosca.capabilities.network.Bindable - node: vlb_0 - relationship: tosca.relationships.network.BindsTo - vdns_private_0_port: - type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port - metadata: - invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 - UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 - version: '1.0' - name: NeutronPort - description: Represents a logical entity that associates between Compute and Network normative types. - type: CP - category: Generic - subcategory: Network Elements - properties: - fixed_ips: - - subnet: - get_input: vlb_private_net_id - ip_address: - get_input: vdns_private_ip_0 - network: - get_input: vlb_private_net_id - requirements: - - binding: - capability: tosca.capabilities.network.Bindable - node: vdns_0 - relationship: tosca.relationships.network.BindsTo - vlb_0: - type: org.openecomp.resource.vfc.59a2ee3fB58045feB5a1.abstact.nodes.heat.vlb - metadata: - invariantUUID: f7f1d745-cfb1-4aa9-83fc-31280d0ce513 - UUID: 1821f13e-411f-4b29-87a5-ae935897b2e1 - version: '1.0' - name: 59a2ee3fB58045feB5a1.nodes.heat.vlb - description: Not reusable inner VFC - type: VFC - category: Generic - subcategory: Abstract - properties: - key_name: UNSUPPORTED_RESOURCE_my_keypair - flavor: - get_input: vlb_flavor_name - image: - get_input: vlb_image_name - metadata: - vf_module_id: - get_input: vf_module_id - vnf_id: - get_input: vnf_id - user_data_format: RAW - name: - get_input: vlb_name_0 - groups: - base_vlb: - type: org.openecomp.groups.heat.HeatStack - members: - - vdns_private_1_port - - vlb_private_network - - vlb_private_1_port - - vdns_0 - - vlb_private_0_port - - vdns_private_0_port - - vlb_0 - metadata: - invariantUUID: 097f71b3-90a1-4064-bc83-f76bf30195fe - UUID: 4daf7600-0a06-4515-859a-c45ec11abd29 - version: '1' - name: base_vlb - 59a2ee3fB58045feB5a1..dnsscaling..module-1: - type: org.openecomp.groups.VfModule - members: - - vdns_private_1_port - - vdns_0 - - vdns_private_0_port - metadata: - vfModuleModelName: 59a2ee3fB58045feB5a1..dnsscaling..module-1 - vfModuleModelInvariantUUID: 395d61a9-309b-4c0f-a442-ca47903e231e - vfModuleModelUUID: 40846490-abf4-4e1d-8f1a-2286968fa231 - vfModuleModelVersion: '1' - properties: - vf_module_type: Expansion - vf_module_description: - volume_group: false - 59a2ee3fB58045feB5a1..base_vlb..module-0: - type: org.openecomp.groups.VfModule - members: - - vdns_private_1_port - - vlb_private_network - - vlb_private_1_port - - vdns_0 - - vlb_private_0_port - - vdns_private_0_port - - vlb_0 - metadata: - vfModuleModelName: 59a2ee3fB58045feB5a1..base_vlb..module-0 - vfModuleModelInvariantUUID: 5ae76f74-6324-4835-a86c-0c96d16afd38 - vfModuleModelUUID: 17c4f752-a3da-4f3d-9cc5-1c4d28e5442d - vfModuleModelVersion: '1' - properties: - vf_module_type: Base - vf_module_description: - volume_group: false - dnsscaling: - type: org.openecomp.groups.heat.HeatStack - members: - - vdns_private_1_port - - vdns_0 - - vdns_private_0_port - metadata: - invariantUUID: 7c2971fa-9369-4fed-a449-a5e21c022f97 - UUID: ae8c3b79-77d3-425a-8bab-6558007f8392 - version: '1' - name: dnsscaling - substitution_mappings: - node_type: org.openecomp.resource.vf.59a2ee3fB58045feB5a1 - capabilities: - vdns_0.memory: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM allocated to the instance - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vdns_0.memory.resident: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM used by the instance on the physical machine - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory.resident - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vdns_0.cpu: - type: org.openecomp.capabilities.metric.Ceilometer - description: CPU time used - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Cumulative - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ns - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vdns_0.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vdns_private_0_port.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vdns_0.host: - type: tosca.capabilities.Container - occurrences: - - 1 - - UNBOUNDED - valid_source_types: - - tosca.nodes.SoftwareComponent - properties: - num_cpus: - type: integer - required: false - disk_size: - type: scalar-unit.size - required: false - cpu_frequency: - type: scalar-unit.frequency - required: false - mem_size: - type: scalar-unit.size - required: false - vdns_0.endpoint: - type: tosca.capabilities.Endpoint.Admin - occurrences: - - 1 - - UNBOUNDED - properties: - port_name: - type: string - required: false - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - secure: - type: boolean - default: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - url_path: - type: string - required: false - vlb_private_1_port.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - vlb_0.memory: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM allocated to the instance - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vdns_private_1_port.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - vlb_0.scalable: - type: tosca.capabilities.Scalable - occurrences: - - 1 - - UNBOUNDED - properties: - max_instances: - type: integer - default: 1 - min_instances: - type: integer - default: 1 - default_instances: - type: integer - vlb_0.binding: - type: tosca.capabilities.network.Bindable - occurrences: - - 0 - - UNBOUNDED - vlb_0.vcpus: - type: org.openecomp.capabilities.metric.Ceilometer - description: Average disk latency - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ms - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: vcpus - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vlb_0.instance: - type: org.openecomp.capabilities.metric.Ceilometer - description: Existence of instance - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: instance - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: instance - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vdns_0.os: - type: tosca.capabilities.OperatingSystem - occurrences: - - 1 - - UNBOUNDED - properties: - distribution: - type: string - required: false - type: - type: string - required: false - version: - type: version - required: false - architecture: - type: string - required: false - vlb_private_0_port.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vlb_private_1_port.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vlb_0.cpu: - type: org.openecomp.capabilities.metric.Ceilometer - description: CPU time used - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Cumulative - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ns - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vdns_0.cpu.delta: - type: org.openecomp.capabilities.metric.Ceilometer - description: CPU time used since previous datapoint - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Delta - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ns - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu.delta - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vlb_0.memory.resident: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM used by the instance on the physical machine - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory.resident - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vdns_0.vcpus: - type: org.openecomp.capabilities.metric.Ceilometer - description: Average disk latency - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ms - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: vcpus - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vdns_0.memory.usage: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM used by the instance from the amount of its allocated memory - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory.usage - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vlb_0.cpu.delta: - type: org.openecomp.capabilities.metric.Ceilometer - description: CPU time used since previous datapoint - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Delta - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ns - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu.delta - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vdns_0.instance:type: - type: org.openecomp.capabilities.metric.Ceilometer - description: Existence of instance (OpenStack types) - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: instance - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: instance:type - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vlb_0.os: - type: tosca.capabilities.OperatingSystem - occurrences: - - 1 - - UNBOUNDED - properties: - distribution: - type: string - required: false - type: - type: string - required: false - version: - type: version - required: false - architecture: - type: string - required: false - vlb_private_0_port.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - vlb_0.host: - type: tosca.capabilities.Container - occurrences: - - 1 - - UNBOUNDED - valid_source_types: - - tosca.nodes.SoftwareComponent - properties: - num_cpus: - type: integer - required: false - disk_size: - type: scalar-unit.size - required: false - cpu_frequency: - type: scalar-unit.frequency - required: false - mem_size: - type: scalar-unit.size - required: false - vlb_0.instance:type: - type: org.openecomp.capabilities.metric.Ceilometer - description: Existence of instance (OpenStack types) - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: instance - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: instance:type - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vlb_private_network.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vdns_0.binding: - type: tosca.capabilities.network.Bindable - occurrences: - - 0 - - UNBOUNDED - vlb_private_network.link: - type: tosca.capabilities.network.Linkable - occurrences: - - 0 - - UNBOUNDED - vlb_0.cpu_util: - type: org.openecomp.capabilities.metric.Ceilometer - description: Average CPU utilization - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: '%' - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu_util - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vlb_0.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vdns_private_0_port.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - vdns_0.cpu_util: - type: org.openecomp.capabilities.metric.Ceilometer - description: Average CPU utilization - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: '%' - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu_util - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vdns_0.instance: - type: org.openecomp.capabilities.metric.Ceilometer - description: Existence of instance - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: instance - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: instance - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vlb_private_network.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - vdns_0.scalable: - type: tosca.capabilities.Scalable - occurrences: - - 1 - - UNBOUNDED - properties: - max_instances: - type: integer - default: 1 - min_instances: - type: integer - default: 1 - default_instances: - type: integer - vdns_private_1_port.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vlb_0.memory.usage: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM used by the instance from the amount of its allocated memory - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory.usage - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vlb_0.endpoint: - type: tosca.capabilities.Endpoint.Admin - occurrences: - - 1 - - UNBOUNDED - properties: - port_name: - type: string - required: false - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - secure: - type: boolean - default: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - url_path: - type: string - required: false - requirements: - vdns_0.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vlb_private_1_port.link: - occurrences: - - 1 - - 1 - capability: tosca.capabilities.network.Linkable - relationship: tosca.relationships.network.LinksTo - vlb_private_0_port.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vdns_private_0_port.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vlb_0.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vdns_private_0_port.link: - occurrences: - - 1 - - 1 - capability: tosca.capabilities.network.Linkable - relationship: tosca.relationships.network.LinksTo - vdns_0.local_storage: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Attachment - node: tosca.nodes.BlockStorage - relationship: tosca.relationships.AttachesTo - vlb_private_1_port.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vlb_private_network.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vlb_0.local_storage: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Attachment - node: tosca.nodes.BlockStorage - relationship: tosca.relationships.AttachesTo - vdns_private_1_port.link: - occurrences: - - 1 - - 1 - capability: tosca.capabilities.network.Linkable - relationship: tosca.relationships.network.LinksTo - vdns_private_1_port.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-Eace933104d443b496b8-template.yml b/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-Eace933104d443b496b8-template.yml deleted file mode 100644 index 3ce20b597..000000000 --- a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-Eace933104d443b496b8-template.yml +++ /dev/null @@ -1,2525 +0,0 @@ -tosca_definitions_version: tosca_simple_yaml_1_0 -metadata: - invariantUUID: 06fe411e-d006-4ac3-8b0e-fb4f13cd78d3 - UUID: 172ce7c5-c2e4-4f8d-b66c-edb49e8e548a - name: eace9331-04d4-43b4-96b8 - description: vendor software product - type: VF - category: Generic - subcategory: Abstract - resourceVendor: 31125954-23a0-4d41-95e5 - resourceVendorRelease: '1.0' -imports: -- NeutronPort: - file: resource-Neutronport-template.yml -- Eace933104d443b496b8.nodes.heat.vfw: - file: resource-Eace933104d443b496b8NodesHeatVfw-template.yml -- Eace933104d443b496b8.nodes.heat.vpg: - file: resource-Eace933104d443b496b8NodesHeatVpg-template.yml -- NeutronNet: - file: resource-Neutronnet-template.yml -- Eace933104d443b496b8.nodes.heat.vsn: - file: resource-Eace933104d443b496b8NodesHeatVsn-template.yml -topology_template: - inputs: - vf_module_id: - type: string - description: The vFirewall Module ID is provided by ECOMP - repo_url_blob: - type: string - description: URL of the repository that hosts the demo packages - public_net_id: - type: string - default: 00000000-0000-0000-0000-000000000000 - description: Public network that enables remote connection to VNF - vfw_private_ip_1: - type: string - description: Private IP address that is assigned to the vFirewall to communicate with the vSink - vfw_private_ip_0: - type: string - description: Private IP address that is assigned to the vFirewall to communicate with the vPacketGenerator - vfw_private_ip_2: - type: string - description: Private IP address that is assigned to the vFirewall to communicate with ECOMP components - vfw_name_0: - type: string - description: Name of the vFirewall - vnf_id: - type: string - description: The VNF ID is provided by ECOMP - dcae_collector_ip: - type: string - description: IP address of the DCAE collector - dcae_collector_port: - type: string - description: Port of the DCAE collector - vpg_private_ip_1: - type: string - description: Private IP address that is assigned to the vPacketGenerator to communicate with ECOMP components - vsn_private_ip_0: - type: string - description: Private IP address that is assigned to the vSink to communicate with the vFirewall - vpg_name_0: - type: string - description: Name of the vPacketGenerator - vpg_private_ip_0: - type: string - description: Private IP address that is assigned to the vPacketGenerator to communicate with the vFirewall - vsn_private_ip_1: - type: string - description: Private IP address that is assigned to the vSink to communicate with ECOMP components - protected_private_net_cidr: - type: string - description: The CIDR of the protected private network - ecomp_private_net_cidr: - type: string - description: The CIDR of the protected private network - unprotected_private_net_cidr: - type: string - description: The CIDR of the unprotected private network - ecomp_private_subnet_id: - type: string - description: Private sub-network that connects ECOMP component and the VNF - vsn_name_0: - type: string - description: Name of the vSink - unprotected_private_net_id: - type: string - description: Private network that connects vPacketGenerator with vFirewall - vfw_flavor_name: - type: string - default: 4 GB General Purpose v1 - description: Type of instance (flavor) to be used - demo_artifacts_version: - type: string - description: Artifacts (jar, tar.gz) version used in demo vnfs - ecomp_private_net_id: - type: string - description: Private network that connects ECOMP component and the VNF - pub_key: - type: string - description: Public key to be installed on the compute instance - key_name: - type: string - description: Public/Private key pair name - repo_url_artifacts: - type: string - description: URL of the repository that hosts the demo packages - vfw_image_name: - type: string - default: Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM) - description: Image to be used for compute instance - protected_private_net_id: - type: string - description: Private network that connects vFirewall with vSink - node_templates: - vfw_private_0_port: - type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port - metadata: - invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 - UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 - version: '1.0' - name: NeutronPort - description: Represents a logical entity that associates between Compute and Network normative types. - type: CP - category: Generic - subcategory: Network Elements - properties: - fixed_ips: - - subnet: unprotected_private_network - ip_address: - get_input: vfw_private_ip_0 - network: unprotected_private_network - requirements: - - link: - capability: tosca.capabilities.network.Linkable - node: unprotected_private_network - relationship: tosca.relationships.network.LinksTo - - binding: - capability: tosca.capabilities.network.Bindable - node: vfw_0 - relationship: tosca.relationships.network.BindsTo - vsn_private_1_port: - type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port - metadata: - invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 - UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 - version: '1.0' - name: NeutronPort - description: Represents a logical entity that associates between Compute and Network normative types. - type: CP - category: Generic - subcategory: Network Elements - properties: - fixed_ips: - - subnet: - get_input: ecomp_private_subnet_id - ip_address: - get_input: vsn_private_ip_1 - network: - get_input: ecomp_private_net_id - requirements: - - binding: - capability: tosca.capabilities.network.Bindable - node: vsn_0 - relationship: tosca.relationships.network.BindsTo - unprotected_private_network: - type: org.openecomp.resource.vl.nodes.heat.network.neutron.Net - metadata: - invariantUUID: 2870cc3a-d6cd-4423-b7f6-2d63619b0eeb - UUID: b7e764ba-17f9-4f0a-ad29-29877766ef21 - version: '1.0' - name: NeutronNet - description: Represents a network service with optional subnets and advanced configurations. - type: VL - category: Generic - subcategory: Network Elements - properties: - network_name: - get_input: unprotected_private_net_id - subnets: - unprotected_private_subnet: - cidr: - get_input: unprotected_private_net_cidr - vpg_private_1_port: - type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port - metadata: - invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 - UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 - version: '1.0' - name: NeutronPort - description: Represents a logical entity that associates between Compute and Network normative types. - type: CP - category: Generic - subcategory: Network Elements - properties: - fixed_ips: - - subnet: - get_input: ecomp_private_subnet_id - ip_address: - get_input: vpg_private_ip_1 - network: - get_input: ecomp_private_net_id - requirements: - - binding: - capability: tosca.capabilities.network.Bindable - node: vpg_0 - relationship: tosca.relationships.network.BindsTo - vfw_0: - type: org.openecomp.resource.vfc.Eace933104d443b496b8.abstact.nodes.heat.vfw - metadata: - invariantUUID: 0129e34c-d9fa-442d-bb2c-f925d018000a - UUID: 7fa1f6c7-c6bd-4444-8db2-63334a5aed1b - version: '1.0' - name: Eace933104d443b496b8.nodes.heat.vfw - description: Not reusable inner VFC - type: VFC - category: Generic - subcategory: Abstract - properties: - key_name: UNSUPPORTED_RESOURCE_my_keypair - flavor: - get_input: vfw_flavor_name - image: - get_input: vfw_image_name - metadata: - vf_module_id: - get_input: vf_module_id - vnf_id: - get_input: vnf_id - user_data_format: RAW - name: - get_input: vfw_name_0 - vsn_0: - type: org.openecomp.resource.vfc.Eace933104d443b496b8.abstact.nodes.heat.vsn - metadata: - invariantUUID: b19f6643-3db0-4d73-b280-94d6f21caa71 - UUID: 6dca6eb9-330c-4090-a542-7aca5f446e21 - version: '1.0' - name: Eace933104d443b496b8.nodes.heat.vsn - description: Not reusable inner VFC - type: VFC - category: Generic - subcategory: Abstract - properties: - key_name: UNSUPPORTED_RESOURCE_my_keypair - flavor: - get_input: vfw_flavor_name - image: - get_input: vfw_image_name - metadata: - vf_module_id: - get_input: vf_module_id - vnf_id: - get_input: vnf_id - user_data_format: RAW - name: - get_input: vsn_name_0 - vpg_private_0_port: - type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port - metadata: - invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 - UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 - version: '1.0' - name: NeutronPort - description: Represents a logical entity that associates between Compute and Network normative types. - type: CP - category: Generic - subcategory: Network Elements - properties: - fixed_ips: - - subnet: unprotected_private_network - ip_address: - get_input: vpg_private_ip_0 - network: unprotected_private_network - requirements: - - link: - capability: tosca.capabilities.network.Linkable - node: unprotected_private_network - relationship: tosca.relationships.network.LinksTo - - binding: - capability: tosca.capabilities.network.Bindable - node: vpg_0 - relationship: tosca.relationships.network.BindsTo - vsn_private_0_port: - type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port - metadata: - invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 - UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 - version: '1.0' - name: NeutronPort - description: Represents a logical entity that associates between Compute and Network normative types. - type: CP - category: Generic - subcategory: Network Elements - properties: - fixed_ips: - - subnet: protected_private_network - ip_address: - get_input: vsn_private_ip_0 - network: protected_private_network - requirements: - - link: - capability: tosca.capabilities.network.Linkable - node: protected_private_network - relationship: tosca.relationships.network.LinksTo - - binding: - capability: tosca.capabilities.network.Bindable - node: vsn_0 - relationship: tosca.relationships.network.BindsTo - vfw_private_1_port: - type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port - metadata: - invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 - UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 - version: '1.0' - name: NeutronPort - description: Represents a logical entity that associates between Compute and Network normative types. - type: CP - category: Generic - subcategory: Network Elements - properties: - fixed_ips: - - subnet: protected_private_network - ip_address: - get_input: vfw_private_ip_1 - network: protected_private_network - requirements: - - link: - capability: tosca.capabilities.network.Linkable - node: protected_private_network - relationship: tosca.relationships.network.LinksTo - - binding: - capability: tosca.capabilities.network.Bindable - node: vfw_0 - relationship: tosca.relationships.network.BindsTo - vfw_private_2_port: - type: org.openecomp.resource.cp.nodes.heat.network.neutron.Port - metadata: - invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 - UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 - version: '1.0' - name: NeutronPort - description: Represents a logical entity that associates between Compute and Network normative types. - type: CP - category: Generic - subcategory: Network Elements - properties: - fixed_ips: - - subnet: - get_input: ecomp_private_subnet_id - ip_address: - get_input: vfw_private_ip_2 - network: - get_input: ecomp_private_net_id - requirements: - - binding: - capability: tosca.capabilities.network.Bindable - node: vfw_0 - relationship: tosca.relationships.network.BindsTo - vpg_0: - type: org.openecomp.resource.vfc.Eace933104d443b496b8.abstact.nodes.heat.vpg - metadata: - invariantUUID: 7654ae14-4e98-45bc-a8c0-2c43e1805bb4 - UUID: 5267d6dd-f676-4f98-abec-6387ce6beaf2 - version: '1.0' - name: Eace933104d443b496b8.nodes.heat.vpg - description: Not reusable inner VFC - type: VFC - category: Generic - subcategory: Abstract - properties: - key_name: UNSUPPORTED_RESOURCE_my_keypair - flavor: - get_input: vfw_flavor_name - image: - get_input: vfw_image_name - metadata: - vf_module_id: - get_input: vf_module_id - vnf_id: - get_input: vnf_id - user_data_format: RAW - name: - get_input: vpg_name_0 - protected_private_network: - type: org.openecomp.resource.vl.nodes.heat.network.neutron.Net - metadata: - invariantUUID: 2870cc3a-d6cd-4423-b7f6-2d63619b0eeb - UUID: b7e764ba-17f9-4f0a-ad29-29877766ef21 - version: '1.0' - name: NeutronNet - description: Represents a network service with optional subnets and advanced configurations. - type: VL - category: Generic - subcategory: Network Elements - properties: - network_name: - get_input: protected_private_net_id - subnets: - protected_private_subnet: - cidr: - get_input: protected_private_net_cidr - groups: - base_vfw: - type: org.openecomp.groups.heat.HeatStack - members: - - vfw_private_0_port - - vsn_private_1_port - - unprotected_private_network - - vpg_private_1_port - - vfw_0 - - vsn_0 - - vpg_private_0_port - - vsn_private_0_port - - vfw_private_1_port - - vfw_private_2_port - - vpg_0 - - protected_private_network - metadata: - invariantUUID: 44b0c172-7b61-49b5-a68a-810042087e1f - UUID: 24cb02f0-1d72-441f-a327-22d80180deaa - version: '1' - name: base_vfw - Eace933104d443b496b8..base_vfw..module-0: - type: org.openecomp.groups.VfModule - members: - - vfw_private_0_port - - vsn_private_1_port - - unprotected_private_network - - vpg_private_1_port - - vfw_0 - - vsn_0 - - vpg_private_0_port - - vsn_private_0_port - - vfw_private_1_port - - vfw_private_2_port - - vpg_0 - - protected_private_network - metadata: - vfModuleModelName: Eace933104d443b496b8..base_vfw..module-0 - vfModuleModelInvariantUUID: 58c105fd-9c12-4fb7-8a3e-a5ec280183fb - vfModuleModelUUID: ab251d24-4001-4926-aa5c-c01736b36c68 - vfModuleModelVersion: '1' - properties: - vf_module_type: Base - vf_module_description: - volume_group: false - substitution_mappings: - node_type: org.openecomp.resource.vf.Eace933104d443b496b8 - capabilities: - vfw_0.instance: - type: org.openecomp.capabilities.metric.Ceilometer - description: Existence of instance - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: instance - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: instance - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vfw_0.scalable: - type: tosca.capabilities.Scalable - occurrences: - - 1 - - UNBOUNDED - properties: - max_instances: - type: integer - default: 1 - min_instances: - type: integer - default: 1 - default_instances: - type: integer - vfw_0.instance:type: - type: org.openecomp.capabilities.metric.Ceilometer - description: Existence of instance (OpenStack types) - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: instance - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: instance:type - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - protected_private_network.link: - type: tosca.capabilities.network.Linkable - occurrences: - - 0 - - UNBOUNDED - vsn_0.cpu: - type: org.openecomp.capabilities.metric.Ceilometer - description: CPU time used - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Cumulative - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ns - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vpg_0.instance:type: - type: org.openecomp.capabilities.metric.Ceilometer - description: Existence of instance (OpenStack types) - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: instance - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: instance:type - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - unprotected_private_network.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - vfw_0.memory: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM allocated to the instance - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vpg_0.cpu_util: - type: org.openecomp.capabilities.metric.Ceilometer - description: Average CPU utilization - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: '%' - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu_util - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vpg_0.endpoint: - type: tosca.capabilities.Endpoint.Admin - occurrences: - - 1 - - UNBOUNDED - properties: - port_name: - type: string - required: false - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - secure: - type: boolean - default: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - url_path: - type: string - required: false - vpg_private_0_port.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - vfw_private_1_port.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vfw_private_0_port.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - vpg_0.cpu: - type: org.openecomp.capabilities.metric.Ceilometer - description: CPU time used - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Cumulative - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ns - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vpg_private_1_port.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - vsn_0.vcpus: - type: org.openecomp.capabilities.metric.Ceilometer - description: Average disk latency - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ms - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: vcpus - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vpg_0.cpu.delta: - type: org.openecomp.capabilities.metric.Ceilometer - description: CPU time used since previous datapoint - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Delta - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ns - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu.delta - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vsn_private_1_port.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - vsn_0.cpu_util: - type: org.openecomp.capabilities.metric.Ceilometer - description: Average CPU utilization - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: '%' - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu_util - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vpg_0.instance: - type: org.openecomp.capabilities.metric.Ceilometer - description: Existence of instance - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: instance - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: instance - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vpg_0.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vpg_0.scalable: - type: tosca.capabilities.Scalable - occurrences: - - 1 - - UNBOUNDED - properties: - max_instances: - type: integer - default: 1 - min_instances: - type: integer - default: 1 - default_instances: - type: integer - vpg_0.memory: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM allocated to the instance - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vfw_private_2_port.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - vsn_0.os: - type: tosca.capabilities.OperatingSystem - occurrences: - - 1 - - UNBOUNDED - properties: - distribution: - type: string - required: false - type: - type: string - required: false - version: - type: version - required: false - architecture: - type: string - required: false - vfw_0.memory.resident: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM used by the instance on the physical machine - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory.resident - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vsn_0.scalable: - type: tosca.capabilities.Scalable - occurrences: - - 1 - - UNBOUNDED - properties: - max_instances: - type: integer - default: 1 - min_instances: - type: integer - default: 1 - default_instances: - type: integer - vsn_0.instance: - type: org.openecomp.capabilities.metric.Ceilometer - description: Existence of instance - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: instance - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: instance - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vfw_0.endpoint: - type: tosca.capabilities.Endpoint.Admin - occurrences: - - 1 - - UNBOUNDED - properties: - port_name: - type: string - required: false - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - secure: - type: boolean - default: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - url_path: - type: string - required: false - vsn_0.cpu.delta: - type: org.openecomp.capabilities.metric.Ceilometer - description: CPU time used since previous datapoint - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Delta - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ns - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu.delta - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vfw_0.os: - type: tosca.capabilities.OperatingSystem - occurrences: - - 1 - - UNBOUNDED - properties: - distribution: - type: string - required: false - type: - type: string - required: false - version: - type: version - required: false - architecture: - type: string - required: false - vsn_private_1_port.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vsn_private_0_port.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vfw_0.memory.usage: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM used by the instance from the amount of its allocated memory - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory.usage - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vsn_0.host: - type: tosca.capabilities.Container - occurrences: - - 1 - - UNBOUNDED - valid_source_types: - - tosca.nodes.SoftwareComponent - properties: - num_cpus: - type: integer - required: false - disk_size: - type: scalar-unit.size - required: false - cpu_frequency: - type: scalar-unit.frequency - required: false - mem_size: - type: scalar-unit.size - required: false - vsn_0.memory: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM allocated to the instance - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - unprotected_private_network.link: - type: tosca.capabilities.network.Linkable - occurrences: - - 0 - - UNBOUNDED - vfw_0.host: - type: tosca.capabilities.Container - occurrences: - - 1 - - UNBOUNDED - valid_source_types: - - tosca.nodes.SoftwareComponent - properties: - num_cpus: - type: integer - required: false - disk_size: - type: scalar-unit.size - required: false - cpu_frequency: - type: scalar-unit.frequency - required: false - mem_size: - type: scalar-unit.size - required: false - vsn_private_0_port.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - vfw_private_2_port.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - unprotected_private_network.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vpg_0.vcpus: - type: org.openecomp.capabilities.metric.Ceilometer - description: Average disk latency - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ms - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: vcpus - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vpg_0.binding: - type: tosca.capabilities.network.Bindable - occurrences: - - 0 - - UNBOUNDED - vpg_0.host: - type: tosca.capabilities.Container - occurrences: - - 1 - - UNBOUNDED - valid_source_types: - - tosca.nodes.SoftwareComponent - properties: - num_cpus: - type: integer - required: false - disk_size: - type: scalar-unit.size - required: false - cpu_frequency: - type: scalar-unit.frequency - required: false - mem_size: - type: scalar-unit.size - required: false - vsn_0.binding: - type: tosca.capabilities.network.Bindable - occurrences: - - 0 - - UNBOUNDED - protected_private_network.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - vfw_0.binding: - type: tosca.capabilities.network.Bindable - occurrences: - - 0 - - UNBOUNDED - vpg_0.memory.usage: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM used by the instance from the amount of its allocated memory - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory.usage - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vfw_private_0_port.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vsn_0.endpoint: - type: tosca.capabilities.Endpoint.Admin - occurrences: - - 1 - - UNBOUNDED - properties: - port_name: - type: string - required: false - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - secure: - type: boolean - default: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - url_path: - type: string - required: false - vfw_0.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - protected_private_network.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vfw_0.cpu: - type: org.openecomp.capabilities.metric.Ceilometer - description: CPU time used - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Cumulative - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ns - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vsn_0.instance:type: - type: org.openecomp.capabilities.metric.Ceilometer - description: Existence of instance (OpenStack types) - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: instance - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: instance:type - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vpg_0.os: - type: tosca.capabilities.OperatingSystem - occurrences: - - 1 - - UNBOUNDED - properties: - distribution: - type: string - required: false - type: - type: string - required: false - version: - type: version - required: false - architecture: - type: string - required: false - vsn_0.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vfw_0.vcpus: - type: org.openecomp.capabilities.metric.Ceilometer - description: Average disk latency - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ms - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: vcpus - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vfw_0.cpu.delta: - type: org.openecomp.capabilities.metric.Ceilometer - description: CPU time used since previous datapoint - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Delta - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ns - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu.delta - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vsn_0.memory.resident: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM used by the instance on the physical machine - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory.resident - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vsn_0.memory.usage: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM used by the instance from the amount of its allocated memory - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory.usage - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vfw_private_1_port.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - vfw_0.cpu_util: - type: org.openecomp.capabilities.metric.Ceilometer - description: Average CPU utilization - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: '%' - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu_util - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vpg_0.memory.resident: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM used by the instance on the physical machine - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory.resident - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - vpg_private_0_port.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - vpg_private_1_port.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - requirements: - vsn_private_1_port.link: - occurrences: - - 1 - - 1 - capability: tosca.capabilities.network.Linkable - relationship: tosca.relationships.network.LinksTo - vfw_0.local_storage: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Attachment - node: tosca.nodes.BlockStorage - relationship: tosca.relationships.AttachesTo - vfw_private_1_port.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vpg_private_1_port.link: - occurrences: - - 1 - - 1 - capability: tosca.capabilities.network.Linkable - relationship: tosca.relationships.network.LinksTo - vsn_0.local_storage: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Attachment - node: tosca.nodes.BlockStorage - relationship: tosca.relationships.AttachesTo - protected_private_network.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vfw_private_2_port.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vfw_private_2_port.link: - occurrences: - - 1 - - 1 - capability: tosca.capabilities.network.Linkable - relationship: tosca.relationships.network.LinksTo - unprotected_private_network.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vsn_private_0_port.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vpg_0.local_storage: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Attachment - node: tosca.nodes.BlockStorage - relationship: tosca.relationships.AttachesTo - vsn_private_1_port.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vfw_0.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vpg_0.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vpg_private_1_port.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vsn_0.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vpg_private_0_port.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - vfw_private_0_port.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-57e66ea70ed645c7970f-template.yml b/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-57e66ea70ed645c7970f-template.yml deleted file mode 100644 index b59c85269..000000000 --- a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-57e66ea70ed645c7970f-template.yml +++ /dev/null @@ -1,677 +0,0 @@ -tosca_definitions_version: tosca_simple_yaml_1_0 -metadata: - invariantUUID: 5cfe6f4a-41bc-4247-8674-ebd4b98e35cc - UUID: 0f40bba5-986e-4b3c-803f-ddd1b7b25f24 - name: 57e66ea7-0ed6-45c7-970f - description: catalog service description - type: Service - category: Network L1-3 - serviceEcompNaming: false - serviceHoming: false -imports: -- eace9331-04d4-43b4-96b8: - file: resource-Eace933104d443b496b8-template.yml -topology_template: - node_templates: - eace9331-04d4-43b4-96b8 1: - type: org.openecomp.resource.vf.Eace933104d443b496b8 - metadata: - invariantUUID: 06fe411e-d006-4ac3-8b0e-fb4f13cd78d3 - UUID: 172ce7c5-c2e4-4f8d-b66c-edb49e8e548a - version: '1.0' - name: eace9331-04d4-43b4-96b8 - description: vendor software product - type: VF - category: Generic - subcategory: Abstract - substitution_mappings: - node_type: org.openecomp.service.57e66ea70ed645c7970f - capabilities: - eace9331-04d4-43b4-96b8 1.memory.resident: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM used by the instance on the physical machine - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory.resident - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - eace9331-04d4-43b4-96b8 1.os: - type: tosca.capabilities.OperatingSystem - occurrences: - - 1 - - UNBOUNDED - properties: - distribution: - type: string - required: false - type: - type: string - required: false - version: - type: version - required: false - architecture: - type: string - required: false - eace9331-04d4-43b4-96b8 1.binding: - type: tosca.capabilities.network.Bindable - occurrences: - - 0 - - UNBOUNDED - eace9331-04d4-43b4-96b8 1.host: - type: tosca.capabilities.Container - occurrences: - - 1 - - UNBOUNDED - valid_source_types: - - tosca.nodes.SoftwareComponent - properties: - num_cpus: - type: integer - required: false - disk_size: - type: scalar-unit.size - required: false - cpu_frequency: - type: scalar-unit.frequency - required: false - mem_size: - type: scalar-unit.size - required: false - eace9331-04d4-43b4-96b8 1.instance: - type: org.openecomp.capabilities.metric.Ceilometer - description: Existence of instance - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: instance - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: instance - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - eace9331-04d4-43b4-96b8 1.scalable: - type: tosca.capabilities.Scalable - occurrences: - - 1 - - UNBOUNDED - properties: - max_instances: - type: integer - default: 1 - min_instances: - type: integer - default: 1 - default_instances: - type: integer - eace9331-04d4-43b4-96b8 1.memory: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM allocated to the instance - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - eace9331-04d4-43b4-96b8 1.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - eace9331-04d4-43b4-96b8 1.vcpus: - type: org.openecomp.capabilities.metric.Ceilometer - description: Average disk latency - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ms - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: vcpus - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - eace9331-04d4-43b4-96b8 1.cpu_util: - type: org.openecomp.capabilities.metric.Ceilometer - description: Average CPU utilization - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: '%' - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu_util - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - eace9331-04d4-43b4-96b8 1.cpu.delta: - type: org.openecomp.capabilities.metric.Ceilometer - description: CPU time used since previous datapoint - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Delta - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ns - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu.delta - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - eace9331-04d4-43b4-96b8 1.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - eace9331-04d4-43b4-96b8 1.cpu: - type: org.openecomp.capabilities.metric.Ceilometer - description: CPU time used - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Cumulative - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ns - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - eace9331-04d4-43b4-96b8 1.instance:type: - type: org.openecomp.capabilities.metric.Ceilometer - description: Existence of instance (OpenStack types) - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: instance - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: instance:type - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - eace9331-04d4-43b4-96b8 1.link: - type: tosca.capabilities.network.Linkable - occurrences: - - 0 - - UNBOUNDED - eace9331-04d4-43b4-96b8 1.memory.usage: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM used by the instance from the amount of its allocated memory - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory.usage - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - eace9331-04d4-43b4-96b8 1.endpoint: - type: tosca.capabilities.Endpoint.Admin - occurrences: - - 1 - - UNBOUNDED - properties: - port_name: - type: string - required: false - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - secure: - type: boolean - default: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - url_path: - type: string - required: false - requirements: - eace9331-04d4-43b4-96b8 1.local_storage: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Attachment - node: tosca.nodes.BlockStorage - relationship: tosca.relationships.AttachesTo - eace9331-04d4-43b4-96b8 1.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - eace9331-04d4-43b4-96b8 1.link: - occurrences: - - 1 - - 1 - capability: tosca.capabilities.network.Linkable - relationship: tosca.relationships.network.LinksTo diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-D473899264974dca9db9-template.yml b/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-D473899264974dca9db9-template.yml deleted file mode 100644 index 302cacc0a..000000000 --- a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-D473899264974dca9db9-template.yml +++ /dev/null @@ -1,677 +0,0 @@ -tosca_definitions_version: tosca_simple_yaml_1_0 -metadata: - invariantUUID: dc112d6e-7e73-4777-9c6f-1a7fb5fd1b6f - UUID: 2eea06c6-e1d3-4c3a-b9c4-478c506eeedf - name: d4738992-6497-4dca-9db9 - description: catalog service description - type: Service - category: Network L1-3 - serviceEcompNaming: false - serviceHoming: false -imports: -- 59a2ee3f-b580-45fe-b5a1: - file: resource-59a2ee3fB58045feB5a1-template.yml -topology_template: - node_templates: - 59a2ee3f-b580-45fe-b5a1 1: - type: org.openecomp.resource.vf.59a2ee3fB58045feB5a1 - metadata: - invariantUUID: 4b8d4018-068b-4c33-b9bb-d980798e52c2 - UUID: d7d28881-b24d-4512-bfee-1e2eb335591f - version: '1.0' - name: 59a2ee3f-b580-45fe-b5a1 - description: vendor software product - type: VF - category: Generic - subcategory: Abstract - substitution_mappings: - node_type: org.openecomp.service.D473899264974dca9db9 - capabilities: - 59a2ee3f-b580-45fe-b5a1 1.memory.resident: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM used by the instance on the physical machine - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory.resident - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - 59a2ee3f-b580-45fe-b5a1 1.endpoint: - type: tosca.capabilities.Endpoint.Admin - occurrences: - - 1 - - UNBOUNDED - properties: - port_name: - type: string - required: false - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - secure: - type: boolean - default: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - url_path: - type: string - required: false - 59a2ee3f-b580-45fe-b5a1 1.attachment: - type: tosca.capabilities.Attachment - occurrences: - - 1 - - UNBOUNDED - 59a2ee3f-b580-45fe-b5a1 1.feature: - type: tosca.capabilities.Node - occurrences: - - 1 - - UNBOUNDED - 59a2ee3f-b580-45fe-b5a1 1.binding: - type: tosca.capabilities.network.Bindable - occurrences: - - 0 - - UNBOUNDED - 59a2ee3f-b580-45fe-b5a1 1.vcpus: - type: org.openecomp.capabilities.metric.Ceilometer - description: Average disk latency - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ms - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: vcpus - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - 59a2ee3f-b580-45fe-b5a1 1.host: - type: tosca.capabilities.Container - occurrences: - - 1 - - UNBOUNDED - valid_source_types: - - tosca.nodes.SoftwareComponent - properties: - num_cpus: - type: integer - required: false - disk_size: - type: scalar-unit.size - required: false - cpu_frequency: - type: scalar-unit.frequency - required: false - mem_size: - type: scalar-unit.size - required: false - 59a2ee3f-b580-45fe-b5a1 1.memory.usage: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM used by the instance from the amount of its allocated memory - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory.usage - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - 59a2ee3f-b580-45fe-b5a1 1.instance: - type: org.openecomp.capabilities.metric.Ceilometer - description: Existence of instance - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: instance - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: instance - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - 59a2ee3f-b580-45fe-b5a1 1.scalable: - type: tosca.capabilities.Scalable - occurrences: - - 1 - - UNBOUNDED - properties: - max_instances: - type: integer - default: 1 - min_instances: - type: integer - default: 1 - default_instances: - type: integer - 59a2ee3f-b580-45fe-b5a1 1.cpu_util: - type: org.openecomp.capabilities.metric.Ceilometer - description: Average CPU utilization - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: '%' - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu_util - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - 59a2ee3f-b580-45fe-b5a1 1.instance:type: - type: org.openecomp.capabilities.metric.Ceilometer - description: Existence of instance (OpenStack types) - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: instance - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: instance:type - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - 59a2ee3f-b580-45fe-b5a1 1.cpu.delta: - type: org.openecomp.capabilities.metric.Ceilometer - description: CPU time used since previous datapoint - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Delta - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ns - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu.delta - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - 59a2ee3f-b580-45fe-b5a1 1.memory: - type: org.openecomp.capabilities.metric.Ceilometer - description: Volume of RAM allocated to the instance - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Gauge - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: MB - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: memory - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - 59a2ee3f-b580-45fe-b5a1 1.link: - type: tosca.capabilities.network.Linkable - occurrences: - - 0 - - UNBOUNDED - 59a2ee3f-b580-45fe-b5a1 1.cpu: - type: org.openecomp.capabilities.metric.Ceilometer - description: CPU time used - occurrences: - - 1 - - UNBOUNDED - properties: - initiator: - type: string - default: source - network_name: - type: string - default: PRIVATE - required: false - description: - type: string - description: Description of the metric - required: false - type: - type: string - default: Cumulative - description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. - required: true - ports: - type: map - required: false - entry_schema: - type: PortSpec - secure: - type: boolean - default: false - port_name: - type: string - required: false - unit: - type: string - default: ns - description: Unit of the metric value - required: true - protocol: - type: string - default: tcp - port: - type: PortDef - required: false - name: - type: string - default: cpu - description: Ceilometer metric type name to monitor. (The name ceilometer is using) - required: true - category: - type: string - default: compute - description: Category of the metric, for an example, compute, disk, network, storage and etc. - required: false - url_path: - type: string - required: false - 59a2ee3f-b580-45fe-b5a1 1.os: - type: tosca.capabilities.OperatingSystem - occurrences: - - 1 - - UNBOUNDED - properties: - distribution: - type: string - required: false - type: - type: string - required: false - version: - type: version - required: false - architecture: - type: string - required: false - requirements: - 59a2ee3f-b580-45fe-b5a1 1.local_storage: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Attachment - node: tosca.nodes.BlockStorage - relationship: tosca.relationships.AttachesTo - 59a2ee3f-b580-45fe-b5a1 1.dependency: - occurrences: - - 0 - - UNBOUNDED - capability: tosca.capabilities.Node - node: tosca.nodes.Root - relationship: tosca.relationships.DependsOn - 59a2ee3f-b580-45fe-b5a1 1.link: - occurrences: - - 1 - - 1 - capability: tosca.capabilities.network.Linkable - relationship: tosca.relationships.network.LinksTo diff --git a/ECOMP-PAP-REST/autopush.properties b/ECOMP-PAP-REST/autopush.properties deleted file mode 100644 index 481c33c56..000000000 --- a/ECOMP-PAP-REST/autopush.properties +++ /dev/null @@ -1,22 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PAP-REST -# ================================================================================ -# 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========================================================= -### - -default.policyType= -default.policyScope= diff --git a/ECOMP-PAP-REST/dictionaryItemsAPI.json b/ECOMP-PAP-REST/dictionaryItemsAPI.json deleted file mode 100644 index 4a4219700..000000000 --- a/ECOMP-PAP-REST/dictionaryItemsAPI.json +++ /dev/null @@ -1,52 +0,0 @@ -{ - "dictionary": [{ - "type": "commmon", - "dictionaries": [{ - "name": "attribute", - "table": "Attribute", - "fields": [{ - "name": "xacmlId" - }, { - "name": "description" - }, { - "name": "categoryBean" - }, { - "name": "datatypeBean" - }, { - "name": "priority" - }, { - "name": "attributeValue" - }] - }, { - "name": "ecompname", - "table": "EcompName", - "fields": [{ - "name": "ecompName" - }, { - "name": "description" - }] - }] - }, { - "type": "action", - "dictionaries": [{ - "name": "action", - "table": "ActionPolicyDict", - "fields": [{ - "name": "type" - }, { - "name": "url" - }, { - "name": "method" - }, { - "name": "header" - }, { - "name": "body" - }, { - "name": "attributeName" - }, { - "name": "description" - }] - }] - }] - -} diff --git a/ECOMP-PAP-REST/pip.properties b/ECOMP-PAP-REST/pip.properties deleted file mode 100644 index d9df903e4..000000000 --- a/ECOMP-PAP-REST/pip.properties +++ /dev/null @@ -1,15 +0,0 @@ -# -# Default PIP Configuration from Policy. -# -xacml.pip.engines=AAF,historydb - -### AAF PIP Configuration. -AAF.description=AAFEngine to communicate with AAF to take decisions -AAF.classname=org.openecomp.policy.xacml.std.pip.engines.aaf.AAFEngine -AAF.name=AAFEngine - -# PIP Engine Definition -# -historydb.classname=org.openecomp.policy.xacml.std.pip.engines.OperationHistoryEngine -historydb.issuer=org:onap:xacml:guard:historydb -historydb.name=operationHistoryDB \ No newline at end of file diff --git a/ECOMP-PAP-REST/policyLogger.properties b/ECOMP-PAP-REST/policyLogger.properties deleted file mode 100644 index a597a7a22..000000000 --- a/ECOMP-PAP-REST/policyLogger.properties +++ /dev/null @@ -1,44 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PAP-REST -# ================================================================================ -# 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========================================================= -### - -################################### Set concurrentHashMap and timer info ####################### -#Timer initial delay and the delay between in milliseconds before task is to be execute. -timer.delay.time=1000 -#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. -check.interval= 30000 -#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. -event.expired.time=86400 -#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed -#to remove all expired records from this concurrentHashMap. -concurrentHashMap.limit=5000 -#Size of the concurrentHashMap - when its size drops to this point, stop the Timer -stop.check.point=2500 -################################### Set logging format ############################################# -# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println -logger.type=EELF -#################################### Set level for EELF or SYSTEMOUT logging ################################## -# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all -debugLogger.level=INFO -# Set level for metrics file. Set OFF to disable; set ON to enable -metricsLogger.level=ON -# Set level for error file. Set OFF to disable; set ON to enable -error.level=ON -# Set level for audit file. Set OFF to disable; set ON to enable -audit.level=ON diff --git a/ECOMP-PAP-REST/policyelk.properties b/ECOMP-PAP-REST/policyelk.properties deleted file mode 100644 index a42a83ca7..000000000 --- a/ECOMP-PAP-REST/policyelk.properties +++ /dev/null @@ -1,30 +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========================================================= -### - - -#Elk database url -policy.elk.url=http://localhost:9200 - - -#Policy Database properties -policy.database.driver=com.mysql.jdbc.Driver -policy.database.url=jdbc:mysql://localhost:3306/ecomp_sdk?autoReconnect=true&useSSL=false -policy.database.username=policy_user -policy.database.password=policy_user \ No newline at end of file diff --git a/ECOMP-PAP-REST/pom.xml b/ECOMP-PAP-REST/pom.xml deleted file mode 100644 index 71fefca9b..000000000 --- a/ECOMP-PAP-REST/pom.xml +++ /dev/null @@ -1,344 +0,0 @@ - - - - - - 4.0.0 - ECOMP-PAP-REST - ECOMP-PAP-REST - war - - org.openecomp.policy.engine - PolicyEngineSuite - 1.1.0-SNAPSHOT - - - - - maven-war-plugin - 2.1 - - true - - - src/main/java/ - WEB-INF/classes/ - - hibernate.cfg.xml - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.2 - - 1.8 - 1.8 - - - - - - - - org.openecomp.policy.engine - PolicyEngineUtils - ${project.version} - - - com.att.aft - dme2 - - - org.json - json - - - com.att.nsa - dmaapClient - - - com.att.nsa - cambriaClient - - - com.att.cadi - cadi-aaf - - - - - org.apache.commons - commons-lang3 - 3.4 - - - org.openecomp.policy.engine - ECOMP-PDP - ${project.version} - - - org.json - json - - - - - org.openecomp.policy.common - ECOMP-Logging - ${common-modules.version} - - - org.powermock - powermock-module-junit4 - - - org.powermock - powermock-api-mockito - - - - - javax.servlet - javax.servlet-api - 3.1.0 - - - commons-logging - commons-logging - 1.1.3 - - - javax.servlet - servlet-api - - - - - org.apache.commons - commons-compress - 1.8 - - - commons-fileupload - commons-fileupload - 1.3.1 - - - org.apache.logging.log4j - log4j-core - 2.8.2 - - - log4j - apache-log4j-extras - 1.2.17 - - - commons-io - commons-io - 2.4 - - - io.netty - netty - 3.5.0.Final - - - com.google.guava - guava - 14.0.1 - - - org.eclipse.jgit - org.eclipse.jgit - 3.2.0.201312181205-r - - - junit - junit - 4.11 - test - - - org.apache.tomcat - tomcat-jdbc - 8.0.24 - - - com.h2database - h2 - [1.4.186,) - - - com.github.fge - json-patch - 1.9 - - - org.eclipse.persistence - javax.persistence - 2.1.0 - - - org.eclipse.persistence - eclipselink - 2.6.0 - - - - mysql - mysql-connector-java - 5.1.30 - - - org.springframework - spring-mock - 2.0.8 - - - org.openecomp.policy.engine - ControlloopPolicy - ${project.version} - - - com.mockrunner - mockrunner - 0.3.1 - - - - org.springframework - spring-core - ${springframework.version} - - - org.springframework - spring-web - ${springframework.version} - - - org.springframework - spring-webmvc - ${springframework.version} - - - org.springframework - spring-tx - ${springframework.version} - - - org.springframework - spring-context-support - ${springframework.version} - - - org.springframework - spring-orm - ${springframework.version} - - - - org.hibernate - hibernate-core - ${hibernate.version} - - - org.hibernate - hibernate-validator - 5.1.3.Final - - - - org.json - json - 20160810 - - - com.fasterxml.jackson.core - jackson-annotations - 2.6.3 - - - com.fasterxml.jackson.core - jackson-core - 2.6.3 - - - com.fasterxml.jackson.core - jackson-databind - 2.6.3 - - - com.fasterxml.jackson.module - jackson-module-jaxb-annotations - ${jackson.version} - - - com.fasterxml.jackson.module - jackson-module-jsonSchema - ${jackson.version} - - - com.fasterxml.jackson.dataformat - jackson-dataformat-xml - ${jackson.version} - - - org.elasticsearch - elasticsearch - 5.1.2 - - - io.searchbox - jest - 2.0.4 - - - commons-logging - commons-logging - - - - - args4j - args4j - 2.32 - - - - org.apache.tomcat - tomcat-dbcp - 8.5.9 - - - - - 4.2.0.RELEASE - 4.3.10.Final - 2.0.2 - 2.6.0 - - diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/PAPRestConfig.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/PAPRestConfig.java deleted file mode 100644 index bbacabab0..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/PAPRestConfig.java +++ /dev/null @@ -1,145 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import javax.annotation.PostConstruct; -import javax.sql.DataSource; - -import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; -import org.hibernate.SessionFactory; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; -import org.springframework.transaction.annotation.EnableTransactionManagement; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -@Configuration -@EnableWebMvc -@EnableTransactionManagement -@ComponentScan(basePackages = { "org.openecomp.*", "com.*" }) -public class PAPRestConfig extends WebMvcConfigurerAdapter { - private static final Logger LOGGER = FlexLogger.getLogger(PAPRestConfig.class); - - private static String dbDriver = null; - private static String dbUrl = null; - private static String dbUserName = null; - private static String dbPassword = null; - - @PostConstruct - public void init(){ - Properties prop = new Properties(); - InputStream input = null; - try { - input = new FileInputStream("xacml.pap.properties"); - // load a properties file - prop.load(input); - setDbDriver(prop.getProperty("javax.persistence.jdbc.driver")); - setDbUrl(prop.getProperty("javax.persistence.jdbc.url")); - setDbUserName(prop.getProperty("javax.persistence.jdbc.user")); - setDbPassword(prop.getProperty("javax.persistence.jdbc.password")); - }catch(Exception e){ - LOGGER.error("Exception Occured while loading properties file"+e); - }finally{ - if(input != null){ - try { - input.close(); - } catch (IOException e) { - LOGGER.error("Exception Occured while clsoing the stream"+e); - } - } - } - } - - @Bean(name = "dataSource") - public DataSource getDataSource() { - BasicDataSource dataSource = new BasicDataSource(); - dataSource.setDriverClassName(PAPRestConfig.getDbDriver()); - dataSource.setUrl(PAPRestConfig.getDbUrl()); - dataSource.setUsername(PAPRestConfig.getDbUserName()); - dataSource.setPassword(PAPRestConfig.getDbPassword()); - return dataSource; - } - - @Autowired - @Bean(name = "sessionFactory") - public SessionFactory getSessionFactory(DataSource dataSource) { - LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource); - sessionBuilder.scanPackages("org.openecomp.*", "com.*"); - sessionBuilder.addProperties(getHibernateProperties()); - return sessionBuilder.buildSessionFactory(); - } - - private Properties getHibernateProperties() { - Properties properties = new Properties(); - properties.put("hibernate.show_sql", "true"); - properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); - return properties; - } - - @Autowired - @Bean(name = "transactionManager") - public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) { - return new HibernateTransactionManager(sessionFactory); - } - - public static String getDbDriver() { - return dbDriver; - } - - public static void setDbDriver(String dbDriver) { - PAPRestConfig.dbDriver = dbDriver; - } - - public static String getDbUrl() { - return dbUrl; - } - - public static void setDbUrl(String dbUrl) { - PAPRestConfig.dbUrl = dbUrl; - } - - public static String getDbUserName() { - return dbUserName; - } - - public static void setDbUserName(String dbUserName) { - PAPRestConfig.dbUserName = dbUserName; - } - - public static String getDbPassword() { - return dbPassword; - } - - public static void setDbPassword(String dbPassword) { - PAPRestConfig.dbPassword = dbPassword; - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/WebConfig.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/WebConfig.java deleted file mode 100644 index 069d1ba5b..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/WebConfig.java +++ /dev/null @@ -1,43 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest; - -import javax.servlet.ServletContext; -import javax.servlet.ServletRegistration; - -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -public class WebConfig implements WebApplicationInitializer { - - @Override - public void onStartup(ServletContext container) { - AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); - ctx.register(PAPRestConfig.class); - ctx.setServletContext(container); - ctx.refresh(); - ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(ctx)); - dispatcher.setLoadOnStartup(1); - dispatcher.addMapping("/ecomp/*"); - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java deleted file mode 100644 index c681c9325..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/XACMLPapServlet.java +++ /dev/null @@ -1,2617 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest; - -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.ConnectException; -import java.net.HttpURLConnection; -import java.net.InetAddress; -import java.net.MalformedURLException; -import java.net.SocketTimeoutException; -import java.net.URL; -import java.net.URLDecoder; -import java.net.UnknownHostException; -import java.nio.file.Files; -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.Iterator; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.CopyOnWriteArrayList; - -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.persistence.PersistenceException; -import javax.servlet.Servlet; -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.io.IOUtils; -import org.openecomp.policy.common.ia.IntegrityAudit; -import org.openecomp.policy.common.im.AdministrativeStateException; -import org.openecomp.policy.common.im.ForwardProgressException; -import org.openecomp.policy.common.im.IntegrityMonitor; -import org.openecomp.policy.common.im.IntegrityMonitorProperties; -import org.openecomp.policy.common.im.StandbyStatusException; -import org.openecomp.policy.common.logging.ECOMPLoggingContext; -import org.openecomp.policy.common.logging.ECOMPLoggingUtils; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.components.AutoPushPolicy; -import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDao; -import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; -import org.openecomp.policy.pap.xacml.rest.handler.APIRequestHandler; -import org.openecomp.policy.pap.xacml.rest.handler.PushPolicyHandler; -import org.openecomp.policy.pap.xacml.rest.handler.SavePolicyHandler; -import org.openecomp.policy.pap.xacml.restAuth.CheckPDP; -import org.openecomp.policy.rest.XACMLRest; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.utils.PolicyUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.api.pap.ECOMPPapEngineFactory; -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.StdItemSetChangeListener; -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.FactoryException; -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Splitter; - -/** - * Servlet implementation class XacmlPapServlet - */ -@WebServlet( - description = "Implements the XACML PAP RESTful API.", - urlPatterns = { "/" }, - loadOnStartup=1, - initParams = { - @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", description = "The location of the properties file holding configuration information.") - }) -public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable { - private static final long serialVersionUID = 1L; - private static final Logger LOGGER = FlexLogger.getLogger(XACMLPapServlet.class); - // audit (transaction) LOGGER - private static final Logger auditLogger = FlexLogger.getLogger("auditLogger"); - //Persistence Unit for JPA - private static final String PERSISTENCE_UNIT = "XACML-PAP-REST"; - private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU"; - // Client Headers. - private static final String ENVIRONMENT_HEADER = "Environment"; - /* - * List of Admin Console URLs. - * Used to send notifications when configuration changes. - * - * The CopyOnWriteArrayList *should* protect from concurrency errors. - * This list is seldom changed but often read, so the costs of this approach make sense. - */ - private static final CopyOnWriteArrayList adminConsoleURLStringList = new CopyOnWriteArrayList(); - - private static String CONFIG_HOME; - private static String ACTION_HOME; - /* - * This PAP instance's own URL. - * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process. - */ - private static String papURL = null; - // The heartbeat thread. - private static Heartbeat heartbeat = null; - private static Thread heartbeatThread = null; - //The entity manager factory for JPA access - private static EntityManagerFactory emf; - private static PolicyDBDao policyDBDao; - /* - * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes. - */ - private static PAPPolicyEngine papEngine = null; - /* - * These are the parameters needed for DB access from the PAP - */ - private static int papIntegrityAuditPeriodSeconds = -1; - private static String papDbDriver = null; - private static String papDbUrl = null; - private static String papDbUser = null; - private static String papDbPassword = null; - private static Integer papTransWait = null; - private static Integer papTransTimeout = null; - private static Integer papAuditTimeout = null; - private static Boolean papAuditFlag = null; - private static Boolean papFileSystemAudit = null; - private static Boolean autoPushFlag = false; - private static String papResourceName = null; - private static Integer fpMonitorInterval = null; - private static Integer failedCounterThreshold = null; - private static Integer testTransInterval = null; - private static Integer writeFpcInterval = null; - private static String papSiteName=null; - private static String papNodeType=null; - private static String papDependencyGroups = null; - private static String[] papDependencyGroupsFlatArray = null; - private static String environment = null; - private static String pdpFile = null; - - private String storedRequestId = null; - private IntegrityMonitor im; - private IntegrityAudit ia; - - //MicroService Model Properties - private static String msEcompName; - private static String msPolicyName; - /* - * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when - * this servlet starts. Its configurable by the admin. - */ - private Thread initiateThread = null; - private ECOMPLoggingContext baseLoggingContext = null; - private AutoPushPolicy autoPushPolicy; - - /** - * @see HttpServlet#HttpServlet() - */ - public XACMLPapServlet() { - super(); - } - - /** - * @see Servlet#init(ServletConfig) - */ - public void init(ServletConfig config) throws ServletException { - try { - // Logging - baseLoggingContext = new ECOMPLoggingContext(); - // fixed data that will be the same in all logging output goes here - try { - String hostname = InetAddress.getLocalHost().getCanonicalHostName(); - baseLoggingContext.setServer(hostname); - } catch (UnknownHostException e) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging"); - } - // Initialize - XACMLRest.xacmlInit(config); - // Load the properties - XACMLRest.loadXacmlProperties(null, null); - /* - * Retrieve the property values - */ - CONFIG_HOME = getConfigHome(); - ACTION_HOME = getActionHome(); - papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER); - if(papDbDriver == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry"); - throw new PAPException("papDbDriver is null"); - } - setPapDbDriver(papDbDriver); - papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); - if(papDbUrl == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry"); - throw new PAPException("papDbUrl is null"); - } - setPapDbUrl(papDbUrl); - papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER); - if(papDbUser == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry"); - throw new PAPException("papDbUser is null"); - } - setPapDbUser(papDbUser); - papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD); - if(papDbPassword == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry"); - throw new PAPException("papDbPassword is null"); - } - setPapDbPassword(papDbPassword); - papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME); - if(papResourceName == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry"); - throw new PAPException("papResourceName is null"); - } - papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME); - if(papSiteName == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry"); - throw new PAPException("papSiteName is null"); - } - papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE); - if(papNodeType == null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papNodeType property entry"); - throw new PAPException("papNodeType is null"); - } - environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); - //Integer will throw an exception of anything is missing or unrecognized - papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); - papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)); - papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); - //Boolean will default to false if anything is missing or unrecognized - papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG)); - papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG)); - //PAP Auto Push - autoPushFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PUSH_FLAG)); - // if Auto push then Load with properties. - if(autoPushFlag){ - String file; - try{ - file = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PUSH_FILE); - if(file.endsWith(".properties")){ - autoPushPolicy = new AutoPushPolicy(file); - }else{ - throw new PAPException(); - } - }catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Missing property or not a proper property file check for: " + XACMLRestProperties.PROP_PAP_PUSH_FILE ); - LOGGER.info("Overriding the autoPushFlag to False..."); - autoPushFlag = false; - } - } - papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS); - if(papDependencyGroups == null){ - throw new PAPException("papDependencyGroups is null"); - } - try{ - //Now we have flattened the array into a simple comma-separated list - papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]"); - //clean up the entries - for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){ - papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim(); - } - try{ - if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){ - papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim()); - } - }catch(Exception e){ - String msg = "integrity_audit_period_seconds "; - LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n"); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry"); - throw e; - } - }catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry"); - throw e; - } - //Integer will throw an exception of anything is missing or unrecognized - fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL)); - failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD)); - testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL)); - writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL)); - LOGGER.debug("\n\n\n**************************************" - + "\n**************************************" - + "\n" - + "\n papDbDriver = " + papDbDriver - + "\n papDbUrl = " + papDbUrl - + "\n papDbUser = " + papDbUser - + "\n papDbPassword = " + papDbPassword - + "\n papTransWait = " + papTransWait - + "\n papTransTimeout = " + papTransTimeout - + "\n papAuditTimeout = " + papAuditTimeout - + "\n papAuditFlag = " + papAuditFlag - + "\n papFileSystemAudit = " + papFileSystemAudit - + "\n autoPushFlag = " + autoPushFlag - + "\n papResourceName = " + papResourceName - + "\n fpMonitorInterval = " + fpMonitorInterval - + "\n failedCounterThreshold = " + failedCounterThreshold - + "\n testTransInterval = " + testTransInterval - + "\n writeFpcInterval = " + writeFpcInterval - + "\n papSiteName = " + papSiteName - + "\n papNodeType = " + papNodeType - + "\n papDependencyGroupsList = " + papDependencyGroups - + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds - + "\n\n**************************************" - + "\n**************************************"); - // Pull custom persistence settings - Properties properties; - try { - properties = XACMLProperties.getProperties(); - LOGGER.debug("\n\n\n**************************************" - + "\n**************************************" - + "\n\n" - + "properties = " + properties - + "\n\n**************************************"); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: " - + "XACMLProperties.getProperties()"); - throw new ServletException(e.getMessage(), e.getCause()); - } - //Micro Service Properties - msEcompName=properties.getProperty("xacml.policy.msEcompName"); - setMsEcompName(msEcompName); - msPolicyName=properties.getProperty("xacml.policy.msPolicyName"); - setMsPolicyName(msPolicyName); - // PDPId File location - XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); - if (XACMLPapServlet.pdpFile == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: " - + XACMLRestProperties.PROP_PDP_IDFILE); - throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. "); - } - // Create an IntegrityMonitor - im = IntegrityMonitor.getInstance(papResourceName,properties); - // Create an IntegrityAudit - ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties); - ia.startAuditThread(); - // Create the entity manager factory - emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties); - if (emf == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: " - + PERSISTENCE_UNIT); - throw new ServletException("Unable to create Entity Manager Factory"); - } - // we are about to call the PDPs and give them their configuration. - // To do that we need to have the URL of this PAP so we can construct the Policy file URLs - XACMLPapServlet.papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); - //Create the policyDBDao - policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf()); - // Load our PAP engine, first create a factory - ECOMPPapEngineFactory factory = ECOMPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY)); - // The factory knows how to go about creating a PAP Engine - XACMLPapServlet.papEngine = (PAPPolicyEngine) factory.newEngine(); - PolicyDBDaoTransaction addNewGroup = null; - try{ - if(((org.openecomp.policy.xacml.std.pap.StdEngine)papEngine).wasDefaultGroupJustAdded){ - addNewGroup = policyDBDao.getNewTransaction(); - EcompPDPGroup group = papEngine.getDefaultGroup(); - addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), "automaticallyAdded"); - addNewGroup.commitTransaction(); - addNewGroup = policyDBDao.getNewTransaction(); - addNewGroup.changeDefaultGroup(group, "automaticallyAdded"); - addNewGroup.commitTransaction(); - } - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Error creating new default group in the database"); - if(addNewGroup != null){ - addNewGroup.rollbackTransaction(); - } - } - policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine); - //boolean performFileToDatabaseAudit = false; - if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){ - //get an AuditTransaction to lock out all other transactions - PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction(); - policyDBDao.auditLocalDatabase(XACMLPapServlet.papEngine); - //release the transaction lock - auditTrans.close(); - } - - // Sanity check for URL. - if (XACMLPapServlet.papURL == null) { - throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + XACMLPapServlet.papURL); - } - // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration - // to all its known PDP nodes. - if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) { - this.initiateThread = new Thread(this); - this.initiateThread.start(); - } - // After startup, the PAP does Heartbeat's to each of the PDPs periodically - XACMLPapServlet.heartbeat = new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine); - XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat); - XACMLPapServlet.heartbeatThread.start(); - - } catch (FactoryException | PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine"); - throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: "+e); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine - unexpected error"); - throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: "+e); - } - } - - /** - * Thread used only during PAP startup to initiate change messages to all known PDPs. - * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced. - */ - @Override - public void run() { - // send the current configuration to all the PDPs that we know about - changed(); - } - - /** - * @see Servlet#destroy() - * - * Depending on how this servlet is run, we may or may not care about cleaning up the resources. - * For now we assume that we do care. - */ - public void destroy() { - // Make sure our threads are destroyed - if (XACMLPapServlet.heartbeatThread != null) { - // stop the heartbeat - try { - if (XACMLPapServlet.heartbeat != null) { - XACMLPapServlet.heartbeat.terminate(); - } - XACMLPapServlet.heartbeatThread.interrupt(); - XACMLPapServlet.heartbeatThread.join(); - } catch (InterruptedException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat"); - } - } - if (this.initiateThread != null) { - try { - this.initiateThread.interrupt(); - this.initiateThread.join(); - } catch (InterruptedException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread"); - } - } - } - - /** - * Called by: - * - PDP nodes to register themselves with the PAP, and - * - Admin Console to make changes in the PDP Groups. - * - * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) - */ - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); - loggingContext.transactionStarted(); - loggingContext.setServiceName("PAP.post"); - if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one"); - } else { - PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)"); - } - PolicyDBDaoTransaction pdpTransaction = null; - try { - im.startTransaction(); - } catch (AdministrativeStateException ae){ - String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative" - + " state of " + im.getStateManager().getAdminState() - + "\n Exception Message: " + ae.getMessage(); - LOGGER.info(message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - }catch (StandbyStatusException se) { - String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status" - + " of " + im.getStateManager().getStandbyStatus() - + "\n Exception Message: " + se.getMessage(); - LOGGER.info(message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - } - try { - XACMLRest.dumpRequest(request); - // since getParameter reads the content string, explicitly get the content before doing that. - // Simply getting the inputStream seems to protect it against being consumed by getParameter. - request.getInputStream(); - String groupId = request.getParameter("groupId"); - String apiflag = request.getParameter("apiflag"); - if(groupId != null) { - // Is this from the Admin Console or API? - if(apiflag!=null && apiflag.equalsIgnoreCase("api")) { - // this is from the API so we need to check the client credentials before processing the request - if(!authorizeRequest(request)){ - String message = "PEP not Authorized for making this Request!!"; - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_FORBIDDEN, message); - im.endTransaction(); - return; - } - } - doACPost(request, response, groupId, loggingContext); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - // Request is from a PDP asking for its config. - loggingContext.setServiceName("PDP:PAP.register"); - // Get the PDP's ID - String id = this.getPDPID(request); - String jmxport = this.getPDPJMX(request); - LOGGER.info("Request(doPost) from PDP coming up: " + id); - // Get the PDP Object - EcompPDP pdp = XACMLPapServlet.papEngine.getPDP(id); - // Is it known? - if (pdp == null) { - LOGGER.info("Unknown PDP: " + id); - // Check PDP ID - if(CheckPDP.validateID(id)){ - pdpTransaction = policyDBDao.getNewTransaction(); - try { - pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister"); - XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport)); - } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException e) { - pdpTransaction.rollbackTransaction(); - String message = "Failed to create new PDP for id: " + id; - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - im.endTransaction(); - return; - } - // get the PDP we just created - pdp = XACMLPapServlet.papEngine.getPDP(id); - if (pdp == null) { - if(pdpTransaction != null){ - pdpTransaction.rollbackTransaction(); - } - String message = "Failed to create new PDP for id: " + id; - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - im.endTransaction(); - return; - } - } else { - String message = "PDP is Unauthorized to Connect to PAP: "+ id; - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); - loggingContext.transactionEnded(); - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration."); - PolicyLogger.audit("Transaction Failed - See Error.log"); - im.endTransaction(); - return; - } - try{ - pdpTransaction.commitTransaction(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Could not commit transaction to put pdp in the database"); - } - } - if (jmxport != null && jmxport != ""){ - ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport)); - } - // Get the PDP's Group - EcompPDPGroup group = XACMLPapServlet.papEngine.getPDPGroup((EcompPDP) pdp); - if (group == null) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default"); - im.endTransaction(); - return; - } - // Determine what group the PDP node is in and get - // its policy/pip properties. - Properties policies = group.getPolicyProperties(); - Properties pipconfig = group.getPipConfigProperties(); - // Get the current policy/pip configuration that the PDP has - Properties pdpProperties = new Properties(); - pdpProperties.load(request.getInputStream()); - LOGGER.info("PDP Current Properties: " + pdpProperties.toString()); - LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null")); - LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null")); - // Validate the node's properties - boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties); - // Send back current configuration - if (isCurrent == false) { - // Tell the PDP we are sending back the current policies/pip config - LOGGER.info("PDP configuration NOT current."); - if (policies != null) { - // Put URL's into the properties in case the PDP needs to - // retrieve them. - this.populatePolicyURL(request.getRequestURL(), policies); - // Copy the properties to the output stream - policies.store(response.getOutputStream(), ""); - } - if (pipconfig != null) { - // Copy the properties to the output stream - pipconfig.store(response.getOutputStream(), ""); - } - // We are good - and we are sending them information - response.setStatus(HttpServletResponse.SC_OK); - setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH); - } else { - // Tell them they are good - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE); - } - // tell the AC that something changed - notifyAC(); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - } catch (PAPException e) { - if(pdpTransaction != null){ - pdpTransaction.rollbackTransaction(); - } - LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(500, e.getMessage()); - im.endTransaction(); - return; - } - //Catch anything that fell through - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended"); - im.endTransaction(); - } - - /** - * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) - */ - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); - loggingContext.transactionStarted(); - loggingContext.setServiceName("PAP.get"); - if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doGet) so we generated one"); - } else { - PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)"); - } - try { - XACMLRest.dumpRequest(request); - String pathInfo = request.getRequestURI(); - LOGGER.info("path info: " + pathInfo); - if (pathInfo != null){ - //DO NOT do a im.startTransaction for the test request - if (pathInfo.equals("/pap/test")) { - testService(loggingContext, response); - return; - } - } - //This im.startTransaction() covers all other Get transactions - try { - im.startTransaction(); - } catch (AdministrativeStateException ae){ - String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative" - + " state of " + im.getStateManager().getAdminState() - + "\n Exception Message: " + ae.getMessage(); - LOGGER.info(message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - }catch (StandbyStatusException se) { - String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status" - + " of " + im.getStateManager().getStandbyStatus() - + "\n Exception Message: " + se.getMessage(); - LOGGER.info(message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - } - // Request from the API to get the gitPath - String apiflag = request.getParameter("apiflag"); - if (apiflag!=null) { - if(authorizeRequest(request)){ - APIRequestHandler apiRequestHandler = new APIRequestHandler(); - apiRequestHandler.doGet(request,response, apiflag); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } else { - String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_FORBIDDEN, message); - im.endTransaction(); - return; - } - } - // Is this from the Admin Console? - String groupId = request.getParameter("groupId"); - if (groupId != null) { - // this is from the Admin Console, so handle separately - doACGet(request, response, groupId, loggingContext); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - // Get the PDP's ID - String id = this.getPDPID(request); - LOGGER.info("doGet from: " + id); - // Get the PDP Object - EcompPDP pdp = XACMLPapServlet.papEngine.getPDP(id); - // Is it known? - if (pdp == null) { - // Check if request came from localhost - if (request.getRemoteHost().equals("localhost") || - request.getRemoteHost().equals("127.0.0.1") || - request.getRemoteHost().equals(request.getLocalAddr())) { - // Return status information - basically all the groups - loggingContext.setServiceName("PAP.getGroups"); - Set groups = papEngine.getEcompPDPGroups(); - // convert response object to JSON and include in the response - ObjectMapper mapper = new ObjectMapper(); - mapper.writeValue(response.getOutputStream(), groups); - response.setHeader("content-type", "application/json"); - response.setStatus(HttpServletResponse.SC_OK); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr(); - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message); - im.endTransaction(); - return; - } - loggingContext.setServiceName("PAP.getPolicy"); - // Get the PDP's Group - EcompPDPGroup group = XACMLPapServlet.papEngine.getPDPGroup((EcompPDP) pdp); - if (group == null) { - String message = "No group associated with pdp " + pdp.getId(); - LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message); - im.endTransaction(); - return; - } - // Which policy do they want? - String policyId = request.getParameter("id"); - if (policyId == null) { - String message = "Did not specify an id for the policy"; - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_NOT_FOUND, message); - im.endTransaction(); - return; - } - PDPPolicy policy = group.getPolicy(policyId); - if (policy == null) { - String message = "Unknown policy: " + policyId; - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_NOT_FOUND, message); - im.endTransaction(); - return; - } - LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n " - + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString()); - try (InputStream is = new FileInputStream(((StdPDPGroup)group).getDirectory().toString()+File.separator+policyId); OutputStream os = response.getOutputStream()) { - // Send the policy back - IOUtils.copy(is, os); - response.setStatus(HttpServletResponse.SC_OK); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - } catch (IOException e) { - String message = "Failed to open policy id " + policyId; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_NOT_FOUND, message); - } - } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(500, e.getMessage()); - im.endTransaction(); - return; - } - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended"); - im.endTransaction(); - } - - /** - * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response) - */ - protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); - storedRequestId = loggingContext.getRequestID(); - loggingContext.transactionStarted(); - loggingContext.setServiceName("PAP.put"); - if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one"); - } else { - PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)"); - } - try { - im.startTransaction(); - } catch (AdministrativeStateException ae){ - String message = "PUT interface called for PAP " + papResourceName + " but it has an Administrative" - + " state of " + im.getStateManager().getAdminState() - + "\n Exception Message: " + ae.getMessage(); - LOGGER.info(message +ae); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - }catch (StandbyStatusException se) { - String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status" - + " of " + im.getStateManager().getStandbyStatus() - + "\n Exception Message: " + se.getMessage(); - LOGGER.info(message +se); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - } - XACMLRest.dumpRequest(request); - //need to check if request is from the API or Admin console - String apiflag = request.getParameter("apiflag"); - //This would occur if a PolicyDBDao notification was received - String policyDBDaoRequestUrl = request.getParameter("policydbdaourl"); - if(policyDBDaoRequestUrl != null){ - String policyDBDaoRequestEntityId = request.getParameter("entityid"); - //String policyDBDaoRequestEntityType = request.getParameter("entitytype"); - String policyDBDaoRequestEntityType = request.getParameter("entitytype"); - String policyDBDaoRequestExtraData = request.getParameter("extradata"); - if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){ - response.sendError(400, "entityid or entitytype not supplied"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this); - response.setStatus(200); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - /* - * Request for ImportService - */ - String importService = request.getParameter("importService"); - if (importService != null) { - if(authorizeRequest(request)){ - APIRequestHandler apiRequestHandler = new APIRequestHandler(); - apiRequestHandler.doPut(request, response, importService); - im.endTransaction(); - return; - } else { - String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; - LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message ); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_FORBIDDEN, message); - return; - } - } - //This would occur if we received a notification of a policy rename from AC - String oldPolicyName = request.getParameter("oldPolicyName"); - String newPolicyName = request.getParameter("newPolicyName"); - if(oldPolicyName != null && newPolicyName != null){ - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("\nXACMLPapServlet.doPut() - before decoding" - + "\npolicyToCreateUpdate = " + " "); - } - //decode it - try{ - oldPolicyName = URLDecoder.decode(oldPolicyName, "UTF-8"); - newPolicyName = URLDecoder.decode(newPolicyName, "UTF-8"); - if(LOGGER.isDebugEnabled()){ - LOGGER.debug("\nXACMLPapServlet.doPut() - after decoding" - + "\npolicyToCreateUpdate = " + " "); - } - } catch(UnsupportedEncodingException e){ - PolicyLogger.error("\nXACMLPapServlet.doPut() - Unsupported URL encoding of policyToCreateUpdate (UTF-8)" - + "\npolicyToCreateUpdate = " + " "); - response.sendError(500,"policyToCreateUpdate encoding not supported" - + "\nfailure with the following exception: " + e); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See error.log"); - im.endTransaction(); - return; - } - //send it to PolicyDBDao - PolicyDBDaoTransaction renameTransaction = policyDBDao.getNewTransaction(); - try{ - renameTransaction.renamePolicy(oldPolicyName,newPolicyName, "XACMLPapServlet.doPut"); - }catch(Exception e){ - renameTransaction.rollbackTransaction(); - response.sendError(500,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) " - + "\nfailure with the following exception: " + e); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See error.log"); - im.endTransaction(); - return; - } - renameTransaction.commitTransaction(); - response.setStatus(HttpServletResponse.SC_OK); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - // - // See if this is Admin Console registering itself with us - // - String acURLString = request.getParameter("adminConsoleURL"); - if (acURLString != null) { - loggingContext.setServiceName("AC:PAP.register"); - // remember this Admin Console for future updates - if ( ! adminConsoleURLStringList.contains(acURLString)) { - adminConsoleURLStringList.add(acURLString); - } - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Admin Console registering with URL: " + acURLString); - } - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - /* - * This is to update the PDP Group with the policy/policies being pushed - * Part of a 2 step process to push policies to the PDP that can now be done - * From both the Admin Console and the PolicyEngine API - */ - String groupId = request.getParameter("groupId"); - if (groupId != null) { - if(apiflag!=null){ - if(!authorizeRequest(request)){ - String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_FORBIDDEN, message); - return; - } - if(apiflag.equalsIgnoreCase("addPolicyToGroup")){ - updateGroupsFromAPI(request, response, groupId, loggingContext); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - } - // this is from the Admin Console, so handle separately - doACPut(request, response, groupId, loggingContext); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - // - // Request is for policy validation and creation - // - if (apiflag != null && apiflag.equalsIgnoreCase("admin")){ - // this request is from the Admin Console - SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance(); - savePolicyHandler.doPolicyAPIPut(request, response); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } else if (apiflag != null && apiflag.equalsIgnoreCase("api")) { - // this request is from the Policy Creation API - if(authorizeRequest(request)){ - APIRequestHandler apiRequestHandler = new APIRequestHandler(); - apiRequestHandler.doPut(request, response, request.getHeader("ClientScope")); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } else { - String message = "PEP not Authorized for making this Request!!"; - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_FORBIDDEN, message); - im.endTransaction(); - return; - } - } - // We do not expect anything from anywhere else. - // This method is here in case we ever need to support other operations. - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See error.log"); - im.endTransaction(); - } - - /** - * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response) - */ - protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); - loggingContext.transactionStarted(); - loggingContext.setServiceName("PAP.delete"); - if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one"); - } else { - PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)"); - } - try { - im.startTransaction(); - } catch (AdministrativeStateException ae){ - String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative" - + " state of " + im.getStateManager().getAdminState() - + "\n Exception Message: " + ae.getMessage(); - LOGGER.info(message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - }catch (StandbyStatusException se) { - String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status" - + " of " + im.getStateManager().getStandbyStatus() - + "\n Exception Message: " + se.getMessage(); - LOGGER.info(message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - } - XACMLRest.dumpRequest(request); - String groupId = request.getParameter("groupId"); - String apiflag = request.getParameter("apiflag"); - if (groupId != null) { - // Is this from the Admin Console or API? - if(apiflag!=null) { - if(!authorizeRequest(request)){ - String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_FORBIDDEN, message); - return; - } - APIRequestHandler apiRequestHandler = new APIRequestHandler(); - try { - apiRequestHandler.doDelete(request, response, loggingContext, apiflag); - } catch (Exception e) { - LOGGER.error("Exception Occured"+e); - } - if(apiRequestHandler.getNewGroup()!=null){ - groupChanged(apiRequestHandler.getNewGroup()); - } - return; - } - // this is from the Admin Console, so handle separately - doACDelete(request, response, groupId, loggingContext); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended Successfully"); - im.endTransaction(); - return; - } - //Catch anything that fell through - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId"); - im.endTransaction(); - } - - private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) { - String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES); - String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); - if (localRootPolicies == null || localReferencedPolicies == null) { - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="+localRootPolicies+" ReferencedPolicies="+localReferencedPolicies); - return false; - } - // Compare the policies and pipconfig properties to the pdpProperties - try { - // the policy properties includes only xacml.rootPolicies and - // xacml.referencedPolicies without any .url entries - Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false); - Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties); - if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) && - localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) && - pdpPipConfig.equals(pipconfig)) { - // The PDP is current - return true; - } - } catch (Exception e) { - // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines, - // or if there are policies that do not have a corresponding ".url" property. - // Either of these cases means that the PDP is not up-to-date, so just drop-through to return false. - PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error"); - } - return false; - } - - private void populatePolicyURL(StringBuffer urlPath, Properties policies) { - String lists[] = new String[2]; - lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES); - lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); - for (String list : lists) { - if (list != null && list.isEmpty() == false) { - for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) { - String url = urlPath + "?id=" + id; - LOGGER.info("Policy URL for " + id + ": " + url); - policies.setProperty(id + ".url", url); - } - } - } - } - - protected String getPDPID(HttpServletRequest request) { - String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID); - if (pdpURL == null || pdpURL.isEmpty()) { - // Should send back its port for identification - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header"); - pdpURL = ""; - } - return pdpURL; - } - - protected String getPDPJMX(HttpServletRequest request) { - String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT); - if (pdpJMMX == null || pdpJMMX.isEmpty()) { - // Should send back its port for identification - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header for JMX Port so the value of 0 is assigned"); - return null; - } - return pdpJMMX; - } - - /** - * Requests from the PolicyEngine API to update the PDP Group with pushed policy - * - * @param request - * @param response - * @param groupId - * @param loggingContext - * @throws ServletException - * @throws IOException - */ - public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws IOException { - PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction(); - try { - // for PUT operations the group may or may not need to exist before the operation can be done - StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId); - // get the request input stream content into a String - String json = null; - java.util.Scanner scanner = new java.util.Scanner(request.getInputStream()); - scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - PolicyLogger.info("JSON request from PolicyEngine API: " + json); - // convert Object sent as JSON into local object - StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class); - Set policies = new HashSet<>(); - if(policy!=null){ - policies.add(policy); - } - //Get the current policies from the Group and Add the new one - Set currentPoliciesInGroup = new HashSet<>(); - currentPoliciesInGroup = group.getPolicies(); - //If the selected policy is in the group we must remove it because the name is default - Iterator policyIterator = policies.iterator(); - LOGGER.debug("policyIterator....." + policies); - while (policyIterator.hasNext()) { - PDPPolicy selPolicy = policyIterator.next(); - for (PDPPolicy existingPolicy : currentPoliciesInGroup) { - if (existingPolicy.getId().equals(selPolicy.getId())) { - group.removePolicyFromGroup(existingPolicy); - LOGGER.debug("Removing policy: " + existingPolicy); - break; - } - } - } - //Update the PDP Group after removing old version of policy - Set updatedPoliciesInGroup = new HashSet<>(); - updatedPoliciesInGroup = group.getPolicies(); - //need to remove the policy with default name from group - for (PDPPolicy updatedPolicy : currentPoliciesInGroup) { - if (updatedPolicy.getName().equalsIgnoreCase("default")) { - group.removePolicyFromGroup(updatedPolicy); - break; - } - } - if(updatedPoliciesInGroup!=null){ - policies.addAll(updatedPoliciesInGroup); - } - group.setPolicies(policies); - // Assume that this is an update of an existing PDP Group - loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup"); - try{ - acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut"); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: " - +"group="+group.getId()); - throw new PAPException(e.getMessage()); - } - papEngine.updateGroup(group); - String policyId = "empty"; - if(policy!=null){ - policyId = policy.getId(); - } - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - response.addHeader("operation", "push"); - response.addHeader("policyId", policyId); - response.addHeader("groupId", groupId); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Group '" + group.getId() + "' updated"); - } - acPutTransaction.commitTransaction(); - notifyAC(); - // Group changed, which might include changing the policies - groupChanged(group); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - - if (policy != null && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) { - PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); - if (pushPolicyHandler.preSafetyCheck(policy, CONFIG_HOME)) { - LOGGER.debug("Precheck Successful."); - } - } - - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } catch (PAPException e) { - acPutTransaction.rollbackTransaction(); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP."; - response.sendError(500, e.getMessage()); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error","addGroupError"); - response.addHeader("message", message); - return; - } - } - - /** - * Requests from the Admin Console for operations not on single specific objects - * - * @param request - * @param response - * @param groupId - * @param loggingContext - * @throws ServletException - * @throws IOException - */ - private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException { - PolicyDBDaoTransaction doACPostTransaction = null; - try { - String groupName = request.getParameter("groupName"); - String groupDescription = request.getParameter("groupDescription"); - String apiflag = request.getParameter("apiflag"); - if (groupName != null && groupDescription != null) { - // Args: group= groupName= groupDescription= <= create a new group - loggingContext.setServiceName("AC:PAP.createGroup"); - String unescapedName = URLDecoder.decode(groupName, "UTF-8"); - String unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8"); - PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction(); - try { - newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost"); - papEngine.newGroup(unescapedName, unescapedDescription); - newGroupTransaction.commitTransaction(); - } catch (Exception e) { - newGroupTransaction.rollbackTransaction(); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group"); - loggingContext.transactionEnded(); - - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(500, "Unable to create new group '" + groupId + "'"); - return; - } - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("New Group '" + groupId + "' created"); - } - // tell the Admin Consoles there is a change - notifyAC(); - // new group by definition has no PDPs, so no need to notify them of changes - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } - // for all remaining POST operations the group must exist before the operation can be done - EcompPDPGroup group = papEngine.getGroup(groupId); - if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - if (apiflag!=null){ - response.addHeader("error", "unknownGroupId"); - response.addHeader("operation", "push"); - response.addHeader("message", message); - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - } else { - response.sendError(HttpServletResponse.SC_NOT_FOUND, message); - } - return; - } - // determine the operation needed based on the parameters in the request - if (request.getParameter("policyId") != null) { - // Args: group= policy= <= copy file - // copy a policy from the request contents into a file in the group's directory on this machine - if(apiflag!=null){ - loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy"); - } else { - loggingContext.setServiceName("AC:PAP.postPolicy"); - } - String policyId = request.getParameter("policyId"); - PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction(); - try { - InputStream is = null; - File temp= null; - if (apiflag != null){ - // get the request content into a String if the request is from API - 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(request.getInputStream()); - scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - LOGGER.info("JSON request from API: " + json); - // convert Object sent as JSON into local object - ObjectMapper mapper = new ObjectMapper(); - Object objectFromJSON = mapper.readValue(json, StdPAPPolicy.class); - StdPAPPolicy policy = (StdPAPPolicy) objectFromJSON; - temp = new File(policy.getLocation()); - is = new FileInputStream(temp); - } else { - is = request.getInputStream(); - } - addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost"); - if (apiflag != null){ - ((StdPDPGroup) group).copyPolicyToFile(policyId,"API", is); - } else { - String name = null; - if (policyId.endsWith(".xml")) { - name = policyId.replace(".xml", ""); - name = name.substring(0, name.lastIndexOf(".")); - } - ((StdPDPGroup) group).copyPolicyToFile(policyId, name, is); - } - if(is!=null && temp!=null){ - is.close(); - temp.delete(); - } - addPolicyToGroupTransaction.commitTransaction(); - } catch (Exception e) { - addPolicyToGroupTransaction.rollbackTransaction(); - String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e; - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - if (apiflag!=null){ - response.addHeader("error", "policyCopyError"); - response.addHeader("message", message); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } else { - response.sendError(500, message); - } - return; - } - // policy file copied ok and the Group was updated on the PDP - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - response.addHeader("operation", "push"); - response.addHeader("policyId", policyId); - response.addHeader("groupId", groupId); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("policy '" + policyId + "' copied to directory for group '" + groupId + "'"); - } - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } else if (request.getParameter("default") != null) { - // Args: group= default=true <= make default - // change the current default group to be the one identified in the request. - loggingContext.setServiceName("AC:PAP.setDefaultGroup"); - // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed. - // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway. - PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction(); - try { - setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost"); - papEngine.SetDefaultGroup(group); - setDefaultGroupTransaction.commitTransaction(); - } catch (Exception e) { - setDefaultGroupTransaction.rollbackTransaction(); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group"); - loggingContext.transactionEnded(); - - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(500, "Unable to set group '" + groupId + "' to default"); - return; - } - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Group '" + groupId + "' set to be default"); - } - // Notify the Admin Consoles that something changed - // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that - //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups - notifyAC(); - // This does not affect any PDPs in the existing groups, so no need to notify them of this change - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } else if (request.getParameter("pdpId") != null) { - doACPostTransaction = policyDBDao.getNewTransaction(); - // Args: group= pdpId= <= move PDP to group - loggingContext.setServiceName("AC:PAP.movePDP"); - String pdpId = request.getParameter("pdpId"); - EcompPDP pdp = papEngine.getPDP(pdpId); - EcompPDPGroup originalGroup = papEngine.getPDPGroup((EcompPDP) pdp); - try{ - doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost"); - }catch(Exception e){ - doACPostTransaction.rollbackTransaction(); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", - " Error while moving pdp in the database: " - +"pdp="+pdp.getId()+",to group="+group.getId()); - throw new PAPException(e.getMessage()); - } - papEngine.movePDP((EcompPDP) pdp, group); - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default"); - } - // update the status of both the original group and the new one - ((StdPDPGroup)originalGroup).resetStatus(); - ((StdPDPGroup)group).resetStatus(); - // Notify the Admin Consoles that something changed - // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that - notifyAC(); - // Need to notify the PDP that it's config may have changed - pdpChanged(pdp); - doACPostTransaction.commitTransaction(); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } - } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(500, e.getMessage()); - return; - } - } - - /** - * Requests from the Admin Console to GET info about the Groups and PDPs - * - * @param request - * @param response - * @param groupId - * @param loggingContext - * @throws ServletException - * @throws IOException - */ - private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException { - try { - String parameterDefault = request.getParameter("default"); - String pdpId = request.getParameter("pdpId"); - String pdpGroup = request.getParameter("getPDPGroup"); - if ("".equals(groupId)) { - // request IS from AC but does not identify a group by name - if (parameterDefault != null) { - // Request is for the Default group (whatever its id) - loggingContext.setServiceName("AC:PAP.getDefaultGroup"); - EcompPDPGroup group = papEngine.getDefaultGroup(); - // convert response object to JSON and include in the response - ObjectMapper mapper = new ObjectMapper(); - mapper.writeValue(response.getOutputStream(), group); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'"); - } - response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("content-type", "application/json"); - response.getOutputStream().close(); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } else if (pdpId != null) { - // Request is related to a PDP - if (pdpGroup == null) { - // Request is for the (unspecified) group containing a given PDP - loggingContext.setServiceName("AC:PAP.getPDP"); - EcompPDP pdp = papEngine.getPDP(pdpId); - // convert response object to JSON and include in the response - ObjectMapper mapper = new ObjectMapper(); - mapper.writeValue(response.getOutputStream(), pdp); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'"); - } - response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("content-type", "application/json"); - response.getOutputStream().close(); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } else { - // Request is for the group containing a given PDP - loggingContext.setServiceName("AC:PAP.getGroupForPDP"); - EcompPDP pdp = papEngine.getPDP(pdpId); - EcompPDPGroup group = papEngine.getPDPGroup((EcompPDP) pdp); - // convert response object to JSON and include in the response - ObjectMapper mapper = new ObjectMapper(); - mapper.writeValue(response.getOutputStream(), group); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'"); - } - response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("content-type", "application/json"); - response.getOutputStream().close(); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } - } else { - // request is for top-level properties about all groups - loggingContext.setServiceName("AC:PAP.getAllGroups"); - Set groups = papEngine.getEcompPDPGroups(); - // convert response object to JSON and include in the response - ObjectMapper mapper = new ObjectMapper(); - mapper.writeValue(response.getOutputStream(), groups); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("GET All groups req"); - } - response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("content-type", "application/json"); - response.getOutputStream().close(); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } - } - // for all other GET operations the group must exist before the operation can be done - EcompPDPGroup group = papEngine.getGroup(groupId); - if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); - loggingContext.transactionEnded(); - - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_NOT_FOUND, message); - return; - } - // Figure out which request this is based on the parameters - String policyId = request.getParameter("policyId"); - if (policyId != null) { - // retrieve a policy - loggingContext.setServiceName("AC:PAP.getPolicy"); - // convert response object to JSON and include in the response - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented"); - } else { - // No other parameters, so return the identified Group - loggingContext.setServiceName("AC:PAP.getGroup"); - // convert response object to JSON and include in the response - ObjectMapper mapper = new ObjectMapper(); - mapper.writeValue(response.getOutputStream(), group); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'"); - } - response.setStatus(HttpServletResponse.SC_OK); - response.setHeader("content-type", "application/json"); - response.getOutputStream().close(); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } - // Currently there are no other GET calls from the AC. - // The AC uses the "GET All Groups" operation to fill its local cache and uses that cache for all other GETs without calling the PAP. - // Other GETs that could be called: - // Specific Group (groupId=) - // A Policy (groupId= policyId=) - // A PDP (groupId= pdpId=) - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED "); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); - } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(500, e.getMessage()); - return; - } - } - - /** - * Requests from the Admin Console to create new items or update existing ones - * - * @param request - * @param response - * @param groupId - * @param loggingContext - * @throws ServletException - * @throws IOException - */ - private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException { - PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction(); - try { - // for PUT operations the group may or may not need to exist before the operation can be done - EcompPDPGroup group = papEngine.getGroup(groupId); - // determine the operation needed based on the parameters in the request - // for remaining operations the group must exist before the operation can be done - if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_NOT_FOUND, message); - return; - } - if (request.getParameter("policy") != null) { - // group= policy= contents=policy file <= Create new policy file in group dir, or replace it if it already exists (do not touch properties) - loggingContext.setServiceName("AC:PAP.putPolicy"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!! ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! "); - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } else if (request.getParameter("pdpId") != null) { - // ARGS: group= pdpId= <= create a new PDP or Update an Existing one - String pdpId = request.getParameter("pdpId"); - if (papEngine.getPDP(pdpId) == null) { - loggingContext.setServiceName("AC:PAP.createPDP"); - } else { - loggingContext.setServiceName("AC:PAP.updatePDP"); - } - // get the request 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(request.getInputStream()); - scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - LOGGER.info("JSON request from AC: " + json); - // convert Object sent as JSON into local object - ObjectMapper mapper = new ObjectMapper(); - Object objectFromJSON = mapper.readValue(json, StdPDP.class); - if (pdpId == null || - objectFromJSON == null || - ! (objectFromJSON instanceof StdPDP) || - ((StdPDP)objectFromJSON).getId() == null || - ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(500, "Bad input, pdpid="+pdpId+" object="+objectFromJSON); - } - StdPDP pdp = (StdPDP) objectFromJSON; - if(pdp != null){ - if (papEngine.getPDP(pdpId) == null) { - // this is a request to create a new PDP object - try{ - acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(), - pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut"); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: " - +"pdp="+ (pdp.getId()) +",to group="+group.getId()); - throw new PAPException(e.getMessage()); - } - papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort()); - } else { - try{ - acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut"); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: " - +"pdp="+ pdp.getId()); - throw new PAPException(e.getMessage()); - } - // this is a request to update the pdp - papEngine.updatePDP(pdp); - } - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("PDP '" + pdpId + "' created/updated"); - } - // adjust the group's state including the new PDP - ((StdPDPGroup)group).resetStatus(); - // tell the Admin Consoles there is a change - notifyAC(); - // this might affect the PDP, so notify it of the change - pdpChanged(pdp); - acPutTransaction.commitTransaction(); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - }else{ - try{ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", " Error while adding pdp to group in the database: " - +"pdp=null" + ",to group="+group.getId()); - throw new PAPException("PDP is null"); - } catch(Exception e){ - throw new PAPException("PDP is null" + e.getMessage() +e); - } - } - } else if (request.getParameter("pipId") != null) { - // group= pipId= contents=pip properties <= add a PIP to pip config, or replace it if it already exists (lenient operation) - loggingContext.setServiceName("AC:PAP.putPIP"); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); - return; - } else { - // Assume that this is an update of an existing PDP Group - // ARGS: group= <= Update an Existing Group - loggingContext.setServiceName("AC:PAP.updateGroup"); - // get the request 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(request.getInputStream()); - scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - LOGGER.info("JSON request from AC: " + json); - // convert Object sent as JSON into local object - ObjectMapper mapper = new ObjectMapper(); - Object objectFromJSON = mapper.readValue(json, StdPDPGroup.class); - if (objectFromJSON == null || ! (objectFromJSON instanceof StdPDPGroup) || - ! ((StdPDPGroup)objectFromJSON).getId().equals(group.getId())) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(500, "Bad input, id="+group.getId() +" object="+objectFromJSON); - } - // The Path on the PAP side is not carried on the RESTful interface with the AC - // (because it is local to the PAP) - // so we need to fill that in before submitting the group for update - if(objectFromJSON != null){ - ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory()); - } - try{ - acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut"); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: " - +"group="+group.getId()); - throw new PAPException(e.getMessage()); - } - - PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); - EcompPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON; - if (pushPolicyHandler.preSafetyCheck(updatedGroup, CONFIG_HOME)) { - LOGGER.debug("Precheck Successful."); - } - - papEngine.updateGroup((StdPDPGroup)objectFromJSON); - - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Group '" + group.getId() + "' updated"); - } - acPutTransaction.commitTransaction(); - // tell the Admin Consoles there is a change - notifyAC(); - // Group changed, which might include changing the policies - groupChanged(group); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } - } catch (PAPException e) { - acPutTransaction.rollbackTransaction(); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(500, e.getMessage()); - return; - } - } - - /** - * Requests from the Admin Console to delete/remove items - * - * @param request - * @param response - * @param groupId - * @param loggingContext - * @throws ServletException - * @throws IOException - */ - private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ECOMPLoggingContext loggingContext) throws ServletException, IOException { - //This code is to allow deletes to propagate to the database since delete is not implemented - String isDeleteNotify = request.getParameter("isDeleteNotify"); - if(isDeleteNotify != null){ - String policyToDelete = request.getParameter("policyToDelete"); - try{ - policyToDelete = URLDecoder.decode(policyToDelete,"UTF-8"); - } catch(UnsupportedEncodingException e){ - PolicyLogger.error("Unsupported URL encoding of policyToDelete (UTF-8"); - response.sendError(500,"policyToDelete encoding not supported"); - return; - } - PolicyDBDaoTransaction deleteTransaction = policyDBDao.getNewTransaction(); - try{ - deleteTransaction.deletePolicy(policyToDelete); - } catch(Exception e){ - deleteTransaction.rollbackTransaction(); - response.sendError(500,"deleteTransaction.deleteTransaction(policyToDelete) " - + "\nfailure with the following exception: " + e); - return; - } - deleteTransaction.commitTransaction(); - response.setStatus(HttpServletResponse.SC_OK); - return; - } - PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.getNewTransaction(); - try { - // for all DELETE operations the group must exist before the operation can be done - loggingContext.setServiceName("AC:PAP.delete"); - EcompPDPGroup group = papEngine.getGroup(groupId); - if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'"); - return; - } - // determine the operation needed based on the parameters in the request - if (request.getParameter("policy") != null) { - // group= policy= [delete=] <= delete policy file from group - loggingContext.setServiceName("AC:PAP.deletePolicy"); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); - return; - } else if (request.getParameter("pdpId") != null) { - // ARGS: group= pdpId= <= delete PDP - String pdpId = request.getParameter("pdpId"); - EcompPDP pdp = papEngine.getPDP(pdpId); - try{ - removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete"); - } catch(Exception e){ - throw new PAPException(); - } - papEngine.removePDP((EcompPDP) pdp); - // adjust the status of the group, which may have changed when we removed this PDP - ((StdPDPGroup)group).resetStatus(); - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - notifyAC(); - // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests) - pdpChanged(pdp); - removePdpOrGroupTransaction.commitTransaction(); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } else if (request.getParameter("pipId") != null) { - // group= pipId= <= delete PIP config for given engine - loggingContext.setServiceName("AC:PAP.deletePIPConfig"); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); - return; - } else { - // ARGS: group= movePDPsToGroupId= <= delete a group and move all its PDPs to the given group - String moveToGroupId = request.getParameter("movePDPsToGroupId"); - EcompPDPGroup moveToGroup = null; - if (moveToGroupId != null) { - moveToGroup = papEngine.getGroup(moveToGroupId); - } - // get list of PDPs in the group being deleted so we can notify them that they got changed - Set movedPDPs = new HashSet<>(); - movedPDPs.addAll(group.getEcompPdps()); - // do the move/remove - try{ - removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete"); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception"); - throw new PAPException(e.getMessage()); - } - papEngine.removeGroup(group, moveToGroup); - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - notifyAC(); - // notify any PDPs in the removed set that their config may have changed - for (EcompPDP pdp : movedPDPs) { - pdpChanged(pdp); - } - removePdpOrGroupTransaction.commitTransaction(); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Transaction Ended Successfully"); - return; - } - } catch (PAPException e) { - removePdpOrGroupTransaction.rollbackTransaction(); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(500, e.getMessage()); - return; - } - } - - /** - * Heartbeat thread - periodically check on PDPs' status - * - * Heartbeat with all known PDPs. - * - * Implementation note: - * - * The PDPs are contacted Sequentially, not in Parallel. - * - * If we did this in parallel using multiple threads we would simultaneously use - * - 1 thread and - * - 1 connection - * for EACH PDP. - * This could become a resource problem since we already use multiple threads and connections for updating the PDPs - * when user changes occur. - * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive. - * - * The Sequential operation does a heartbeat request to each PDP one at a time. - * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout. - * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds) - * it could take a long time to cycle through all of the PDPs. - * That means that this may not notice a PDP being down in a predictable time. - */ - private class Heartbeat implements Runnable { - private PAPPolicyEngine papEngine; - private Set pdps = new HashSet<>(); - private int heartbeatInterval; - private int heartbeatTimeout; - - public volatile boolean isRunning = false; - - public synchronized boolean isRunning() { - return this.isRunning; - } - - public synchronized void terminate() { - this.isRunning = false; - } - - public Heartbeat(PAPPolicyEngine papEngine2) { - papEngine = papEngine2; - this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000")); - this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000")); - } - - @Override - public void run() { - // Set ourselves as running - synchronized(this) { - this.isRunning = true; - } - HashMap idToURLMap = new HashMap<>(); - try { - while (this.isRunning()) { - // Wait the given time - Thread.sleep(heartbeatInterval); - // get the list of PDPs (may have changed since last time) - pdps.clear(); - synchronized(papEngine) { - try { - for (EcompPDPGroup g : papEngine.getEcompPDPGroups()) { - for (EcompPDP p : g.getEcompPdps()) { - pdps.add(p); - } - } - } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine"); - } - } - // Check for shutdown - if (this.isRunning() == false) { - LOGGER.info("isRunning is false, getting out of loop."); - break; - } - // try to get the summary status from each PDP - boolean changeSeen = false; - for (EcompPDP pdp : pdps) { - // Check for shutdown - if (this.isRunning() == false) { - LOGGER.info("isRunning is false, getting out of loop."); - break; - } - // the id of the PDP is its url (though we add a query parameter) - URL pdpURL = idToURLMap.get(pdp.getId()); - if (pdpURL == null) { - // haven't seen this PDP before - String fullURLString = null; - try { - // Check PDP ID - if(CheckPDP.validateID(pdp.getId())){ - fullURLString = pdp.getId() + "?type=hb"; - pdpURL = new URL(fullURLString); - idToURLMap.put(pdp.getId(), pdpURL); - } - } catch (MalformedURLException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL"); - continue; - } - } - // Do a GET with type HeartBeat - String newStatus = ""; - HttpURLConnection connection = null; - try { - // Open up the connection - if(pdpURL != null){ - connection = (HttpURLConnection)pdpURL.openConnection(); - // Setup our method and headers - connection.setRequestMethod("GET"); - connection.setConnectTimeout(heartbeatTimeout); - // Authentication - String encoding = CheckPDP.getEncoding(pdp.getId()); - if(encoding !=null){ - connection.setRequestProperty("Authorization", "Basic " + encoding); - } - // Do the connect - connection.connect(); - if (connection.getResponseCode() == 204) { - newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'"); - } - } else { - // anything else is an unexpected result - newStatus = PDPStatus.Status.UNKNOWN.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId()); - } - } - } catch (UnknownHostException e) { - newStatus = PDPStatus.Status.NO_SUCH_HOST.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST"); - } catch (SocketTimeoutException e) { - newStatus = PDPStatus.Status.CANNOT_CONNECT.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout"); - } catch (ConnectException e) { - newStatus = PDPStatus.Status.CANNOT_CONNECT.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect"); - } catch (Exception e) { - newStatus = PDPStatus.Status.UNKNOWN.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception"); - } finally { - // cleanup the connection - if(connection != null) - connection.disconnect(); - } - if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("previous status='" + pdp.getStatus().getStatus()+"' new Status='" + newStatus + "'"); - } - try { - setPDPSummaryStatus(pdp, newStatus); - } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId()); - } - changeSeen = true; - } - } - // Check for shutdown - if (this.isRunning() == false) { - LOGGER.info("isRunning is false, getting out of loop."); - break; - } - // if any of the PDPs changed state, tell the ACs to update - if (changeSeen) { - notifyAC(); - } - } - } catch (InterruptedException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted. Shutting down"); - this.terminate(); - } - } - } - - /* - * HELPER to change Group status when PDP status is changed - * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock) - */ - private void setPDPSummaryStatus(EcompPDP pdp, PDPStatus.Status newStatus) throws PAPException { - setPDPSummaryStatus(pdp, newStatus.toString()); - } - - private void setPDPSummaryStatus(EcompPDP pdp, String newStatus) throws PAPException { - synchronized(papEngine) { - StdPDPStatus status = new StdPDPStatus(); - status.setStatus(PDPStatus.Status.valueOf(newStatus)); - ((StdPDP)pdp).setStatus(status); - // now adjust the group - StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((EcompPDP) pdp); - // if the PDP was just deleted it may transiently exist but not be in a group - if (group != null) { - group.resetStatus(); - } - } - } - - /* - * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine - * in the PDP group directories - */ - @Override - public void changed() { - // all PDPs in all groups need to be updated/sync'd - Set groups; - try { - groups = papEngine.getEcompPDPGroups(); - } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed"); - throw new RuntimeException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); - } - for (EcompPDPGroup group : groups) { - groupChanged(group); - } - } - - @Override - public void groupChanged(EcompPDPGroup group) { - // all PDPs within one group need to be updated/sync'd - for (EcompPDP pdp : group.getEcompPdps()) { - pdpChanged(pdp); - } - } - - @Override - public void pdpChanged(EcompPDP pdp) { - // kick off a thread to do an event notification for each PDP. - // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc) - // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out. - Thread t = new Thread(new UpdatePDPThread(pdp, storedRequestId)); - if(CheckPDP.validateID(pdp.getId())){ - t.start(); - } - } - - private class UpdatePDPThread implements Runnable { - private EcompPDP pdp; - private String requestId; - - public UpdatePDPThread(EcompPDP pdp, String storedRequestId) { - this.pdp = pdp; - requestId = storedRequestId; - } - - public void run() { - // send the current configuration to one PDP - HttpURLConnection connection = null; - // get a new logging context for the thread - ECOMPLoggingContext loggingContext = new ECOMPLoggingContext(baseLoggingContext); - try { - loggingContext.setServiceName("PAP:PDP.putConfig"); - // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP - if ((requestId == null) || (requestId == "")) { - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one: " + loggingContext.getRequestID()); - } else { - loggingContext.setRequestID(requestId); - PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread): " + loggingContext.getRequestID()); - } - loggingContext.transactionStarted(); - // the Id of the PDP is its URL - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("creating url for id '" + pdp.getId() + "'"); - } - //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other? - //TODO (need to change "cache=", implying getting some input saying which to change) - URL url = new URL(pdp.getId() + "?cache=all"); - // Open up the connection - connection = (HttpURLConnection)url.openConnection(); - // Setup our method and headers - connection.setRequestMethod("PUT"); - // Authentication - String encoding = CheckPDP.getEncoding(pdp.getId()); - if(encoding !=null){ - connection.setRequestProperty("Authorization", "Basic " + encoding); - } - connection.setRequestProperty("Content-Type", "text/x-java-properties"); - connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID()); - storedRequestId = null; - connection.setInstanceFollowRedirects(true); - connection.setDoOutput(true); - try (OutputStream os = connection.getOutputStream()) { - EcompPDPGroup group = papEngine.getPDPGroup((EcompPDP) pdp); - // if the PDP was just deleted, there is no group, but we want to send an update anyway - if (group == null) { - // create blank properties files - Properties policyProperties = new Properties(); - policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, ""); - policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, ""); - policyProperties.store(os, ""); - Properties pipProps = new Properties(); - pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, ""); - pipProps.store(os, ""); - } else { - // send properties from the current group - group.getPolicyProperties().store(os, ""); - Properties policyLocations = new Properties(); - for (PDPPolicy policy : group.getPolicies()) { - policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId()); - } - policyLocations.store(os, ""); - group.getPipConfigProperties().store(os, ""); - } - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId()); - // Since this is a server-side error, it probably does not reflect a problem on the client, - // so do not change the PDP status. - return; - } - // Do the connect - connection.connect(); - if (connection.getResponseCode() == 204) { - LOGGER.info("Success. We are configured correctly."); - loggingContext.transactionEnded(); - auditLogger.info("Success. PDP is configured correctly."); - PolicyLogger.audit("Transaction Success. PDP is configured correctly."); - setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE); - } else if (connection.getResponseCode() == 200) { - LOGGER.info("Success. PDP needs to update its configuration."); - loggingContext.transactionEnded(); - auditLogger.info("Success. PDP needs to update its configuration."); - PolicyLogger.audit("Transaction Success. PDP is configured correctly."); - setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH); - } else { - LOGGER.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); - loggingContext.transactionEnded(); - auditLogger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); - PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); - setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN); - } - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e); - try { - setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN); - } catch (PAPException e1) { - PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN"); - } - } finally { - // cleanup the connection - if(connection != null){ - connection.disconnect(); - } - // tell the AC to update it's status info - notifyAC(); - } - } - } - - /* - * RESTful Interface from PAP to ACs notifying them of changes - */ - private void notifyAC() { - // kick off a thread to do one event notification for all registered ACs - // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data - // as part of processing this message on their end. - Thread t = new Thread(new NotifyACThread()); - t.start(); - } - - private class NotifyACThread implements Runnable { - public void run() { - List disconnectedACs = new ArrayList<>(); - // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList. - // The "for each" loop uses the collection's iterator under the covers, so it should be correct. - for (String acURL : adminConsoleURLStringList) { - HttpURLConnection connection = null; - try { - acURL += "?PAPNotification=true"; - //TODO - Currently we just tell AC that "Something changed" without being specific. Do we want to tell it which group/pdp changed? - //TODO - If so, put correct parameters into the Query string here - acURL += "&objectType=all" + "&action=update"; - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("creating url for id '" + acURL + "'"); - } - //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other? - //TODO (need to change "cache=", implying getting some input saying which to change) - URL url = new URL(acURL ); - // Open up the connection - connection = (HttpURLConnection)url.openConnection(); - // Setup our method and headers - connection.setRequestMethod("PUT"); - connection.setRequestProperty("Content-Type", "text/x-java-properties"); - // 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. - //TODO - is this needed for a PUT? seems better to leave in for now? - connection.setInstanceFollowRedirects(false); - // Do not include any data in the PUT because this is just a - // notification to the AC. - // The AC will use GETs back to the PAP to get what it needs - // to fill in the screens. - // Do the connect - connection.connect(); - if (connection.getResponseCode() == 204) { - LOGGER.info("Success. We updated correctly."); - } else { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); - } - - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'"); - disconnectedACs.add(acURL); - } finally { - // cleanup the connection - if(connection != null) - connection.disconnect(); - } - } - // remove any ACs that are no longer connected - if (disconnectedACs.size() > 0) { - adminConsoleURLStringList.removeAll(disconnectedACs); - } - } - } - - private void testService(ECOMPLoggingContext loggingContext, HttpServletResponse response) throws IOException{ - LOGGER.info("Test request received"); - try { - im.evaluateSanity(); - //If we make it this far, all is well - String message = "GET:/pap/test called and PAP " + papResourceName + " is OK"; - LOGGER.info(message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.setStatus(HttpServletResponse.SC_OK); - return; - }catch (ForwardProgressException fpe){ - //No forward progress is being made - String message = "GET:/pap/test called and PAP " + papResourceName + " is not making forward progress." - + " Exception Message: " + fpe.getMessage(); - LOGGER.info(message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - }catch (AdministrativeStateException ase){ - //Administrative State is locked - String message = "GET:/pap/test called and PAP " + papResourceName + " Administrative State is LOCKED " - + " Exception Message: " + ase.getMessage(); - LOGGER.info(message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - }catch (StandbyStatusException sse){ - //Administrative State is locked - String message = "GET:/pap/test called and PAP " + papResourceName + " Standby Status is NOT PROVIDING SERVICE " - + " Exception Message: " + sse.getMessage(); - LOGGER.info(message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - }catch (Exception e) { - //A subsystem is not making progress, is locked, standby or is not responding - String eMsg = e.getMessage(); - if(eMsg == null){ - eMsg = "No Exception Message"; - } - String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure." - + " Exception Message: " + eMsg; - LOGGER.info(message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - //Get the specific list of subsystems that failed - String ssFailureList = null; - for(String failedSS : papDependencyGroupsFlatArray){ - if(eMsg.contains(failedSS)){ - if(ssFailureList == null){ - ssFailureList = failedSS; - }else{ - ssFailureList = ssFailureList.concat(","+failedSS); - } - } - } - if(ssFailureList == null){ - ssFailureList = "UnknownSubSystem"; - } - response.addHeader("X-ECOMP-SubsystemFailure", ssFailureList); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - return; - } - } - - /* - * Authorizing the PEP Requests. - */ - private boolean authorizeRequest(HttpServletRequest request) { - String clientCredentials = request.getHeader(ENVIRONMENT_HEADER); - // Check if the Client is Authorized. - if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){ - return true; - }else{ - return false; - } - } - - private static void loadWebapps() throws PAPException{ - if(ACTION_HOME == null || CONFIG_HOME == null){ - Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); - //Sanity Check - if (webappsPath == null) { - PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); - throw new PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); - } - Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config"); - Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"Action"); - if (Files.notExists(webappsPathConfig)) { - try { - Files.createDirectories(webappsPathConfig); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Failed to create config directory: " - + webappsPathConfig.toAbsolutePath().toString()); - } - } - if (Files.notExists(webappsPathAction)) { - try { - Files.createDirectories(webappsPathAction); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: " - + webappsPathAction.toAbsolutePath().toString(), e); - } - } - ACTION_HOME = webappsPathAction.toString(); - CONFIG_HOME = webappsPathConfig.toString(); - } - } - - public static String getConfigHome(){ - try { - loadWebapps(); - } catch (PAPException e) { - return null; - } - return CONFIG_HOME; - } - - public static String getActionHome(){ - try { - loadWebapps(); - } catch (PAPException e) { - return null; - } - return ACTION_HOME; - } - - public static EntityManagerFactory getEmf() { - return emf; - } - - public IntegrityAudit getIa() { - return ia; - } - - public static String getPDPFile(){ - return XACMLPapServlet.pdpFile; - } - - public static String getPersistenceUnit(){ - return PERSISTENCE_UNIT; - } - - public static PAPPolicyEngine getPAPEngine(){ - return papEngine; - } - - public static PolicyDBDaoTransaction getDbDaoTransaction(){ - return policyDBDao.getNewTransaction(); - } - public static String getPapDbDriver() { - return papDbDriver; - } - - public static void setPapDbDriver(String papDbDriver) { - XACMLPapServlet.papDbDriver = papDbDriver; - } - - public static String getPapDbUrl() { - return papDbUrl; - } - - public static void setPapDbUrl(String papDbUrl) { - XACMLPapServlet.papDbUrl = papDbUrl; - } - - public static String getPapDbUser() { - return papDbUser; - } - - public static void setPapDbUser(String papDbUser) { - XACMLPapServlet.papDbUser = papDbUser; - } - - public static String getPapDbPassword() { - return papDbPassword; - } - - public static void setPapDbPassword(String papDbPassword) { - XACMLPapServlet.papDbPassword = papDbPassword; - } - - public static String getMsEcompName() { - return msEcompName; - } - - public static void setMsEcompName(String msEcompName) { - XACMLPapServlet.msEcompName = msEcompName; - } - - public static String getMsPolicyName() { - return msPolicyName; - } - - public static void setMsPolicyName(String msPolicyName) { - XACMLPapServlet.msPolicyName = msPolicyName; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/adapters/GridData.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/adapters/GridData.java deleted file mode 100644 index 86f42bcbe..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/adapters/GridData.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.adapters; - -import java.util.ArrayList; - -public class GridData { - private ArrayList attributes; - private ArrayList alAttributes; - private ArrayList transportProtocols; - private ArrayList appProtocols; - - public ArrayList getAttributes() { - return attributes; - } - - public void setAttributes(ArrayList attributes) { - this.attributes = attributes; - } - - public ArrayList getAlAttributes() { - return alAttributes; - } - - public void setAlAttributes(ArrayList alAttributes) { - this.alAttributes = alAttributes; - } - - public ArrayList getAppProtocols() { - return appProtocols; - } - - public void setAppProtocols(ArrayList appProtocols) { - this.appProtocols = appProtocols; - } - - public ArrayList getTransportProtocols() { - return transportProtocols; - } - - public void setTransportProtocols(ArrayList transportProtocols) { - this.transportProtocols = transportProtocols; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/adapters/package-info.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/adapters/package-info.java deleted file mode 100644 index 20b95c734..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/adapters/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.adapters; diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java deleted file mode 100644 index 45ef01f6e..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ActionPolicy.java +++ /dev/null @@ -1,529 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import javax.persistence.EntityManager; -import javax.persistence.Query; - -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.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -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.pap.xacml.rest.XACMLPapServlet; -import org.openecomp.policy.pap.xacml.rest.util.JPAUtils; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.jpa.ActionPolicyDict; -import org.openecomp.policy.rest.jpa.Datatype; -import org.openecomp.policy.rest.jpa.FunctionDefinition; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -public class ActionPolicy extends Policy { - - /** - * ActionPolicy Fields - */ - private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicy.class); - - public static final String JSON_CONFIG = "JSON"; - - public static final String PDP_ACTION = "PDP"; - public static final String PEP_ACTION = "PEP"; - public static final String TYPE_ACTION = "REST"; - - public static final String GET_METHOD = "GET"; - public static final String PUT_METHOD = "PUT"; - public static final String POST_METHOD = "POST"; - - public static final String PERFORMER_ATTRIBUTEID = "performer"; - public static final String TYPE_ATTRIBUTEID = "type"; - public static final String METHOD_ATTRIBUTEID = "method"; - public static final String HEADERS_ATTRIBUTEID = "headers"; - public static final String URL_ATTRIBUTEID = "url"; - public static final String BODY_ATTRIBUTEID = "body"; - - private static boolean isAttribute = false; - - - List dynamicLabelRuleAlgorithms = new LinkedList<>(); - List dynamicFieldFunctionRuleAlgorithms = new LinkedList<>(); - List dynamicFieldOneRuleAlgorithms = new LinkedList<>(); - List dynamicFieldTwoRuleAlgorithms = new LinkedList<>(); - - protected Map dropDownMap = new HashMap<>(); - - - public ActionPolicy() { - super(); - } - - public ActionPolicy(PolicyRestAdapter policyAdapter){ - this.policyAdapter = policyAdapter; - } - - @Override - public Map savePolicies() throws Exception { - - Map successMap = new HashMap<>(); - if(isPolicyExists()){ - successMap.put("EXISTS", "This Policy already exist on the PAP"); - return successMap; - } - - if(!ActionPolicy.isAttribute) { - successMap.put("invalidAttribute", "Action Attrbute was not in the database."); - return successMap; - } - - if(!isPreparedToSave()){ - //Prep and configure the policy for saving - prepareToSave(); - } - - // Until here we prepared the data and here calling the method to create xml. - Path newPolicyPath = null; - newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject() ); - return successMap; - } - - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things - @Override - public boolean prepareToSave() throws Exception{ - - if(isPreparedToSave()){ - //we have already done this - return true; - } - - int version = 0; - String policyID = policyAdapter.getPolicyID(); - version = policyAdapter.getHighestVersion(); - - // Create the Instance for pojo, PolicyType object is used in marshalling. - if (policyAdapter.getPolicyType().equals("Action")) { - PolicyType policyConfig = new PolicyType(); - - policyConfig.setVersion(Integer.toString(version)); - policyConfig.setPolicyId(policyID); - policyConfig.setTarget(new TargetType()); - policyAdapter.setData(policyConfig); - } - - policyName = policyAdapter.getNewFileName(); - - if (policyAdapter.getData() != null) { - // Action body is optional so checking value provided or not - String comboDictValue = policyAdapter.getActionAttribute(); - String actionBody = getActionPolicyDict(comboDictValue).getBody(); - if(!(actionBody==null || "".equals(actionBody))){ - saveActionBody(policyName, actionBody); - } else { - if(!isAttribute){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not find " + comboDictValue + " in the ActionPolicyDict table."); - return false; - } - } - - PolicyType actionPolicy = (PolicyType) policyAdapter.getData(); - actionPolicy.setDescription(policyAdapter.getPolicyDescription()); - actionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); - - AllOfType allOf = new AllOfType(); - - Map dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes(); - - // If there is any dynamic field attributes create the matches here - for (String keyField : dynamicFieldComponentAttributes.keySet()) { - String key = keyField; - String value = dynamicFieldComponentAttributes.get(key); - MatchType dynamicMatch = createDynamicMatch(key, value); - allOf.getMatch().add(dynamicMatch); - } - - AnyOfType anyOf = new AnyOfType(); - anyOf.getAllOf().add(allOf); - - TargetType target = new TargetType(); - target.getAnyOf().add(anyOf); - - // Adding the target to the policy element - actionPolicy.setTarget(target); - - RuleType rule = new RuleType(); - rule.setRuleId(policyAdapter.getRuleID()); - - rule.setEffect(EffectType.PERMIT); - rule.setTarget(new TargetType()); - - dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels(); - dynamicFieldFunctionRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo(); - dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1(); - dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2(); - //dropDownMap = policyAdapter.getDropDownMap(); - dropDownMap = createDropDownMap(); - - // Rule attributes are optional and dynamic so check and add them to condition. - if (dynamicLabelRuleAlgorithms != null && dynamicLabelRuleAlgorithms.size() > 0) { - boolean isCompound = false; - ConditionType condition = new ConditionType(); - int index = dynamicFieldOneRuleAlgorithms.size() - 1; - - for (String labelAttr : dynamicLabelRuleAlgorithms) { - // if the rule algorithm as a label means it is a compound - if (dynamicFieldOneRuleAlgorithms.get(index).toString().equals(labelAttr)) { - ApplyType actionApply = new ApplyType(); - - String selectedFunction = (String) dynamicFieldFunctionRuleAlgorithms.get(index).toString(); - String value1 = (String) dynamicFieldOneRuleAlgorithms.get(index).toString(); - String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString(); - actionApply.setFunctionId(dropDownMap.get(selectedFunction)); - actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1))); - actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2))); - condition.setExpression(new ObjectFactory().createApply(actionApply)); - isCompound = true; - } - } - // if rule algorithm not a compound - if (!isCompound) { - condition.setExpression(new ObjectFactory().createApply(getInnerActionApply(dynamicLabelRuleAlgorithms.get(index).toString()))); - } - rule.setCondition(condition); - } - // set the obligations to rule - rule.setObligationExpressions(getObligationExpressions()); - actionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); - policyAdapter.setPolicyData(actionPolicy); - } else { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); - } - - setPreparedToSave(true); - return true; - } - - // Saving the json Configurations file if exists at server location for action policy. - private void saveActionBody(String policyName, String actionBodyData) { - try { - if(policyName.endsWith(".xml")){ - policyName = policyName.replace(".xml", ""); - } - File file = new File(ACTION_HOME+ File.separator + policyName + ".json"); - FileWriter fw = new FileWriter(file.getAbsoluteFile()); - BufferedWriter bw = new BufferedWriter(fw); - bw.write(actionBodyData); - bw.close(); - if (LOGGER.isInfoEnabled()) { - LOGGER.info("Action Body is succesfully saved at " + file.getAbsolutePath()); - } - } catch (IOException e) { - LOGGER.error("Exception Occured"+e); - } - } - - // Data required for obligation part is setting here. - private ObligationExpressionsType getObligationExpressions() { - ObligationExpressionsType obligations = new ObligationExpressionsType(); - - ObligationExpressionType obligation = new ObligationExpressionType(); - String comboDictValue = policyAdapter.getActionAttribute(); - obligation.setObligationId(comboDictValue); - obligation.setFulfillOn(EffectType.PERMIT); - - // Add Action Assignment: - AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); - assignment1.setAttributeId(PERFORMER_ATTRIBUTEID); - assignment1.setCategory(CATEGORY_RECIPIENT_SUBJECT); - - AttributeValueType actionNameAttributeValue = new AttributeValueType(); - actionNameAttributeValue.setDataType(STRING_DATATYPE); - actionNameAttributeValue.getContent().add(performer.get(policyAdapter.getActionPerformer())); - - assignment1.setExpression(new ObjectFactory().createAttributeValue(actionNameAttributeValue)); - obligation.getAttributeAssignmentExpression().add(assignment1); - - // Add Type Assignment: - AttributeAssignmentExpressionType assignmentType = new AttributeAssignmentExpressionType(); - assignmentType.setAttributeId(TYPE_ATTRIBUTEID); - assignmentType.setCategory(CATEGORY_RESOURCE); - - AttributeValueType typeAttributeValue = new AttributeValueType(); - typeAttributeValue.setDataType(STRING_DATATYPE); - String actionDictType = getActionPolicyDict(comboDictValue).getType(); - typeAttributeValue.getContent().add(actionDictType); - - assignmentType.setExpression(new ObjectFactory().createAttributeValue(typeAttributeValue)); - obligation.getAttributeAssignmentExpression().add(assignmentType); - - // Add Rest_URL Assignment: - AttributeAssignmentExpressionType assignmentURL = new AttributeAssignmentExpressionType(); - assignmentURL.setAttributeId(URL_ATTRIBUTEID); - assignmentURL.setCategory(CATEGORY_RESOURCE); - - AttributeValueType actionURLAttributeValue = new AttributeValueType(); - actionURLAttributeValue.setDataType(URI_DATATYPE); - String actionDictUrl = getActionPolicyDict(comboDictValue).getUrl(); - actionURLAttributeValue.getContent().add(actionDictUrl); - - assignmentURL.setExpression(new ObjectFactory().createAttributeValue(actionURLAttributeValue)); - obligation.getAttributeAssignmentExpression().add(assignmentURL); - - // Add Method Assignment: - AttributeAssignmentExpressionType assignmentMethod = new AttributeAssignmentExpressionType(); - assignmentMethod.setAttributeId(METHOD_ATTRIBUTEID); - assignmentMethod.setCategory(CATEGORY_RESOURCE); - - AttributeValueType methodAttributeValue = new AttributeValueType(); - methodAttributeValue.setDataType(STRING_DATATYPE); - String actionDictMethod = getActionPolicyDict(comboDictValue).getMethod(); - methodAttributeValue.getContent().add(actionDictMethod); - - assignmentMethod.setExpression(new ObjectFactory().createAttributeValue(methodAttributeValue)); - obligation.getAttributeAssignmentExpression().add(assignmentMethod); - - // Add JSON_URL Assignment: - String actionBody = getActionPolicyDict(comboDictValue).getBody(); - if (actionBody != null) { - AttributeAssignmentExpressionType assignmentJsonURL = new AttributeAssignmentExpressionType(); - assignmentJsonURL.setAttributeId(BODY_ATTRIBUTEID); - assignmentJsonURL.setCategory(CATEGORY_RESOURCE); - - AttributeValueType jsonURLAttributeValue = new AttributeValueType(); - jsonURLAttributeValue.setDataType(URI_DATATYPE); - jsonURLAttributeValue.getContent().add(CONFIG_URL + "/Action/" + policyName + ".json"); - - assignmentJsonURL.setExpression(new ObjectFactory().createAttributeValue(jsonURLAttributeValue)); - obligation.getAttributeAssignmentExpression().add(assignmentJsonURL); - } - - if(getActionPolicyDict(comboDictValue).getHeader() != null){ - String headerVal = getActionPolicyDict(comboDictValue).getHeader(); - if(headerVal != null && !headerVal.equals("")){ - // parse it on : to get number of headers - String[] result = headerVal.split(":"); - for (String eachString : result){ - // parse each value on = - String[] textFieldVals = eachString.split("="); - obligation.getAttributeAssignmentExpression().add(addDynamicHeaders(textFieldVals[0], textFieldVals[1])); - } - } - - } - - obligations.getObligationExpression().add(obligation); - return obligations; - } - - - // if compound setting the inner apply here - protected ApplyType getInnerActionApply(String value1Label) { - ApplyType actionApply = new ApplyType(); - int index = 0; - // check the index for the label. - for (String labelAttr : dynamicLabelRuleAlgorithms) { - if (labelAttr.equals(value1Label)) { - String value1 = dynamicFieldOneRuleAlgorithms.get(index).toString(); - // check if the row contains label again - for (String labelValue : dynamicLabelRuleAlgorithms) { - if (labelValue.equals(value1)) { - return getCompoundApply(index); - } - } - - // Getting the values from the form. - String functionKey = dynamicFieldFunctionRuleAlgorithms.get(index).toString(); - String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString(); - actionApply.setFunctionId(dropDownMap.get(functionKey)); - // if two text field are rule attributes. - if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) { - ApplyType innerActionApply1 = new ApplyType(); - ApplyType innerActionApply2 = new ApplyType(); - AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType(); - AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType(); - // If selected function is Integer function set integer functionID - if (functionKey.toLowerCase().contains("integer")) { - innerActionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY); - innerActionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY); - attributeDesignator1.setDataType(INTEGER_DATATYPE); - attributeDesignator2.setDataType(INTEGER_DATATYPE); - } else { - // If selected function is not a Integer function - // set String functionID - innerActionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY); - innerActionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY); - attributeDesignator1.setDataType(STRING_DATATYPE); - attributeDesignator2.setDataType(STRING_DATATYPE); - } - attributeDesignator1.setCategory(CATEGORY_RESOURCE); - attributeDesignator2.setCategory(CATEGORY_RESOURCE); - - // Here set actual field values - attributeDesignator1.setAttributeId(value1.contains("resource:") ? value1.substring(9): value1.substring(8)); - attributeDesignator2.setAttributeId(value1.contains("resource:") ? value1.substring(9): value1.substring(8)); - - innerActionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator1)); - innerActionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator2)); - - actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply1)); - actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply2)); - - } else {// if either of one text field is rule attribute. - ApplyType innerActionApply = new ApplyType(); - AttributeDesignatorType attributeDesignator = new AttributeDesignatorType(); - AttributeValueType actionConditionAttributeValue = new AttributeValueType(); - - if (functionKey.toLowerCase().contains("integer")) { - innerActionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY); - actionConditionAttributeValue.setDataType(INTEGER_DATATYPE); - attributeDesignator.setDataType(INTEGER_DATATYPE); - } else { - innerActionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY); - actionConditionAttributeValue.setDataType(STRING_DATATYPE); - attributeDesignator.setDataType(STRING_DATATYPE); - } - - String attributeId = null; - String attributeValue = null; - - // Find which textField has rule attribute and set it as - attributeId = value1; - attributeValue = value2; - - if (attributeId != null) { - attributeDesignator.setCategory(CATEGORY_RESOURCE); - attributeDesignator.setAttributeId(attributeId); - } - actionConditionAttributeValue.getContent().add(attributeValue); - innerActionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator)); - // Decide the order of element based the values. - if (attributeId.equals(value1)) { - actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply)); - actionApply.getExpression().add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue)); - } else { - actionApply.getExpression().add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue)); - actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply)); - } - } - } - index++; - } - return actionApply; - } - - // if the rule algorithm is multiple compound one setting the apply - protected ApplyType getCompoundApply(int index) { - ApplyType actionApply = new ApplyType(); - String selectedFunction = dynamicFieldFunctionRuleAlgorithms.get(index).toString(); - String value1 = dynamicFieldOneRuleAlgorithms.get(index).toString(); - String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString(); - actionApply.setFunctionId(dropDownMap.get(selectedFunction)); - actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1))); - actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2))); - return actionApply; - } - - // Adding the dynamic headers if any - private AttributeAssignmentExpressionType addDynamicHeaders(String header, String value) { - AttributeAssignmentExpressionType assignmentHeaders = new AttributeAssignmentExpressionType(); - assignmentHeaders.setAttributeId("headers:" + header); - assignmentHeaders.setCategory(CATEGORY_RESOURCE); - - AttributeValueType headersAttributeValue = new AttributeValueType(); - headersAttributeValue.setDataType(STRING_DATATYPE); - headersAttributeValue.getContent().add(value); - - assignmentHeaders.setExpression(new ObjectFactory().createAttributeValue(headersAttributeValue)); - return assignmentHeaders; - } - - private Map createDropDownMap(){ - JPAUtils jpaUtils = null; - Map dropDownMap = new HashMap<>(); - try { - jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf()); - } catch (Exception e) { - LOGGER.error("Exception Occured"+e); - } - if(jpaUtils != null){ - Map> functionMap = jpaUtils.getFunctionDatatypeMap(); - - for (Datatype id : functionMap.keySet()) { - List functionDefinitions = (List) functionMap - .get(id); - for (FunctionDefinition functionDef : functionDefinitions) { - dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid()); - } - } - } - return dropDownMap; - } - - private ActionPolicyDict getActionPolicyDict(String attributeName){ - ActionPolicyDict retObj = new ActionPolicyDict(); - EntityManager em = XACMLPapServlet.getEmf().createEntityManager(); - Query getActionPolicyDicts = em.createNamedQuery("ActionPolicyDict.findAll"); - List actionPolicyDicts = getActionPolicyDicts.getResultList(); - - for (Object id : actionPolicyDicts) { - ActionPolicyDict actionPolicy = (ActionPolicyDict) id; - if(attributeName.equals(actionPolicy.getAttributeName())){ - isAttribute = true; - retObj = actionPolicy; - break; - } - } - em.close(); - return retObj; - } - - @Override - public Object getCorrectPolicyDataObject() { - return policyAdapter.getPolicyData(); - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/AutoPushPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/AutoPushPolicy.java deleted file mode 100644 index 31871587b..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/AutoPushPolicy.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - -import java.io.File; -import java.io.FileInputStream; -import java.nio.file.Paths; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Properties; -import java.util.Set; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.xacml.std.pap.StdPDPGroup; -import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; - -import com.att.research.xacml.api.pap.PDPPolicy; -/** - * Auto Push Policy based on the property file properties. - * - * @version 0.1 - */ -public class AutoPushPolicy { - - private static final Logger LOGGER = FlexLogger.getLogger(AutoPushPolicy.class); - - private String filePath = null; - private Properties properties; - private Long newModified; - private Long oldModified; - private File propFile; - - - /** - * Constructor Pass in the property file path. - */ - public AutoPushPolicy(String file){ - filePath = file; - properties = new Properties(); - propFile = Paths.get(filePath).toFile(); - readFile(); - } - - private void readFile(){ - try { - properties.load(new FileInputStream(propFile)); - oldModified = propFile.lastModified(); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "AutoPushPolicy", "Error while loading in the auto push properties file."); - } - } - - private StdPDPGroup addToGroup(String policyId, String policyName, String policyToCreateUpdate, StdPDPGroup pdpGroup) throws Exception{ - // Add to group. Send Notification. - StdPDPPolicy policy = new StdPDPPolicy(policyId, true, policyName, null); - //Get the current policies from the Group and Add the new one - Set currentPoliciesInGroup = pdpGroup.getPolicies(); - Set policies = new HashSet<>(); - policies.add(policy); - pdpGroup.copyPolicyToFile(policyId, new FileInputStream(Paths.get(policyToCreateUpdate).toFile())); - //If the selected policy is in the group we must remove it because the name is default - Iterator policyIterator = policies.iterator(); - while (policyIterator.hasNext()) { - PDPPolicy selPolicy = policyIterator.next(); - for (PDPPolicy existingPolicy : currentPoliciesInGroup) { - if (existingPolicy.getId().equals(selPolicy.getId())) { - pdpGroup.removePolicyFromGroup(existingPolicy); - LOGGER.debug("Removing policy: " + existingPolicy); - break; - } - } - } - if(currentPoliciesInGroup!=null){ - policies.addAll(currentPoliciesInGroup); - } - pdpGroup.setPolicies(policies); - return pdpGroup; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ClosedLoopPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ClosedLoopPolicy.java deleted file mode 100644 index 1281bd083..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ClosedLoopPolicy.java +++ /dev/null @@ -1,412 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.io.FilenameUtils; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; - -import com.att.research.xacml.std.IdentifierImpl; - -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.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -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; - -public class ClosedLoopPolicy extends Policy { - - private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopPolicy.class); - - public ClosedLoopPolicy() { - super(); - } - - public ClosedLoopPolicy(PolicyRestAdapter policyAdapter){ - this.policyAdapter = policyAdapter; - } - - //save configuration of the policy based on the policyname - private void saveConfigurations(String policyName, String jsonBody) { - try { - String body = jsonBody; - try { - try{ - //Remove the trapMaxAge in Verification Signature - body = body.replace(",\"trapMaxAge\":null", ""); - }catch(Exception e){ - LOGGER.debug("No Trap Max Age in JSON body"); - } - this.policyAdapter.setJsonBody(body); - } catch (Exception e) { - LOGGER.error("Exception Occured"+e); - } - - if(policyName.endsWith(".xml")){ - policyName = policyName.replace(".xml", ""); - } - PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator+ policyName +".json"); - out.println(body); - out.close(); - - } catch (Exception e) { - LOGGER.error("Exception Occured while writing Configuration Data"+e); - } - } - - //Utility to read json data from the existing file to a string - static String readFile(String path, Charset encoding) throws IOException { - - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded, encoding); - - } - - //create the configuration file based on the policy name on adding the extension as .json - private String getConfigFile(String filename) { - filename = FilenameUtils.removeExtension(filename); - if (filename.endsWith(".xml")) { - filename = filename.substring(0, filename.length() - 4); - } - filename = filename + ".json"; - return filename; - } - - @Override - public Map savePolicies() throws Exception { - - Map successMap = new HashMap<>(); - if(isPolicyExists()){ - successMap.put("EXISTS", "This Policy already exist on the PAP"); - return successMap; - } - - if(!isPreparedToSave()){ - prepareToSave(); - } - - // Until here we prepared the data and here calling the method to create xml. - Path newPolicyPath = null; - newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); - return successMap; - } - - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things - @Override - public boolean prepareToSave() throws Exception{ - - if(isPreparedToSave()){ - //we have already done this - return true; - } - - int version = 0; - String policyID = policyAdapter.getPolicyID(); - version = policyAdapter.getHighestVersion(); - - // Create the Instance for pojo, PolicyType object is used in marshalling. - if (policyAdapter.getPolicyType().equals("Config")) { - PolicyType policyConfig = new PolicyType(); - - policyConfig.setVersion(Integer.toString(version)); - policyConfig.setPolicyId(policyID); - policyConfig.setTarget(new TargetType()); - policyAdapter.setData(policyConfig); - } - policyName = policyAdapter.getNewFileName(); - if (policyAdapter.getData() != null) { - // Save the Configurations file with the policy name with extention based on selection. - String jsonBody = policyAdapter.getJsonBody(); - saveConfigurations(policyName, jsonBody); - - // Make sure the filename ends with an extension - if (policyName.endsWith(".xml") == false) { - policyName = policyName + ".xml"; - } - - PolicyType faultPolicy = (PolicyType) policyAdapter.getData(); - - faultPolicy.setDescription(policyAdapter.getPolicyDescription()); - - faultPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); - - AllOfType allOfOne = new AllOfType(); - String fileName = policyAdapter.getNewFileName(); - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); - } - allOfOne.getMatch().add(createMatch("PolicyName", name)); - AllOfType allOf = new AllOfType(); - // Adding the matches to AllOfType element - // Match for Ecomp - allOf.getMatch().add(createMatch("ECOMPName", policyAdapter.getEcompName())); - // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); - // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); - // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); - // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); - - AnyOfType anyOf = new AnyOfType(); - anyOf.getAllOf().add(allOfOne); - anyOf.getAllOf().add(allOf); - - TargetType target = new TargetType(); - ((TargetType) target).getAnyOf().add(anyOf); - // Adding the target to the policy element - faultPolicy.setTarget((TargetType) target); - - RuleType rule = new RuleType(); - rule.setRuleId(policyAdapter.getRuleID()); - rule.setEffect(EffectType.PERMIT); - - // Create Target in Rule - AllOfType allOfInRule = new AllOfType(); - - // Creating match for ACCESS in rule target - MatchType accessMatch = new MatchType(); - AttributeValueType accessAttributeValue = new AttributeValueType(); - accessAttributeValue.setDataType(STRING_DATATYPE); - accessAttributeValue.getContent().add("ACCESS"); - accessMatch.setAttributeValue(accessAttributeValue); - AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); - URI accessURI = null; - try { - accessURI = new URI(ACTION_ID); - } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy", "Exception creating ACCESS URI"); - } - accessAttributeDesignator.setCategory(CATEGORY_ACTION); - accessAttributeDesignator.setDataType(STRING_DATATYPE); - accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); - accessMatch.setAttributeDesignator(accessAttributeDesignator); - accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - // Creating Config Match in rule Target - MatchType closedMatch = new MatchType(); - AttributeValueType closedAttributeValue = new AttributeValueType(); - closedAttributeValue.setDataType(STRING_DATATYPE); - closedAttributeValue.getContent().add("Config"); - closedMatch.setAttributeValue(closedAttributeValue); - AttributeDesignatorType closedAttributeDesignator = new AttributeDesignatorType(); - URI closedURI = null; - try { - closedURI = new URI(RESOURCE_ID); - } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy", "Exception creating closed URI"); - } - closedAttributeDesignator.setCategory(CATEGORY_RESOURCE); - closedAttributeDesignator.setDataType(STRING_DATATYPE); - closedAttributeDesignator.setAttributeId(new IdentifierImpl(closedURI).stringValue()); - closedMatch.setAttributeDesignator(closedAttributeDesignator); - closedMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - allOfInRule.getMatch().add(accessMatch); - allOfInRule.getMatch().add(closedMatch); - - AnyOfType anyOfInRule = new AnyOfType(); - anyOfInRule.getAllOf().add(allOfInRule); - - TargetType targetInRule = new TargetType(); - targetInRule.getAnyOf().add(anyOfInRule); - - rule.setTarget(targetInRule); - rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); - - faultPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); - policyAdapter.setPolicyData(faultPolicy); - - } else { - PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); - } - - setPreparedToSave(true); - return true; - } - - // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { - AdviceExpressionsType advices = new AdviceExpressionsType(); - AdviceExpressionType advice = new AdviceExpressionType(); - advice.setAdviceId("faultID"); - advice.setAppliesTo(EffectType.PERMIT); - // For Configuration - AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); - assignment1.setAttributeId("type"); - assignment1.setCategory(CATEGORY_RESOURCE); - assignment1.setIssuer(""); - - AttributeValueType configNameAttributeValue = new AttributeValueType(); - configNameAttributeValue.setDataType(STRING_DATATYPE); - configNameAttributeValue.getContent().add("Configuration"); - assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); - - advice.getAttributeAssignmentExpression().add(assignment1); - // For Config file Url if configurations are provided. - AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); - assignment2.setAttributeId("URLID"); - assignment2.setCategory(CATEGORY_RESOURCE); - assignment2.setIssuer(""); - - AttributeValueType AttributeValue = new AttributeValueType(); - AttributeValue.setDataType(URI_DATATYPE); - String content = CONFIG_URL +"/Config/" + getConfigFile(policyName); - System.out.println("URL value :" + content); - AttributeValue.getContent().add(content); - assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); - - advice.getAttributeAssignmentExpression().add(assignment2); - AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); - assignment3.setAttributeId("PolicyName"); - assignment3.setCategory(CATEGORY_RESOURCE); - assignment3.setIssuer(""); - - AttributeValueType attributeValue3 = new AttributeValueType(); - attributeValue3.setDataType(STRING_DATATYPE); - fileName = FilenameUtils.removeExtension(fileName); - fileName = fileName + ".xml"; - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); - } - attributeValue3.getContent().add(name); - assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); - advice.getAttributeAssignmentExpression().add(assignment3); - - AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); - assignment4.setAttributeId("VersionNumber"); - assignment4.setCategory(CATEGORY_RESOURCE); - assignment4.setIssuer(""); - - AttributeValueType configNameAttributeValue4 = new AttributeValueType(); - configNameAttributeValue4.setDataType(STRING_DATATYPE); - configNameAttributeValue4.getContent().add(Integer.toString(version)); - assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); - - advice.getAttributeAssignmentExpression().add(assignment4); - - AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); - assignment5.setAttributeId("matching:" + ECOMPID); - assignment5.setCategory(CATEGORY_RESOURCE); - assignment5.setIssuer(""); - - AttributeValueType configNameAttributeValue5 = new AttributeValueType(); - configNameAttributeValue5.setDataType(STRING_DATATYPE); - configNameAttributeValue5.getContent().add(policyAdapter.getEcompName()); - assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); - - advice.getAttributeAssignmentExpression().add(assignment5); - - //Risk Attributes - AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); - assignment6.setAttributeId("RiskType"); - assignment6.setCategory(CATEGORY_RESOURCE); - assignment6.setIssuer(""); - - AttributeValueType configNameAttributeValue6 = new AttributeValueType(); - configNameAttributeValue6.setDataType(STRING_DATATYPE); - configNameAttributeValue6.getContent().add(policyAdapter.getRiskType()); - assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); - - advice.getAttributeAssignmentExpression().add(assignment6); - - AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); - assignment7.setAttributeId("RiskLevel"); - assignment7.setCategory(CATEGORY_RESOURCE); - assignment7.setIssuer(""); - - AttributeValueType configNameAttributeValue7 = new AttributeValueType(); - configNameAttributeValue7.setDataType(STRING_DATATYPE); - configNameAttributeValue7.getContent().add(policyAdapter.getRiskLevel()); - assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); - - advice.getAttributeAssignmentExpression().add(assignment7); - - AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); - assignment8.setAttributeId("guard"); - assignment8.setCategory(CATEGORY_RESOURCE); - assignment8.setIssuer(""); - - AttributeValueType configNameAttributeValue8 = new AttributeValueType(); - configNameAttributeValue8.setDataType(STRING_DATATYPE); - configNameAttributeValue8.getContent().add(policyAdapter.getGuard()); - assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8)); - - advice.getAttributeAssignmentExpression().add(assignment8); - - AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); - assignment9.setAttributeId("TTLDate"); - assignment9.setCategory(CATEGORY_RESOURCE); - assignment9.setIssuer(""); - - AttributeValueType configNameAttributeValue9 = new AttributeValueType(); - configNameAttributeValue9.setDataType(STRING_DATATYPE); - configNameAttributeValue9.getContent().add(policyAdapter.getTtlDate()); - assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); - - advice.getAttributeAssignmentExpression().add(assignment9); - - - - advices.getAdviceExpression().add(advice); - return advices; - } - - @Override - public Object getCorrectPolicyDataObject() { - return policyAdapter.getPolicyData(); - } - - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ConfigPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ConfigPolicy.java deleted file mode 100644 index 0cf9c6546..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/ConfigPolicy.java +++ /dev/null @@ -1,564 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.StringReader; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.Map; -import java.util.Scanner; - -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - -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.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -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.apache.commons.io.FilenameUtils; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -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.xml.sax.ErrorHandler; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; -import org.xml.sax.XMLReader; - -import com.att.research.xacml.std.IdentifierImpl; - -public class ConfigPolicy extends Policy { - - /** - * Config Fields - */ - private static final Logger LOGGER = FlexLogger.getLogger(ConfigPolicy.class); - - public static final String JSON_CONFIG = "JSON"; - public static final String XML_CONFIG = "XML"; - public static final String PROPERTIES_CONFIG = "PROPERTIES"; - public static final String OTHER_CONFIG = "OTHER"; - - private String configBodyData; - - public ConfigPolicy() { - super(); - } - - public ConfigPolicy(PolicyRestAdapter policyAdapter){ - this.policyAdapter = policyAdapter; - } - - // Saving the Configurations file at server location for config policy. - protected void saveConfigurations(String policyName) { - try { - String fileName = getConfigFile(policyName); - FileWriter fw = new FileWriter(CONFIG_HOME + File.separator + fileName); - BufferedWriter bw = new BufferedWriter(fw); - bw.write(configBodyData); - bw.close(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Configuration is succesfully saved"); - } - } catch (IOException e) { - LOGGER.error("Exception Occured while writing Configuration Data"+e); - } - } - - - // Here we are adding the extension for the configurations file based on the - // config type selection for saving. - private String getConfigFile(String filename) { - filename = FilenameUtils.removeExtension(filename); - if (filename.endsWith(".xml")) { - filename = filename.substring(0, filename.length() - 4); - } - String id = policyAdapter.getConfigType(); - - if (id != null) { - if (id.equalsIgnoreCase(JSON_CONFIG)) { - filename = filename + ".json"; - } - if (id.equalsIgnoreCase(XML_CONFIG)) { - filename = filename + ".xml"; - } - if (id.equalsIgnoreCase(PROPERTIES_CONFIG)) { - filename = filename + ".properties"; - } - if (id.equalsIgnoreCase(OTHER_CONFIG)) { - filename = filename + ".txt"; - } - } - return filename; - } - - - // Validations for Config form - /* - * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object... - * BODY VALIDATION WILL BE DONE BY THE PAP-REST after receiving and deserializing the JSON object - */ - public boolean validateConfigForm() { - - isValidForm = true; - - /* - * Validate Text Area Body - */ - configBodyData = policyAdapter.getConfigBodyData(); - String id = policyAdapter.getConfigType(); - if (id != null) { - if (id.equals(JSON_CONFIG)) { - if (!isJSONValid(configBodyData)) { - isValidForm = false; - } - } else if (id.equals(XML_CONFIG)) { - if (!isXMLValid(configBodyData)) { - isValidForm = false; - } - } else if (id.equals(PROPERTIES_CONFIG)) { - if (!isPropValid(configBodyData)||configBodyData.equals("")) { - isValidForm = false; - } - } else if (id.equals(OTHER_CONFIG)) { - if (configBodyData.equals("")) { - isValidForm = false; - } - } - } - return isValidForm; - - } - - // 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 (ParserConfigurationException e) { - return false; - } catch (SAXException e) { - return false; - } catch (IOException 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.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; - - } - - public class XMLErrorHandler implements ErrorHandler { - - public void warning(SAXParseException e) throws SAXException { - System.out.println(e.getMessage()); - } - - public void error(SAXParseException e) throws SAXException { - System.out.println(e.getMessage()); - } - - public void fatalError(SAXParseException e) throws SAXException { - System.out.println(e.getMessage()); - } - - } - - @Override - public Map savePolicies() throws Exception { - - Map successMap = new HashMap<>(); - if(isPolicyExists()){ - successMap.put("EXISTS", "This Policy already exist on the PAP"); - return successMap; - } - - if(!isPreparedToSave()){ - //Prep and configure the policy for saving - prepareToSave(); - } - - // Until here we prepared the data and here calling the method to create xml. - Path newPolicyPath = null; - newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); - return successMap; - } - - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things - @Override - public boolean prepareToSave() throws Exception{ - - if(isPreparedToSave()){ - return true; - } - - int version = 0; - String policyID = policyAdapter.getPolicyID(); - version = policyAdapter.getHighestVersion(); - - // Create the Instance for pojo, PolicyType object is used in marshalling. - if (policyAdapter.getPolicyType().equals("Config")) { - PolicyType policyConfig = new PolicyType(); - - policyConfig.setVersion(Integer.toString(version)); - policyConfig.setPolicyId(policyID); - policyConfig.setTarget(new TargetType()); - policyAdapter.setData(policyConfig); - } - - policyName = policyAdapter.getNewFileName(); - configBodyData = policyAdapter.getConfigBodyData(); - saveConfigurations(policyName); - - if (policyAdapter.getData() != null) { - PolicyType configPolicy = (PolicyType) policyAdapter.getData(); - - configPolicy.setDescription(policyAdapter.getPolicyDescription()); - - configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); - AllOfType allOfOne = new AllOfType(); - - String fileName = policyAdapter.getNewFileName(); - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); - } - allOfOne.getMatch().add(createMatch("PolicyName", name)); - AllOfType allOf = new AllOfType(); - - // Adding the matches to AllOfType element Match for Ecomp - allOf.getMatch().add(createMatch("ECOMPName", policyAdapter.getEcompName())); - // Match for riskType - allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); - // Match for riskLevel - allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); - // Match for riskguard - allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); - // Match for ttlDate - allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); - // Match for ConfigName - allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName())); - - Map dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes(); - - // If there is any dynamic field create the matches here - for (String keyField : dynamicFieldConfigAttributes.keySet()) { - String key = keyField; - String value = dynamicFieldConfigAttributes.get(key); - MatchType dynamicMatch = createDynamicMatch(key, value); - allOf.getMatch().add(dynamicMatch); - } - - AnyOfType anyOf = new AnyOfType(); - anyOf.getAllOf().add(allOfOne); - anyOf.getAllOf().add(allOf); - - TargetType target = new TargetType(); - ((TargetType) target).getAnyOf().add(anyOf); - - // Adding the target to the policy element - configPolicy.setTarget((TargetType) target); - - RuleType rule = new RuleType(); - rule.setRuleId(policyAdapter.getRuleID()); - rule.setEffect(EffectType.PERMIT); - - // Create Target in Rule - AllOfType allOfInRule = new AllOfType(); - - // Creating match for ACCESS in rule target - MatchType accessMatch = new MatchType(); - AttributeValueType accessAttributeValue = new AttributeValueType(); - accessAttributeValue.setDataType(STRING_DATATYPE); - accessAttributeValue.getContent().add("ACCESS"); - accessMatch.setAttributeValue(accessAttributeValue); - AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); - URI accessURI = null; - try{ - accessURI = new URI(ACTION_ID); - }catch(URISyntaxException e){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating ACCESS URI"); - } - accessAttributeDesignator.setCategory(CATEGORY_ACTION); - accessAttributeDesignator.setDataType(STRING_DATATYPE); - accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); - accessMatch.setAttributeDesignator(accessAttributeDesignator); - accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - // Creating Config Match in rule Target - MatchType configMatch = new MatchType(); - AttributeValueType configAttributeValue = new AttributeValueType(); - configAttributeValue.setDataType(STRING_DATATYPE); - configAttributeValue.getContent().add("Config"); - configMatch.setAttributeValue(configAttributeValue); - AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType(); - URI configURI = null; - try{ - configURI = new URI(RESOURCE_ID); - }catch(URISyntaxException e){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating Config URI"); - } - configAttributeDesignator.setCategory(CATEGORY_RESOURCE); - configAttributeDesignator.setDataType(STRING_DATATYPE); - configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue()); - configMatch.setAttributeDesignator(configAttributeDesignator); - configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - allOfInRule.getMatch().add(accessMatch); - allOfInRule.getMatch().add(configMatch); - - AnyOfType anyOfInRule = new AnyOfType(); - anyOfInRule.getAllOf().add(allOfInRule); - - TargetType targetInRule = new TargetType(); - targetInRule.getAnyOf().add(anyOfInRule); - - rule.setTarget(targetInRule); - rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); - - configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); - policyAdapter.setPolicyData(configPolicy); - - } else { - PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); - } - setPreparedToSave(true); - return true; - } - - // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { - AdviceExpressionsType advices = new AdviceExpressionsType(); - AdviceExpressionType advice = new AdviceExpressionType(); - advice.setAdviceId("configID"); - advice.setAppliesTo(EffectType.PERMIT); - - // For Configuration - AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); - assignment1.setAttributeId("type"); - assignment1.setCategory(CATEGORY_RESOURCE); - assignment1.setIssuer(""); - - AttributeValueType configNameAttributeValue = new AttributeValueType(); - configNameAttributeValue.setDataType(STRING_DATATYPE); - configNameAttributeValue.getContent().add("Configuration"); - assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); - - advice.getAttributeAssignmentExpression().add(assignment1); - - // For Config file Url if configurations are provided. - if (policyAdapter.getConfigType() != null) { - AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); - assignment2.setAttributeId("URLID"); - assignment2.setCategory(CATEGORY_RESOURCE); - assignment2.setIssuer(""); - - AttributeValueType AttributeValue = new AttributeValueType(); - AttributeValue.setDataType(URI_DATATYPE); - String content = "$URL" + "/Config/" + getConfigFile(policyName); - AttributeValue.getContent().add(content); - assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); - - advice.getAttributeAssignmentExpression().add(assignment2); - AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); - assignment3.setAttributeId("PolicyName"); - assignment3.setCategory(CATEGORY_RESOURCE); - assignment3.setIssuer(""); - - AttributeValueType attributeValue3 = new AttributeValueType(); - attributeValue3.setDataType(STRING_DATATYPE); - - fileName = FilenameUtils.removeExtension(fileName); - fileName = fileName + ".xml"; - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); - } - attributeValue3.getContent().add(name); - assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); - advice.getAttributeAssignmentExpression().add(assignment3); - - AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); - assignment4.setAttributeId("VersionNumber"); - assignment4.setCategory(CATEGORY_RESOURCE); - assignment4.setIssuer(""); - - AttributeValueType configNameAttributeValue4 = new AttributeValueType(); - configNameAttributeValue4.setDataType(STRING_DATATYPE); - configNameAttributeValue4.getContent().add(Integer.toString(version)); - assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); - - advice.getAttributeAssignmentExpression().add(assignment4); - - AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); - assignment5.setAttributeId("matching:" + ECOMPID); - assignment5.setCategory(CATEGORY_RESOURCE); - assignment5.setIssuer(""); - - AttributeValueType configNameAttributeValue5 = new AttributeValueType(); - configNameAttributeValue5.setDataType(STRING_DATATYPE); - configNameAttributeValue5.getContent().add(policyAdapter.getEcompName()); - assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); - - advice.getAttributeAssignmentExpression().add(assignment5); - - AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); - assignment6.setAttributeId("matching:" + CONFIGID); - assignment6.setCategory(CATEGORY_RESOURCE); - assignment6.setIssuer(""); - - AttributeValueType configNameAttributeValue6 = new AttributeValueType(); - configNameAttributeValue6.setDataType(STRING_DATATYPE); - configNameAttributeValue6.getContent().add(policyAdapter.getConfigName()); - assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); - - advice.getAttributeAssignmentExpression().add(assignment6); - - Map dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes(); - for (String keyField : dynamicFieldConfigAttributes.keySet()) { - String key = keyField; - String value = dynamicFieldConfigAttributes.get(key); - AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); - assignment7.setAttributeId("matching:" + key); - assignment7.setCategory(CATEGORY_RESOURCE); - assignment7.setIssuer(""); - - AttributeValueType configNameAttributeValue7 = new AttributeValueType(); - configNameAttributeValue7.setDataType(STRING_DATATYPE); - configNameAttributeValue7.getContent().add(value); - assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); - - advice.getAttributeAssignmentExpression().add(assignment7); - } - } - - //Risk Attributes - AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); - assignment8.setAttributeId("RiskType"); - assignment8.setCategory(CATEGORY_RESOURCE); - assignment8.setIssuer(""); - - AttributeValueType configNameAttributeValue8 = new AttributeValueType(); - configNameAttributeValue8.setDataType(STRING_DATATYPE); - configNameAttributeValue8.getContent().add(policyAdapter.getRiskType()); - assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8)); - - advice.getAttributeAssignmentExpression().add(assignment8); - - AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); - assignment9.setAttributeId("RiskLevel"); - assignment9.setCategory(CATEGORY_RESOURCE); - assignment9.setIssuer(""); - - AttributeValueType configNameAttributeValue9 = new AttributeValueType(); - configNameAttributeValue9.setDataType(STRING_DATATYPE); - configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel()); - assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); - - advice.getAttributeAssignmentExpression().add(assignment9); - - AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); - assignment10.setAttributeId("guard"); - assignment10.setCategory(CATEGORY_RESOURCE); - assignment10.setIssuer(""); - - AttributeValueType configNameAttributeValue10 = new AttributeValueType(); - configNameAttributeValue10.setDataType(STRING_DATATYPE); - configNameAttributeValue10.getContent().add(policyAdapter.getGuard()); - assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10)); - - advice.getAttributeAssignmentExpression().add(assignment10); - - AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType(); - assignment11.setAttributeId("TTLDate"); - assignment11.setCategory(CATEGORY_RESOURCE); - assignment11.setIssuer(""); - - AttributeValueType configNameAttributeValue11 = new AttributeValueType(); - configNameAttributeValue11.setDataType(STRING_DATATYPE); - configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate()); - assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11)); - - advice.getAttributeAssignmentExpression().add(assignment11); - - advices.getAdviceExpression().add(advice); - return advices; - } - - @Override - public Object getCorrectPolicyDataObject() { - return policyAdapter.getPolicyData(); - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java deleted file mode 100644 index 078ba1040..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java +++ /dev/null @@ -1,73 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - -import java.util.HashMap; -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.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.BRMSParamTemplate; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.openecomp.policy.utils.PolicyUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class CreateBRMSRuleTemplate { - private static final Logger LOGGER = FlexLogger.getLogger(CreateBRMSRuleTemplate.class); - private static CommonClassDao commonClassDao; - - @Autowired - public CreateBRMSRuleTemplate(CommonClassDao commonClassDao){ - CreateBRMSRuleTemplate.commonClassDao = commonClassDao; - } - - public CreateBRMSRuleTemplate() {} - - public Map addRule(String rule, String ruleName, String description, String userID) { - Map responseMap = new HashMap<>(); - if(rule!=null && !PolicyUtils.brmsRawValidate(rule).contains("[ERR")){ - List duplicateData = commonClassDao.checkDuplicateEntry(ruleName, "ruleName", BRMSParamTemplate.class); - if(duplicateData!=null && !duplicateData.isEmpty()){ - LOGGER.error("Import new service failed. Service already exists"); - responseMap.put("DBError", "EXISTS"); - return responseMap; - }else{ - BRMSParamTemplate brmsParamTemplate = new BRMSParamTemplate(); - brmsParamTemplate.setDescription(description); - brmsParamTemplate.setRuleName(ruleName); - brmsParamTemplate.setRule(rule); - UserInfo userCreatedBy = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", userID); - brmsParamTemplate.setUserCreatedBy(userCreatedBy); - commonClassDao.save(brmsParamTemplate); - LOGGER.info("Template created with " + ruleName + " by " + userID); - } - responseMap.put("success", "success"); - }else{ - LOGGER.debug("Error during validating the rule for creating record for BRMS Param Template"); - responseMap.put("error", "VALIDATION"); - } - return responseMap; - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java deleted file mode 100644 index b9dc039fc..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java +++ /dev/null @@ -1,692 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.io.FilenameUtils; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.controller.BRMSDictionaryController; -import org.openecomp.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.jpa.BRMSParamTemplate; - -import com.att.research.xacml.std.IdentifierImpl; - -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.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -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; - -public class CreateBrmsParamPolicy extends Policy { - - private static final Logger LOGGER = FlexLogger.getLogger(CreateBrmsParamPolicy.class); - - public CreateBrmsParamPolicy() { - super(); - } - - public CreateBrmsParamPolicy(PolicyRestAdapter policyAdapter) { - this.policyAdapter = policyAdapter; - this.policyAdapter.setConfigType(policyAdapter.getConfigType()); - - } - - public String expandConfigBody(String ruleContents, Map brmsParamBody) { - - Map copyMap=new HashMap<>(); - copyMap.putAll(brmsParamBody); - copyMap.put("policyName", policyName.substring(0, policyName.replace(".xml", "").lastIndexOf("."))); - copyMap.put("policyScope", policyAdapter.getDomainDir()); - copyMap.put("policyVersion",policyAdapter.getHighestVersion().toString()); - copyMap.put("unique", ("p"+policyName+UUID.randomUUID().toString()).replaceAll("[^A-Za-z0-9]", "")); - - //Finding all the keys in the Map data-structure. - Iterator iterator = copyMap.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(ruleContents); - //Replacing the value with the inputs provided by the user in the editor. - String finalInput = copyMap.get(input); - if(finalInput.contains("$")){ - finalInput = finalInput.replace("$", "\\$"); - } - ruleContents=m.replaceAll(finalInput); - } - return ruleContents; - } - - - - // Utility to read json data from the existing file to a string - static String readFile(String path, Charset encoding) throws IOException { - - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded, encoding); - - } - - // Saving the Configurations file at server location for config policy. - protected void saveConfigurations(String policyName, String ruleBody) { - try { - if (policyName.endsWith(".xml")) { - policyName = policyName.substring(0, - policyName.lastIndexOf(".xml")); - } - PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt"); - String expandedBody=expandConfigBody(ruleBody,policyAdapter.getBrmsParamBody()); - out.println(expandedBody); - policyAdapter.setJsonBody(expandedBody); - policyAdapter.setConfigBodyData(expandedBody); - out.close(); - - - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving configuration file"); - } - } - - - // Here we are adding the extension for the configurations file based on the - // config type selection for saving. - private String getConfigFile(String filename) { - filename = FilenameUtils.removeExtension(filename); - if (filename.endsWith(".txt")) { - filename = filename.substring(0, filename.length() - 3); - } - - filename = filename + ".txt"; - return filename; - } - - // Validations for Config form - public boolean validateConfigForm() { - - // Validating mandatory Fields. - isValidForm = true; - return isValidForm; - - } - - @Override - public Map savePolicies() throws Exception { - - Map successMap = new HashMap<>(); - if(isPolicyExists()){ - successMap.put("EXISTS", "This Policy already exist on the PAP"); - return successMap; - } - - if (!isPreparedToSave()) { - prepareToSave(); - } - // Until here we prepared the data and here calling the method to create - // xml. - Path newPolicyPath = null; - newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); - if(successMap == null){ - successMap = new HashMap<>(); - PolicyLogger.error("Failed to Update the Database Dictionary Tables."); - successMap.put("error", "DB UPDATE"); - } - return successMap; - } - - private String getValueFromDictionary(String templateName){ - String ruleTemplate = null; - CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - String queryString="from BRMSParamTemplate where param_template_name= '"+templateName+"'"; - List result = dbConnection.getDataByQuery(queryString); - if(!result.isEmpty()){ - BRMSParamTemplate template = (BRMSParamTemplate) result.get(0); - ruleTemplate = template.getRule(); - } - return ruleTemplate; - } - - protected Map findType(String rule) { - Map mapFieldType= new HashMap<>(); - if(rule!=null){ - try { - String params = ""; - 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("//")) { - if(!(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) { - line = line.split("\\/\\*")[0]; - } - } else { - line = line.split("\\/\\*")[0]; - } - } - if (line.contains("*/")) { - comment = false; - try { - line = line.split("\\*\\/")[1].replace("*/", ""); - } catch (Exception e) { - line = ""; - } - } - if (comment) { - continue; - } - if (flag) { - params = params + line; - } - if (line.contains("declare Params")) { - params = params + line; - flag = true; - } - if (line.contains("end") && flag) { - break; - } - } - params = params.replace("declare Params", "").replace("end", "") - .replaceAll("\\s+", ""); - String[] components = params.split(":"); - String caption = ""; - for (int i = 0; i < components.length; i++) { - String type = ""; - if (i == 0) { - caption = components[i]; - } - if(caption.equals("")){ - break; - } - String nextComponent = ""; - try { - nextComponent = components[i + 1]; - } catch (Exception e) { - nextComponent = components[i]; - } - //If the type is of type String then we add the UI Item and type to the map. - if (nextComponent.startsWith("String")) { - type = "String"; - mapFieldType.put(caption, type); - caption = nextComponent.replace("String", ""); - } else if (nextComponent.startsWith("int")) { - type = "int"; - mapFieldType.put(caption, type); - caption = nextComponent.replace("int", ""); - } - } - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CreateBrmsParamPolicy", "Exception parsing file in findType"); - } - } - return mapFieldType; - } - - // This is the method for preparing the policy for saving. We have broken it - // out - // separately because the fully configured policy is used for multiple - // things - @Override - public boolean prepareToSave() throws Exception { - - if (isPreparedToSave()) { - // we have already done this - return true; - } - - int version = 0; - String policyID = policyAdapter.getPolicyID(); - version = policyAdapter.getHighestVersion(); - - // Create the Instance for pojo, PolicyType object is used in - // marshalling. - if (policyAdapter.getPolicyType().equals("Config")) { - PolicyType policyConfig = new PolicyType(); - - policyConfig.setVersion(Integer.toString(version)); - policyConfig.setPolicyId(policyID); - policyConfig.setTarget(new TargetType()); - policyAdapter.setData(policyConfig); - } - - policyName = policyAdapter.getNewFileName(); - - if (policyAdapter.getData() != null) { - Map ruleAndUIValue= policyAdapter.getBrmsParamBody(); - String tempateValue= ruleAndUIValue.get("templateName"); - String valueFromDictionary= getValueFromDictionary(tempateValue); - - //Get the type of the UI Fields. - Map typeOfUIField=findType(valueFromDictionary); - String generatedRule=null; - String body = ""; - - try { - - try { - body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " + - "<$%BRMSParamTemplate=" + tempateValue + "%$> \n */ \n"; - body = body + valueFromDictionary + "\n"; - generatedRule = "rule \"" +policyName.substring(0, policyName.replace(".xml", "").lastIndexOf(".")) +".Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();"; - - //We first read the map data structure(ruleAndUIValue) received from the PAP-ADMIN - //We ignore if the key is "templateName as we are interested only in the UI fields and its value. - //We have one more map data structure(typeOfUIField) created by parsing the Drools rule. - //From the type of the UI field(String/int) we structure whether to put the "" or not. - for (Map.Entry entry : ruleAndUIValue.entrySet()) { - if(entry.getKey()!="templateName") - { - for(Map.Entry fieldType:typeOfUIField.entrySet()) - { - if(fieldType.getKey().equalsIgnoreCase(entry.getKey())) - { - String key = entry.getKey().substring(0, 1).toUpperCase() + entry.getKey().substring(1); - if(fieldType.getValue()=="String") - { - //Type is String - generatedRule = generatedRule + "\n\t\tparams.set" - + key + "(\"" - + entry.getValue() + "\");"; - } - else{ - generatedRule = generatedRule + "\n\t\tparams.set" - + key + "(" - + entry.getValue() + ");"; - } - } - } - } - } - - generatedRule = generatedRule - + "\n\t\tinsert(params);\nend"; - LOGGER.info("New rule generated with :" + generatedRule); - body = body + generatedRule; - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy"); - } - } - catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy"); - } - - saveConfigurations(policyName,body); - - // Make sure the filename ends with an extension - if (policyName.endsWith(".xml") == false) { - policyName = policyName + ".xml"; - } - - PolicyType configPolicy = (PolicyType) policyAdapter.getData(); - - configPolicy.setDescription(policyAdapter.getPolicyDescription()); - - configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); - - AllOfType allOfOne = new AllOfType(); - - String fileName = policyAdapter.getNewFileName(); - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, - fileName.length()); - } - allOfOne.getMatch().add(createMatch("PolicyName", name)); - - - AllOfType allOf = new AllOfType(); - - // Match for ECOMPName - allOf.getMatch().add(createMatch("ECOMPName", policyAdapter.getEcompName())); - allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName())); - // Match for riskType - allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); - // Match for riskLevel - allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); - // Match for riskguard - allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); - // Match for ttlDate - allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); - AnyOfType anyOf = new AnyOfType(); - anyOf.getAllOf().add(allOfOne); - anyOf.getAllOf().add(allOf); - - TargetType target = new TargetType(); - ((TargetType) target).getAnyOf().add(anyOf); - - // Adding the target to the policy element - configPolicy.setTarget((TargetType) target); - - RuleType rule = new RuleType(); - rule.setRuleId(policyAdapter.getRuleID()); - - rule.setEffect(EffectType.PERMIT); - - // Create Target in Rule - AllOfType allOfInRule = new AllOfType(); - - // Creating match for ACCESS in rule target - MatchType accessMatch = new MatchType(); - AttributeValueType accessAttributeValue = new AttributeValueType(); - accessAttributeValue.setDataType(STRING_DATATYPE); - accessAttributeValue.getContent().add("ACCESS"); - accessMatch.setAttributeValue(accessAttributeValue); - AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); - URI accessURI = null; - try { - accessURI = new URI(ACTION_ID); - } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy", "Exception creating ACCESS URI"); - } - accessAttributeDesignator.setCategory(CATEGORY_ACTION); - accessAttributeDesignator.setDataType(STRING_DATATYPE); - accessAttributeDesignator.setAttributeId(new IdentifierImpl( - accessURI).stringValue()); - accessMatch.setAttributeDesignator(accessAttributeDesignator); - accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - // Creating Config Match in rule Target - MatchType configMatch = new MatchType(); - AttributeValueType configAttributeValue = new AttributeValueType(); - configAttributeValue.setDataType(STRING_DATATYPE); - - configAttributeValue.getContent().add("Config"); - - configMatch.setAttributeValue(configAttributeValue); - AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType(); - URI configURI = null; - try { - configURI = new URI(RESOURCE_ID); - } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy", "Exception creating Config URI"); - } - - configAttributeDesignator.setCategory(CATEGORY_RESOURCE); - configAttributeDesignator.setDataType(STRING_DATATYPE); - configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue()); - configMatch.setAttributeDesignator(configAttributeDesignator); - configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - allOfInRule.getMatch().add(accessMatch); - allOfInRule.getMatch().add(configMatch); - - AnyOfType anyOfInRule = new AnyOfType(); - anyOfInRule.getAllOf().add(allOfInRule); - - TargetType targetInRule = new TargetType(); - targetInRule.getAnyOf().add(anyOfInRule); - - rule.setTarget(targetInRule); - rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); - - configPolicy - .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() - .add(rule); - policyAdapter.setPolicyData(configPolicy); - - } else { - PolicyLogger.error("Unsupported data object." - + policyAdapter.getData().getClass().getCanonicalName()); - } - setPreparedToSave(true); - return true; - } - - // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, - String fileName) { - - //Policy Config ID Assignment - AdviceExpressionsType advices = new AdviceExpressionsType(); - AdviceExpressionType advice = new AdviceExpressionType(); - advice.setAdviceId("BRMSPARAMID"); - advice.setAppliesTo(EffectType.PERMIT); - // For Configuration - AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); - assignment1.setAttributeId("type"); - assignment1.setCategory(CATEGORY_RESOURCE); - assignment1.setIssuer(""); - AttributeValueType configNameAttributeValue = new AttributeValueType(); - configNameAttributeValue.setDataType(STRING_DATATYPE); - configNameAttributeValue.getContent().add("Configuration"); - assignment1.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue)); - advice.getAttributeAssignmentExpression().add(assignment1); - - // For Config file Url if configurations are provided. - // URL ID Assignment - AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); - assignment2.setAttributeId("URLID"); - assignment2.setCategory(CATEGORY_RESOURCE); - assignment2.setIssuer(""); - AttributeValueType AttributeValue = new AttributeValueType(); - AttributeValue.setDataType(URI_DATATYPE); - - String content = CONFIG_URL + "/Config/"+ getConfigFile(policyName); - - AttributeValue.getContent().add(content); - assignment2.setExpression(new ObjectFactory() - .createAttributeValue(AttributeValue)); - advice.getAttributeAssignmentExpression().add(assignment2); - - // Policy Name Assignment - AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); - assignment3.setAttributeId("PolicyName"); - assignment3.setCategory(CATEGORY_RESOURCE); - assignment3.setIssuer(""); - AttributeValueType attributeValue3 = new AttributeValueType(); - attributeValue3.setDataType(STRING_DATATYPE); - fileName = FilenameUtils.removeExtension(fileName); - fileName = fileName + ".xml"; - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, - fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, - fileName.length()); - } - attributeValue3.getContent().add(name); - assignment3.setExpression(new ObjectFactory() - .createAttributeValue(attributeValue3)); - advice.getAttributeAssignmentExpression().add(assignment3); - - // Version Number Assignment - AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); - assignment4.setAttributeId("VersionNumber"); - assignment4.setCategory(CATEGORY_RESOURCE); - assignment4.setIssuer(""); - AttributeValueType configNameAttributeValue4 = new AttributeValueType(); - configNameAttributeValue4.setDataType(STRING_DATATYPE); - configNameAttributeValue4.getContent().add(Integer.toString(version)); - assignment4.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue4)); - advice.getAttributeAssignmentExpression().add(assignment4); - - // Ecomp Name Assignment - AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); - assignment5.setAttributeId("matching:" + ECOMPID); - assignment5.setCategory(CATEGORY_RESOURCE); - assignment5.setIssuer(""); - AttributeValueType configNameAttributeValue5 = new AttributeValueType(); - configNameAttributeValue5.setDataType(STRING_DATATYPE); - configNameAttributeValue5.getContent().add(policyAdapter.getEcompName()); - assignment5.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue5)); - advice.getAttributeAssignmentExpression().add(assignment5); - - - //Config Name Assignment - AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); - assignment6.setAttributeId("matching:" +CONFIGID); - assignment6.setCategory(CATEGORY_RESOURCE); - assignment6.setIssuer(""); - AttributeValueType configNameAttributeValue6 = new AttributeValueType(); - configNameAttributeValue6.setDataType(STRING_DATATYPE); - configNameAttributeValue6.getContent().add(policyAdapter.getConfigName()); - assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); - advice.getAttributeAssignmentExpression().add(assignment6); - // Adding Controller Information. - if(policyAdapter.getBrmsController()!=null){ - BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("controller:"+ policyAdapter.getBrmsController(), - brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController())); - } - - // Adding Dependencies. - if(policyAdapter.getBrmsDependency()!=null){ - BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); - ArrayList dependencies = new ArrayList<>(); - StringBuilder key = new StringBuilder(); - for(String dependencyName: policyAdapter.getBrmsDependency()){ - dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency()); - key.append(dependencyName + ","); - } - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("dependencies:"+key.toString(), dependencies.toString())); - } - - // Dynamic Field Config Attributes. - Map dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes(); - for (String keyField : dynamicFieldConfigAttributes.keySet()) { - advice.getAttributeAssignmentExpression().add(createResponseAttributes("key:"+keyField, dynamicFieldConfigAttributes.get(keyField))); - } - - //Risk Attributes - AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); - assignment8.setAttributeId("RiskType"); - assignment8.setCategory(CATEGORY_RESOURCE); - assignment8.setIssuer(""); - - AttributeValueType configNameAttributeValue8 = new AttributeValueType(); - configNameAttributeValue8.setDataType(STRING_DATATYPE); - configNameAttributeValue8.getContent().add(policyAdapter.getRiskType()); - assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8)); - - advice.getAttributeAssignmentExpression().add(assignment8); - - AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); - assignment9.setAttributeId("RiskLevel"); - assignment9.setCategory(CATEGORY_RESOURCE); - assignment9.setIssuer(""); - - AttributeValueType configNameAttributeValue9 = new AttributeValueType(); - configNameAttributeValue9.setDataType(STRING_DATATYPE); - configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel()); - assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); - - advice.getAttributeAssignmentExpression().add(assignment9); - - AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); - assignment10.setAttributeId("guard"); - assignment10.setCategory(CATEGORY_RESOURCE); - assignment10.setIssuer(""); - - AttributeValueType configNameAttributeValue10 = new AttributeValueType(); - configNameAttributeValue10.setDataType(STRING_DATATYPE); - configNameAttributeValue10.getContent().add(policyAdapter.getGuard()); - assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10)); - - advice.getAttributeAssignmentExpression().add(assignment10); - - AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType(); - assignment11.setAttributeId("TTLDate"); - assignment11.setCategory(CATEGORY_RESOURCE); - assignment11.setIssuer(""); - - AttributeValueType configNameAttributeValue11 = new AttributeValueType(); - configNameAttributeValue11.setDataType(STRING_DATATYPE); - configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate()); - assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11)); - - advice.getAttributeAssignmentExpression().add(assignment11); - - advices.getAdviceExpression().add(advice); - return advices; - } - - @Override - public Object getCorrectPolicyDataObject() { - return policyAdapter.getData(); - } - - private AttributeAssignmentExpressionType createResponseAttributes(String key, String value){ - AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); - assignment7.setAttributeId(key); - assignment7.setCategory(CATEGORY_RESOURCE); - assignment7.setIssuer(""); - AttributeValueType configNameAttributeValue7 = new AttributeValueType(); - configNameAttributeValue7.setDataType(STRING_DATATYPE); - configNameAttributeValue7.getContent().add(value); - assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); - return assignment7; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java deleted file mode 100644 index a0f13ec02..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java +++ /dev/null @@ -1,489 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.io.FilenameUtils; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.pap.xacml.rest.controller.BRMSDictionaryController; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; - -import com.att.research.xacml.std.IdentifierImpl; - -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.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -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; - - -public class CreateBrmsRawPolicy extends Policy { - - public CreateBrmsRawPolicy() { - super(); - } - - public CreateBrmsRawPolicy(PolicyRestAdapter policyAdapter) { - this.policyAdapter = policyAdapter; - this.policyAdapter.setConfigType(policyAdapter.getConfigType()); - - } - - // Saving the Configurations file at server location for CreateBrmsRawPolicy policy. - protected void saveConfigurations(String policyName, String jsonBody) { - try { - if (policyName.endsWith(".xml")) { - policyName = policyName.substring(0, - policyName.lastIndexOf(".xml")); - } - PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt"); - out.println(jsonBody); - out.close(); - - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsRawPolicy", "Exception saving configurations file"); - } - } - - // Utility to read json data from the existing file to a string - static String readFile(String path, Charset encoding) throws IOException { - - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded, encoding); - - } - - // Here we are adding the extension for the configurations file based on the - // config type selection for saving. - private String getConfigFile(String filename) { - filename = FilenameUtils.removeExtension(filename); - if (filename.endsWith(".txt")) { - filename = filename.substring(0, filename.length() - 3); - } - - filename = filename + ".txt"; - return filename; - } - - // Validations for Config form - public boolean validateConfigForm() { - - // Validating mandatory Fields. - isValidForm = true; - return isValidForm; - - } - - @Override - public Map savePolicies() throws Exception { - - Map successMap = new HashMap<>(); - if(isPolicyExists()){ - successMap.put("EXISTS", "This Policy already exist on the PAP"); - return successMap; - } - - if (!isPreparedToSave()) { - prepareToSave(); - } - // Until here we prepared the data and here calling the method to create - // xml. - Path newPolicyPath = null; - newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - - successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); - if (successMap == null) { - successMap = new HashMap<>(); - PolicyLogger.error("Failed to Update the Database Dictionary Tables."); - successMap.put("error", "DB UPDATE"); - } - - return successMap; - } - - // This is the method for preparing the policy for saving. We have broken it - // out - // separately because the fully configured policy is used for multiple - // things - @Override - public boolean prepareToSave() throws Exception { - - if (isPreparedToSave()) { - // we have already done this - return true; - } - - int version = 0; - String policyID = policyAdapter.getPolicyID(); - version = policyAdapter.getHighestVersion(); - - // Create the Instance for pojo, PolicyType object is used in - // marshalling. - if (policyAdapter.getPolicyType().equals("Config")) { - PolicyType policyConfig = new PolicyType(); - - policyConfig.setVersion(Integer.toString(version)); - policyConfig.setPolicyId(policyID); - policyConfig.setTarget(new TargetType()); - policyAdapter.setData(policyConfig); - } - - policyName = policyAdapter.getNewFileName(); - - if (policyAdapter.getData() != null) { - //String jsonBody = policyAdapter.getJsonBody(); - String configBody=policyAdapter.getConfigBodyData(); - saveConfigurations(policyName, configBody); - - // Make sure the filename ends with an extension - if (policyName.endsWith(".xml") == false) { - policyName = policyName + ".xml"; - } - - PolicyType configPolicy = (PolicyType) policyAdapter.getData(); - - configPolicy.setDescription(policyAdapter.getPolicyDescription()); - - configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); - - AllOfType allOfOne = new AllOfType(); - String fileName = policyAdapter.getNewFileName(); - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, - fileName.length()); - } - allOfOne.getMatch().add(createMatch("PolicyName", name)); - - - AllOfType allOf = new AllOfType(); - - // Match for ECOMPName - allOf.getMatch().add(createMatch("ECOMPName", policyAdapter.getEcompName())); - allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName())); - // Match for riskType - allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); - // Match for riskLevel - allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); - // Match for riskguard - allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); - // Match for ttlDate - allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); - AnyOfType anyOf = new AnyOfType(); - anyOf.getAllOf().add(allOfOne); - anyOf.getAllOf().add(allOf); - - TargetType target = new TargetType(); - ((TargetType) target).getAnyOf().add(anyOf); - - // Adding the target to the policy element - configPolicy.setTarget((TargetType) target); - - RuleType rule = new RuleType(); - rule.setRuleId(policyAdapter.getRuleID()); - - rule.setEffect(EffectType.PERMIT); - - // Create Target in Rule - AllOfType allOfInRule = new AllOfType(); - - // Creating match for ACCESS in rule target - MatchType accessMatch = new MatchType(); - AttributeValueType accessAttributeValue = new AttributeValueType(); - accessAttributeValue.setDataType(STRING_DATATYPE); - accessAttributeValue.getContent().add("ACCESS"); - accessMatch.setAttributeValue(accessAttributeValue); - AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); - URI accessURI = null; - try { - accessURI = new URI(ACTION_ID); - } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy", "Exception creating ACCESS URI"); - } - accessAttributeDesignator.setCategory(CATEGORY_ACTION); - accessAttributeDesignator.setDataType(STRING_DATATYPE); - accessAttributeDesignator.setAttributeId(new IdentifierImpl( - accessURI).stringValue()); - accessMatch.setAttributeDesignator(accessAttributeDesignator); - accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - // Creating Config Match in rule Target - MatchType configMatch = new MatchType(); - AttributeValueType configAttributeValue = new AttributeValueType(); - configAttributeValue.setDataType(STRING_DATATYPE); - - configAttributeValue.getContent().add("Config"); - - configMatch.setAttributeValue(configAttributeValue); - AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType(); - URI configURI = null; - try { - configURI = new URI(RESOURCE_ID); - } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy", "Exception creating Config URI"); - } - - configAttributeDesignator.setCategory(CATEGORY_RESOURCE); - configAttributeDesignator.setDataType(STRING_DATATYPE); - configAttributeDesignator.setAttributeId(new IdentifierImpl( - configURI).stringValue()); - configMatch.setAttributeDesignator(configAttributeDesignator); - configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - allOfInRule.getMatch().add(accessMatch); - allOfInRule.getMatch().add(configMatch); - - AnyOfType anyOfInRule = new AnyOfType(); - anyOfInRule.getAllOf().add(allOfInRule); - - TargetType targetInRule = new TargetType(); - targetInRule.getAnyOf().add(anyOfInRule); - - rule.setTarget(targetInRule); - rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); - - configPolicy - .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() - .add(rule); - policyAdapter.setPolicyData(configPolicy); - - } else { - PolicyLogger.error("Unsupported data object." - + policyAdapter.getData().getClass().getCanonicalName()); - } - setPreparedToSave(true); - return true; - } - - // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, - String fileName) { - - // Policy Config ID Assignment - AdviceExpressionsType advices = new AdviceExpressionsType(); - AdviceExpressionType advice = new AdviceExpressionType(); - advice.setAdviceId("BRMSRAWID"); - advice.setAppliesTo(EffectType.PERMIT); - // For Configuration - AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); - assignment1.setAttributeId("type"); - assignment1.setCategory(CATEGORY_RESOURCE); - assignment1.setIssuer(""); - AttributeValueType configNameAttributeValue = new AttributeValueType(); - configNameAttributeValue.setDataType(STRING_DATATYPE); - configNameAttributeValue.getContent().add("Configuration"); - assignment1.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue)); - advice.getAttributeAssignmentExpression().add(assignment1); - - // For Config file Url if configurations are provided. - // URL ID Assignment - AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); - assignment2.setAttributeId("URLID"); - assignment2.setCategory(CATEGORY_RESOURCE); - assignment2.setIssuer(""); - AttributeValueType AttributeValue = new AttributeValueType(); - AttributeValue.setDataType(URI_DATATYPE); - - String content = CONFIG_URL + "/Config/" + getConfigFile(policyName); - - AttributeValue.getContent().add(content); - assignment2.setExpression(new ObjectFactory() - .createAttributeValue(AttributeValue)); - advice.getAttributeAssignmentExpression().add(assignment2); - - // Policy Name Assignment - AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); - assignment3.setAttributeId("PolicyName"); - assignment3.setCategory(CATEGORY_RESOURCE); - assignment3.setIssuer(""); - AttributeValueType attributeValue3 = new AttributeValueType(); - attributeValue3.setDataType(STRING_DATATYPE); - fileName = FilenameUtils.removeExtension(fileName); - fileName = fileName + ".xml"; - System.out.println(fileName); - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, - fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, - fileName.length()); - } - System.out.println(name); - attributeValue3.getContent().add(name); - assignment3.setExpression(new ObjectFactory() - .createAttributeValue(attributeValue3)); - advice.getAttributeAssignmentExpression().add(assignment3); - - // Version Number Assignment - AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); - assignment4.setAttributeId("VersionNumber"); - assignment4.setCategory(CATEGORY_RESOURCE); - assignment4.setIssuer(""); - AttributeValueType configNameAttributeValue4 = new AttributeValueType(); - configNameAttributeValue4.setDataType(STRING_DATATYPE); - configNameAttributeValue4.getContent().add(Integer.toString(version)); - assignment4.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue4)); - advice.getAttributeAssignmentExpression().add(assignment4); - - // Ecomp Name Assignment - AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); - assignment5.setAttributeId("matching:" + ECOMPID); - assignment5.setCategory(CATEGORY_RESOURCE); - assignment5.setIssuer(""); - AttributeValueType configNameAttributeValue5 = new AttributeValueType(); - configNameAttributeValue5.setDataType(STRING_DATATYPE); - configNameAttributeValue5.getContent().add(policyAdapter.getEcompName()); - assignment5.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue5)); - advice.getAttributeAssignmentExpression().add(assignment5); - - - //Config Name Assignment - AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); - assignment6.setAttributeId("matching:" + CONFIGID); - assignment6.setCategory(CATEGORY_RESOURCE); - assignment6.setIssuer(""); - AttributeValueType configNameAttributeValue6 = new AttributeValueType(); - configNameAttributeValue6.setDataType(STRING_DATATYPE); - configNameAttributeValue6.getContent().add(policyAdapter.getConfigName()); - assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); - advice.getAttributeAssignmentExpression().add(assignment6); - - // Adding Controller Information. - if(policyAdapter.getBrmsController()!=null){ - BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("controller:"+ policyAdapter.getBrmsController(), - brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController())); - } - - // Adding Dependencies. - if(policyAdapter.getBrmsDependency()!=null){ - BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); - ArrayList dependencies = new ArrayList<>(); - StringBuilder key = new StringBuilder(); - for(String dependencyName: policyAdapter.getBrmsDependency()){ - dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency()); - key.append(dependencyName + ","); - } - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("dependencies:"+key.toString(), dependencies.toString())); - } - - // Dynamic Field Config Attributes. - Map dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes(); - for (String keyField : dynamicFieldConfigAttributes.keySet()) { - advice.getAttributeAssignmentExpression().add(createResponseAttributes("key:"+keyField, dynamicFieldConfigAttributes.get(keyField))); - } - - //Risk Attributes - AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); - assignment8.setAttributeId("RiskType"); - assignment8.setCategory(CATEGORY_RESOURCE); - assignment8.setIssuer(""); - - AttributeValueType configNameAttributeValue8 = new AttributeValueType(); - configNameAttributeValue8.setDataType(STRING_DATATYPE); - configNameAttributeValue8.getContent().add(policyAdapter.getRiskType()); - assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8)); - - advice.getAttributeAssignmentExpression().add(assignment8); - - AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); - assignment9.setAttributeId("RiskLevel"); - assignment9.setCategory(CATEGORY_RESOURCE); - assignment9.setIssuer(""); - - AttributeValueType configNameAttributeValue9 = new AttributeValueType(); - configNameAttributeValue9.setDataType(STRING_DATATYPE); - configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel()); - assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); - - advice.getAttributeAssignmentExpression().add(assignment9); - - AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); - assignment10.setAttributeId("guard"); - assignment10.setCategory(CATEGORY_RESOURCE); - assignment10.setIssuer(""); - - AttributeValueType configNameAttributeValue10 = new AttributeValueType(); - configNameAttributeValue10.setDataType(STRING_DATATYPE); - configNameAttributeValue10.getContent().add(policyAdapter.getGuard()); - assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10)); - - advice.getAttributeAssignmentExpression().add(assignment10); - - AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType(); - assignment11.setAttributeId("TTLDate"); - assignment11.setCategory(CATEGORY_RESOURCE); - assignment11.setIssuer(""); - - AttributeValueType configNameAttributeValue11 = new AttributeValueType(); - configNameAttributeValue11.setDataType(STRING_DATATYPE); - configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate()); - assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11)); - - advice.getAttributeAssignmentExpression().add(assignment11); - - advices.getAdviceExpression().add(advice); - return advices; - } - - @Override - public Object getCorrectPolicyDataObject() { - return policyAdapter.getData(); - } - - private AttributeAssignmentExpressionType createResponseAttributes(String key, String value){ - AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); - assignment7.setAttributeId(key); - assignment7.setCategory(CATEGORY_RESOURCE); - assignment7.setIssuer(""); - AttributeValueType configNameAttributeValue7 = new AttributeValueType(); - configNameAttributeValue7.setDataType(STRING_DATATYPE); - configNameAttributeValue7.getContent().add(value); - assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); - return assignment7; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java deleted file mode 100644 index a16ab9a79..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java +++ /dev/null @@ -1,412 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - - -import java.io.File; -import java.io.PrintWriter; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.io.FilenameUtils; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; - -import com.att.research.xacml.std.IdentifierImpl; - -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.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -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; - -public class CreateClosedLoopPerformanceMetrics extends Policy { - - private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPerformanceMetrics.class); - - public CreateClosedLoopPerformanceMetrics() { - super(); - } - - public CreateClosedLoopPerformanceMetrics(PolicyRestAdapter policyAdapter){ - this.policyAdapter = policyAdapter; - } - - //save configuration of the policy based on the policyname - private void saveConfigurations(String policyName, String jsonBody) { - try { - String body = null; - try { - body = jsonBody; - } catch (Exception e) { - LOGGER.error("Exception Occured"+e); - } - if(policyName.endsWith(".xml")){ - policyName = policyName.substring(0, policyName.lastIndexOf(".xml")); - } - PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + "."+ policyName +".json"); - out.println(body); - policyAdapter.setJsonBody(body); - policyAdapter.setConfigBodyData(body); - out.close(); - - } catch (Exception e) { - LOGGER.error("Exception Occured"+e); - } - } - - //getting the policy name and setting to configuration on adding .json - private String getConfigFile(String filename) { - filename = FilenameUtils.removeExtension(filename); - if (filename.endsWith(".xml")) { - filename = filename.substring(0, filename.length() - 4); - } - filename = filename +".json"; - return filename; - } - - @Override - public Map savePolicies() throws Exception { - - Map successMap = new HashMap<>(); - if(isPolicyExists()){ - successMap.put("EXISTS", "This Policy already exist on the PAP"); - return successMap; - } - - if(!isPreparedToSave()){ - //Prep and configure the policy for saving - prepareToSave(); - } - - // Until here we prepared the data and here calling the method to create xml. - Path newPolicyPath = null; - newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); - - return successMap; - } - - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things - @Override - public boolean prepareToSave() throws Exception{ - - if(isPreparedToSave()){ - //we have already done this - return true; - } - - int version = 0; - String policyID = policyAdapter.getPolicyID(); - version = policyAdapter.getHighestVersion(); - - // Create the Instance for pojo, PolicyType object is used in marshalling. - if (policyAdapter.getPolicyType().equals("Config")) { - PolicyType policyConfig = new PolicyType(); - - policyConfig.setVersion(Integer.toString(version)); - policyConfig.setPolicyId(policyID); - policyConfig.setTarget(new TargetType()); - policyAdapter.setData(policyConfig); - } - policyName = policyAdapter.getNewFileName(); - if (policyAdapter.getData() != null) { - // Save the Configurations file with the policy name with extention based on selection. - String jsonBody = policyAdapter.getJsonBody(); - saveConfigurations(policyName, jsonBody); - - // Make sure the filename ends with an extension - if (policyName.endsWith(".xml") == false) { - policyName = policyName + ".xml"; - } - - - PolicyType configPolicy = (PolicyType) policyAdapter.getData(); - - configPolicy.setDescription(policyAdapter.getPolicyDescription()); - - configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); - - AllOfType allOfOne = new AllOfType(); - String fileName = policyAdapter.getNewFileName(); - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); - } - allOfOne.getMatch().add(createMatch("PolicyName", name)); - AllOfType allOf = new AllOfType(); - - // Adding the matches to AllOfType element Match for Ecomp - allOf.getMatch().add(createMatch("ECOMPName", policyAdapter.getEcompName())); - // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); - // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); - // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); - // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); - // Match for ServiceType - allOf.getMatch().add(createMatch("ServiceType", policyAdapter.getServiceType())); - - AnyOfType anyOf = new AnyOfType(); - anyOf.getAllOf().add(allOfOne); - anyOf.getAllOf().add(allOf); - - TargetType target = new TargetType(); - ((TargetType) target).getAnyOf().add(anyOf); - - // Adding the target to the policy element - configPolicy.setTarget((TargetType) target); - - RuleType rule = new RuleType(); - rule.setRuleId(policyAdapter.getRuleID()); - - rule.setEffect(EffectType.PERMIT); - - // Create Target in Rule - AllOfType allOfInRule = new AllOfType(); - - // Creating match for ACCESS in rule target - MatchType accessMatch = new MatchType(); - AttributeValueType accessAttributeValue = new AttributeValueType(); - accessAttributeValue.setDataType(STRING_DATATYPE); - accessAttributeValue.getContent().add("ACCESS"); - accessMatch.setAttributeValue(accessAttributeValue); - AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); - URI accessURI = null; - try { - accessURI = new URI(ACTION_ID); - } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating ACCESS URI"); - } - accessAttributeDesignator.setCategory(CATEGORY_ACTION); - accessAttributeDesignator.setDataType(STRING_DATATYPE); - accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); - accessMatch.setAttributeDesignator(accessAttributeDesignator); - accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - // Creating Config Match in rule Target - MatchType configMatch = new MatchType(); - AttributeValueType configAttributeValue = new AttributeValueType(); - configAttributeValue.setDataType(STRING_DATATYPE); - configAttributeValue.getContent().add("Config"); - configMatch.setAttributeValue(configAttributeValue); - AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType(); - URI configURI = null; - try { - configURI = new URI(RESOURCE_ID); - } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating Config URI"); - } - configAttributeDesignator.setCategory(CATEGORY_RESOURCE); - configAttributeDesignator.setDataType(STRING_DATATYPE); - configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue()); - configMatch.setAttributeDesignator(configAttributeDesignator); - configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - allOfInRule.getMatch().add(accessMatch); - allOfInRule.getMatch().add(configMatch); - - AnyOfType anyOfInRule = new AnyOfType(); - anyOfInRule.getAllOf().add(allOfInRule); - - TargetType targetInRule = new TargetType(); - targetInRule.getAnyOf().add(anyOfInRule); - - rule.setTarget(targetInRule); - rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); - - configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); - policyAdapter.setPolicyData(configPolicy); - - } else { - PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); - } - setPreparedToSave(true); - return true; - } - - // Data required for Advice part is setting here. - @SuppressWarnings("static-access") - private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { - AdviceExpressionsType advices = new AdviceExpressionsType(); - AdviceExpressionType advice = new AdviceExpressionType(); - advice.setAdviceId("PMID"); - advice.setAppliesTo(EffectType.PERMIT); - // For Configuration - AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); - assignment1.setAttributeId("type"); - assignment1.setCategory(CATEGORY_RESOURCE); - assignment1.setIssuer(""); - - AttributeValueType configNameAttributeValue = new AttributeValueType(); - configNameAttributeValue.setDataType(STRING_DATATYPE); - configNameAttributeValue.getContent().add("Configuration"); - assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); - - advice.getAttributeAssignmentExpression().add(assignment1); - // For Config file Url if configurations are provided. - AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); - assignment2.setAttributeId("URLID"); - assignment2.setCategory(CATEGORY_RESOURCE); - assignment2.setIssuer(""); - - AttributeValueType AttributeValue = new AttributeValueType(); - AttributeValue.setDataType(URI_DATATYPE); - String content = CONFIG_URL +"/Config/"+ getConfigFile(policyName); - AttributeValue.getContent().add(content); - assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); - - advice.getAttributeAssignmentExpression().add(assignment2); - AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); - assignment3.setAttributeId("PolicyName"); - assignment3.setCategory(CATEGORY_RESOURCE); - assignment3.setIssuer(""); - - AttributeValueType attributeValue3 = new AttributeValueType(); - attributeValue3.setDataType(STRING_DATATYPE); - fileName = FilenameUtils.removeExtension(fileName); - fileName = fileName + ".xml"; - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); - } - attributeValue3.getContent().add(name); - assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); - advice.getAttributeAssignmentExpression().add(assignment3); - - AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); - assignment4.setAttributeId("VersionNumber"); - assignment4.setCategory(CATEGORY_RESOURCE); - assignment4.setIssuer(""); - - AttributeValueType configNameAttributeValue4 = new AttributeValueType(); - configNameAttributeValue4.setDataType(STRING_DATATYPE); - configNameAttributeValue4.getContent().add(Integer.toString(version)); - assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); - - advice.getAttributeAssignmentExpression().add(assignment4); - - AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); - assignment5.setAttributeId("matching:" + this.ECOMPID); - assignment5.setCategory(CATEGORY_RESOURCE); - assignment5.setIssuer(""); - - AttributeValueType configNameAttributeValue5 = new AttributeValueType(); - configNameAttributeValue5.setDataType(STRING_DATATYPE); - configNameAttributeValue5.getContent().add(policyAdapter.getEcompName()); - assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); - - advice.getAttributeAssignmentExpression().add(assignment5); - - AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); - assignment6.setAttributeId("matching:" + this.CLOSEDLOOPID); - assignment6.setCategory(CATEGORY_RESOURCE); - assignment6.setIssuer(""); - - AttributeValueType configNameAttributeValue6 = new AttributeValueType(); - configNameAttributeValue6.setDataType(STRING_DATATYPE); - configNameAttributeValue6.getContent().add(policyAdapter.getServiceType()); - assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); - - advice.getAttributeAssignmentExpression().add(assignment6); - - //Risk Attributes - AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); - assignment7.setAttributeId("RiskType"); - assignment7.setCategory(CATEGORY_RESOURCE); - assignment7.setIssuer(""); - - AttributeValueType configNameAttributeValue7 = new AttributeValueType(); - configNameAttributeValue7.setDataType(STRING_DATATYPE); - configNameAttributeValue7.getContent().add(policyAdapter.getRiskType()); - assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); - - advice.getAttributeAssignmentExpression().add(assignment7); - - AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); - assignment8.setAttributeId("RiskLevel"); - assignment8.setCategory(CATEGORY_RESOURCE); - assignment8.setIssuer(""); - - AttributeValueType configNameAttributeValue8 = new AttributeValueType(); - configNameAttributeValue8.setDataType(STRING_DATATYPE); - configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel()); - assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8)); - - advice.getAttributeAssignmentExpression().add(assignment8); - - AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); - assignment9.setAttributeId("guard"); - assignment9.setCategory(CATEGORY_RESOURCE); - assignment9.setIssuer(""); - - AttributeValueType configNameAttributeValue9 = new AttributeValueType(); - configNameAttributeValue9.setDataType(STRING_DATATYPE); - configNameAttributeValue9.getContent().add(policyAdapter.getGuard()); - assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); - - advice.getAttributeAssignmentExpression().add(assignment9); - - AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); - assignment10.setAttributeId("TTLDate"); - assignment10.setCategory(CATEGORY_RESOURCE); - assignment10.setIssuer(""); - - AttributeValueType configNameAttributeValue10 = new AttributeValueType(); - configNameAttributeValue10.setDataType(STRING_DATATYPE); - configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate()); - assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10)); - - advice.getAttributeAssignmentExpression().add(assignment10); - - advices.getAdviceExpression().add(advice); - return advices; - } - - @Override - public Object getCorrectPolicyDataObject() { - return policyAdapter.getPolicyData(); - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java deleted file mode 100644 index e801a459d..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java +++ /dev/null @@ -1,248 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang.StringUtils; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -import org.openecomp.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; -import org.openecomp.policy.rest.jpa.MicroServiceModels; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.openecomp.policy.rest.util.MSAttributeObject; -import org.openecomp.policy.rest.util.MSModelUtils; -import org.openecomp.policy.rest.util.MSModelUtils.MODEL_TYPE; - -public class CreateNewMicroServiceModel { - private static final Logger logger = FlexLogger.getLogger(CreateNewMicroServiceModel.class); - private MicroServiceModels newModel = null; - private HashMap classMap = new HashMap<>(); - - - MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsEcompName(), XACMLPapServlet.getMsPolicyName()); - - public CreateNewMicroServiceModel(String fileName, String serviceName, String string, String version) { - super(); - } - - public CreateNewMicroServiceModel(String importFile, String modelName, String description, String version, String randomID) { - - this.newModel = new MicroServiceModels(); - this.newModel.setVersion(version); - this.newModel.setModelName(modelName); - UserInfo userInfo = new UserInfo(); - userInfo.setUserLoginId("API"); - this.newModel.setUserCreatedBy(userInfo); - String cleanUpFile = null; - - HashMap tempMap = new HashMap<>(); - //Need to delete the file - if (importFile.contains(".zip")){ - extractFolder(randomID + ".zip"); - File directory = new File("ExtractDir" + File.separator + randomID); - List fileList = listModelFiles(directory.toString()); - //get all the files from a director - for (File file : fileList){ - if (file.isFile()){ - tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI); - classMap.putAll(tempMap); - } - } - cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip"; - try { - FileUtils.deleteDirectory(new File("ExtractDir" + File.separator + randomID)); - FileUtils.deleteDirectory(new File(randomID)); - File deleteFile = new File(cleanUpFile); - FileUtils.forceDelete(deleteFile); - } catch (IOException e) { - logger.error("Failed to unzip model file " + randomID); - } - }else { - tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID+".xmi", MODEL_TYPE.XMI); - classMap.putAll(tempMap); - cleanUpFile = "ExtractDir" + File.separator + randomID+".xmi"; - File deleteFile = new File(cleanUpFile); - deleteFile.delete(); - } - } - - 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()) { - resultList.addAll(listModelFiles(file.getAbsolutePath())); - } - } - return resultList; - } - - @SuppressWarnings("rawtypes") - private void extractFolder(String zipFile) { - int BUFFER = 2048; - File file = new File(zipFile); - - ZipFile zip = null; - try { - zip = new ZipFile("ExtractDir" + File.separator +file); - String newPath = zipFile.substring(0, zipFile.length() - 4); - 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("ExtractDir" + File.separator + newPath + 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 + e); - }finally{ - if(zip != null){ - try { - zip.close(); - } catch (Exception e) { - logger.error("Exception Occured while closing the zip file"+e); - } - } - } - } - - public Map addValuesToNewModel() { - - Map successMap = new HashMap<>(); - MSAttributeObject mainClass = null; - ArrayList dependency = null; - String subAttribute = null; - - if (!classMap.containsKey(this.newModel.getModelName())){ - logger.error("Model Provided does not contain the service name provided in request. Unable to import new model"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", "Unable to pull out required values, file missing service name provided in request"); - successMap.put("error", "MISSING"); - return successMap; - } - mainClass = classMap.get(this.newModel.getModelName()); - String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""}); - this.newModel.setDependency(dependTemp); - if (!this.newModel.getDependency().equals("")){ - dependency = new ArrayList(Arrays.asList(dependTemp.split(","))); - dependency = utils.getFullDependencyList(dependency, classMap); - if (!dependency.isEmpty()){ - for (String element : dependency){ - MSAttributeObject temp = new MSAttributeObject(); - if (classMap.containsKey(element)){ - temp = classMap.get(element); - mainClass.addAllRefAttribute(temp.getRefAttribute()); - mainClass.addAllAttribute(temp.getAttribute()); - } - } - } - } - subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName()); - - this.newModel.setSub_attributes(subAttribute); - this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", "")); - this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", "")); - this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); - this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); - successMap.put("success", "success"); - return successMap; - - } - - public Map saveImportService(){ - String modelName = this.newModel.getModelName(); - String imported_by = "API"; - String version = this.newModel.getVersion(); - Map successMap = new HashMap<>(); - CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - List result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+version); - if(result.isEmpty()){ - MicroServiceModels model = new MicroServiceModels(); - model.setModelName(modelName); - model.setVersion(version); - model.setAttributes(this.newModel.getAttributes()); - model.setAnnotation(this.newModel.getAnnotation()); - model.setDependency(this.newModel.getDependency()); - model.setDescription(this.newModel.getDescription()); - model.setEnumValues(this.newModel.getEnumValues()); - model.setRef_attributes(this.newModel.getRef_attributes()); - model.setSub_attributes(this.newModel.getSub_attributes()); - UserInfo userInfo = new UserInfo(); - userInfo.setUserLoginId(imported_by); - userInfo.setUserName(imported_by); - model.setUserCreatedBy(userInfo); - dbConnection.save(model); - successMap.put("success", "success"); - }else{ - successMap.put("DBError", "EXISTS"); - logger.error("Import new service failed. Service already exists"); - } - return successMap; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java deleted file mode 100644 index 5a566c9bd..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/DecisionPolicy.java +++ /dev/null @@ -1,793 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; -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.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.persistence.EntityManager; -import javax.persistence.Query; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.controlloop.policy.builder.BuilderException; -import org.openecomp.policy.controlloop.policy.builder.Results; -import org.openecomp.policy.controlloop.policy.guard.Constraint; -import org.openecomp.policy.controlloop.policy.guard.ControlLoopGuard; -import org.openecomp.policy.controlloop.policy.guard.Guard; -import org.openecomp.policy.controlloop.policy.guard.GuardPolicy; -import org.openecomp.policy.controlloop.policy.guard.MatchParameters; -import org.openecomp.policy.controlloop.policy.guard.builder.ControlLoopGuardBuilder; -import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -import org.openecomp.policy.pap.xacml.rest.util.JPAUtils; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.jpa.Datatype; -import org.openecomp.policy.rest.jpa.DecisionSettings; -import org.openecomp.policy.rest.jpa.FunctionDefinition; -import org.openecomp.policy.utils.PolicyUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.std.pip.engines.aaf.AAFEngine; -import org.openecomp.policy.xacml.util.XACMLPolicyScanner; - -import com.att.research.xacml.std.IdentifierImpl; - -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.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.ObjectFactory; -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; - -public class DecisionPolicy extends Policy { - - private static final Logger LOGGER = FlexLogger.getLogger(DecisionPolicy.class); - - public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not"; - private static final String AAFPROVIDER = "AAF"; - public static final String GUARD_YAML = "GUARD_YAML"; - public static final String GUARD_BL_YAML = "GUARD_BL_YAML"; - public static final String RAINY_DAY = "Rainy_Day"; - private static final String XACML_GUARD_TEMPLATE = "Decision_GuardPolicyTemplate.xml"; - private static final String XACML_BLGUARD_TEMPLATE = "Decision_GuardBLPolicyTemplate.xml"; - - private static final String ECOMPNAME = "ECOMPName"; - private static final String POLICY_NAME = "PolicyName"; - private static final String DESCRIPTION = "description"; - - - List dynamicLabelRuleAlgorithms = new LinkedList<>(); - List dynamicFieldComboRuleAlgorithms = new LinkedList<>(); - List dynamicFieldOneRuleAlgorithms = new LinkedList<>(); - List dynamicFieldTwoRuleAlgorithms = new LinkedList<>(); - List dataTypeList = new LinkedList<>(); - - protected Map dropDownMap = new HashMap<>(); - - - public DecisionPolicy() { - super(); - } - - public DecisionPolicy(PolicyRestAdapter policyAdapter){ - this.policyAdapter = policyAdapter; - } - - @Override - public Map savePolicies() throws Exception { - - Map successMap = new HashMap<>(); - if(isPolicyExists()){ - successMap.put("EXISTS", "This Policy already exist on the PAP"); - return successMap; - } - - if(!isPreparedToSave()){ - //Prep and configure the policy for saving - prepareToSave(); - } - - // Until here we prepared the data and here calling the method to create xml. - Path newPolicyPath = null; - newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); - return successMap; - } - - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things - @Override - public boolean prepareToSave() throws Exception{ - - if(isPreparedToSave()){ - //we have already done this - return true; - } - - int version = 0; - String policyID = policyAdapter.getPolicyID(); - version = policyAdapter.getHighestVersion(); - - // Create the Instance for pojo, PolicyType object is used in marshalling. - if ("Decision".equals(policyAdapter.getPolicyType())) { - PolicyType policyConfig = new PolicyType(); - - policyConfig.setVersion(Integer.toString(version)); - policyConfig.setPolicyId(policyID); - policyConfig.setTarget(new TargetType()); - policyAdapter.setData(policyConfig); - } - policyName = policyAdapter.getNewFileName(); - - if(policyAdapter.getRuleProvider().equals(GUARD_YAML) || policyAdapter.getRuleProvider().equals(GUARD_BL_YAML)){ - Map yamlParams = new HashMap<>(); - yamlParams.put(DESCRIPTION, (policyAdapter.getPolicyDescription()!=null)? policyAdapter.getPolicyDescription(): "YAML Guard Policy"); - String fileName = policyAdapter.getNewFileName(); - String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length()); - if ((name == null) || ("".equals(name))) { - name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length()); - } - yamlParams.put(POLICY_NAME, name); - yamlParams.put(ECOMPNAME, policyAdapter.getEcompName()); - Map params = policyAdapter.getDynamicFieldConfigAttributes(); - yamlParams.putAll(params); - // Call YAML to XACML - PolicyType decisionPolicy = getGuardPolicy(yamlParams, policyAdapter.getRuleProvider()); - decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); - decisionPolicy.setVersion(Integer.toString(version)); - policyAdapter.setPolicyData(decisionPolicy); - policyAdapter.setData(decisionPolicy); - }else if (policyAdapter.getData() != null) { - PolicyType decisionPolicy = (PolicyType) policyAdapter.getData(); - - decisionPolicy.setDescription(policyAdapter.getPolicyDescription()); - - decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); - AllOfType allOfOne = new AllOfType(); - String fileName = policyAdapter.getNewFileName(); - String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length()); - if ((name == null) || ("".equals(name))) { - name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length()); - } - allOfOne.getMatch().add(createMatch(POLICY_NAME, name)); - - AllOfType allOf = new AllOfType(); - - // Match for Ecomp - allOf.getMatch().add(createMatch(ECOMPNAME, (policyAdapter.getEcompName()))); - - Map dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes(); - if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){ - dynamicFieldComponentAttributes = new HashMap<>(); - } - - // If there is any dynamic field attributes create the matches here - for (String keyField : dynamicFieldComponentAttributes.keySet()) { - String key = keyField; - String value = dynamicFieldComponentAttributes.get(key); - MatchType dynamicMatch = createDynamicMatch(key, value); - allOf.getMatch().add(dynamicMatch); - } - - AnyOfType anyOf = new AnyOfType(); - anyOf.getAllOf().add(allOfOne); - anyOf.getAllOf().add(allOf); - - TargetType target = new TargetType(); - target.getAnyOf().add(anyOf); - decisionPolicy.setTarget(target); - - Map dynamicFieldDecisionSettings = policyAdapter.getDynamicSettingsMap(); - if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){ - dynamicFieldDecisionSettings = new HashMap<>(); - } - - // settings are dynamic so check how many rows are added and add all - for (String keyField : dynamicFieldDecisionSettings.keySet()) { - String key = keyField; - String value = dynamicFieldDecisionSettings.get(key); - String dataType = getDataType(key); - VariableDefinitionType dynamicVariable = createDynamicVariable(key, value, dataType); - decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(dynamicVariable); - } - Map dynamicFieldTreatmentAttributes = policyAdapter.getRainydayMap(); - - if(policyAdapter.getRuleProvider().equals(RAINY_DAY)){ - for(String keyField : dynamicFieldTreatmentAttributes.keySet()) { - String errorcode = keyField; - String treatment = dynamicFieldTreatmentAttributes.get(errorcode); - createRainydayRule(decisionPolicy, errorcode, treatment, true); - } - } else { - createRule(decisionPolicy, true); - createRule(decisionPolicy, false); - } - - } - setPreparedToSave(true); - return true; - } - - public PolicyType getGuardPolicy(Map yamlParams, String ruleProvider) throws BuilderException{ - try { - ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard()); - MatchParameters matchParameters = new MatchParameters(yamlParams.get("actor"), yamlParams.get("recipe")); - matchParameters.setControlLoopName(yamlParams.get("clname")); - if(yamlParams.containsKey("targets")){ - String targetString = yamlParams.get("targets"); - List targets = null; - if(targetString!=null && !targetString.isEmpty()){ - if (targetString.contains(",")){ - targets = Arrays.asList(targetString.split(",")); - } - else{ - targets = new ArrayList<>(); - targets.add(targetString); - } - } - matchParameters.setTargets(targets); - } - GuardPolicy policy1 = new GuardPolicy((policyAdapter.getUuid()!=null? policyAdapter.getUuid(): UUID.randomUUID().toString()) ,yamlParams.get(POLICY_NAME), yamlParams.get(DESCRIPTION), matchParameters); - builder = builder.addGuardPolicy(policy1); - Map activeTimeRange = new HashMap<>(); - activeTimeRange.put("start", yamlParams.get("guardActiveStart")); - activeTimeRange.put("end", yamlParams.get("guardActiveEnd")); - String blackListString = yamlParams.get("blackList"); - List blackList = null; - if(blackListString!=null){ - if (blackListString.contains(",")){ - blackList = Arrays.asList(blackListString.split(",")); - } - else{ - blackList = new ArrayList<>(); - blackList.add(blackListString); - } - } - File templateFile; - Path xacmlTemplatePath; - ClassLoader classLoader = getClass().getClassLoader(); - Constraint cons = new Constraint(); - switch (ruleProvider){ - case GUARD_BL_YAML: - templateFile = new File(classLoader.getResource(XACML_BLGUARD_TEMPLATE).getFile()); - xacmlTemplatePath = templateFile.toPath(); - cons.setActive_time_range(activeTimeRange); - cons.setBlacklist(blackList); - break; - default: - templateFile = new File(classLoader.getResource(XACML_GUARD_TEMPLATE).getFile()); - xacmlTemplatePath = templateFile.toPath(); - Map timeWindow = new HashMap<>(); - if(!PolicyUtils.isInteger(yamlParams.get("timeWindow"))){ - throw new BuilderException("time window is not in Integer format."); - } - String timeUnits = yamlParams.get("timeUnits"); - if(timeUnits==null || !(timeUnits.equalsIgnoreCase("minute") || timeUnits.equalsIgnoreCase("hour") || timeUnits.equalsIgnoreCase("day") - || timeUnits.equalsIgnoreCase("week") || timeUnits.equalsIgnoreCase("month")||timeUnits.equalsIgnoreCase("year"))){ - throw new BuilderException("time Units is not in proper format."); - } - timeWindow.put("value", yamlParams.get("timeWindow")); - timeWindow.put("units", yamlParams.get("timeUnits")); - cons = new Constraint(Integer.parseInt(yamlParams.get("limit")),timeWindow,activeTimeRange); - break; - } - builder = builder.addLimitConstraint(policy1.getId(), cons); - // Build the specification - Results results = builder.buildSpecification(); - // YAML TO XACML - ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification()); - String xacmlTemplateContent; - try { - xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); - HashMap yamlSpecs = new HashMap<>(); - yamlSpecs.put(POLICY_NAME, yamlParams.get(POLICY_NAME)); - yamlSpecs.put(DESCRIPTION, yamlParams.get(DESCRIPTION)); - yamlSpecs.put(ECOMPNAME, yamlParams.get(ECOMPNAME)); - yamlSpecs.put("actor", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor()); - yamlSpecs.put("recipe", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe()); - yamlSpecs.put("clname", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName()); - if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()!=null){ - yamlSpecs.put("limit", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target().toString()); - } - if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()!=null){ - yamlSpecs.put("twValue", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("value")); - yamlSpecs.put("twUnits", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("units")); - } - yamlSpecs.put("guardActiveStart", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("start")); - yamlSpecs.put("guardActiveEnd", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("end")); - String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs, yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist(), yamlGuardObject.getGuards().getFirst().getMatch_parameters().getTargets()); - // Convert the Policy into Stream input to Policy Adapter. - Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8))); - return (PolicyType) policy; - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() , e); - } - } catch (BuilderException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() ,e); - throw e; - } - return null; - } - - private DecisionSettings findDecisionSettingsBySettingId(String settingId) { - DecisionSettings decisionSetting = null; - - EntityManager em = XACMLPapServlet.getEmf().createEntityManager(); - Query getDecisionSettings = em.createNamedQuery("DecisionSettings.findAll"); - List decisionSettingsList = getDecisionSettings.getResultList(); - - for (Object id : decisionSettingsList) { - decisionSetting = (DecisionSettings) id; - if (decisionSetting.getXacmlId().equals(settingId)) { - break; - } - } - return decisionSetting; - } - - private void createRule(PolicyType decisionPolicy, boolean permitRule) { - RuleType rule = new RuleType(); - - rule.setRuleId(policyAdapter.getRuleID()); - - if (permitRule) { - rule.setEffect(EffectType.PERMIT); - } else { - rule.setEffect(EffectType.DENY); - } - rule.setTarget(new TargetType()); - - // Create Target in Rule - AllOfType allOfInRule = new AllOfType(); - - // Creating match for ACCESS in rule target - MatchType accessMatch = new MatchType(); - AttributeValueType accessAttributeValue = new AttributeValueType(); - accessAttributeValue.setDataType(STRING_DATATYPE); - accessAttributeValue.getContent().add("DECIDE"); - accessMatch.setAttributeValue(accessAttributeValue); - AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); - URI accessURI = null; - try { - accessURI = new URI(ACTION_ID); - } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI"); - } - accessAttributeDesignator.setCategory(CATEGORY_ACTION); - accessAttributeDesignator.setDataType(STRING_DATATYPE); - accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); - accessMatch.setAttributeDesignator(accessAttributeDesignator); - accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels(); - dynamicFieldComboRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo(); - dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1(); - dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2(); - dropDownMap = createDropDownMap(); - - if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){ - // Values for AAF Provider are here for XML Creation. - ConditionType condition = new ConditionType(); - ApplyType decisionApply = new ApplyType(); - String selectedFunction = "boolean-equal"; - - AttributeValueType value1 = new AttributeValueType(); - value1.setDataType(BOOLEAN_DATATYPE); - value1.getContent().add("true"); - - AttributeDesignatorType value2 = new AttributeDesignatorType(); - value2.setAttributeId(AAFEngine.AAF_RESULT); - value2.setCategory(CATEGORY_RESOURCE); - value2.setDataType(BOOLEAN_DATATYPE); - value2.setMustBePresent(false); - - ApplyType innerDecisionApply = new ApplyType(); - innerDecisionApply.setFunctionId(FUNCTION_BOOLEAN_ONE_AND_ONLY); - innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(value2)); - - decisionApply.setFunctionId(dropDownMap.get(selectedFunction)); - decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(value1)); - decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply)); - condition.setExpression(new ObjectFactory().createApply(decisionApply)); - if (!permitRule) { - ApplyType notOuterApply = new ApplyType(); - notOuterApply.setFunctionId(FUNCTION_NOT); - notOuterApply.getExpression().add(condition.getExpression()); - condition.setExpression(new ObjectFactory().createApply(notOuterApply)); - } - rule.setCondition(condition); - allOfInRule.getMatch().add(accessMatch); - - AnyOfType anyOfInRule = new AnyOfType(); - anyOfInRule.getAllOf().add(allOfInRule); - - TargetType targetInRule = new TargetType(); - targetInRule.getAnyOf().add(anyOfInRule); - - rule.setTarget(targetInRule); - if(!permitRule){ - AdviceExpressionsType adviceExpressions = new AdviceExpressionsType(); - AdviceExpressionType adviceExpression = new AdviceExpressionType(); - adviceExpression.setAdviceId(AAFPROVIDER); - adviceExpression.setAppliesTo(EffectType.DENY); - AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType(); - assignment.setAttributeId("aaf.response"); - assignment.setCategory(CATEGORY_RESOURCE); - AttributeDesignatorType value = new AttributeDesignatorType(); - value.setAttributeId(AAFEngine.AAF_RESPONSE); - value.setCategory(CATEGORY_RESOURCE); - value.setDataType(STRING_DATATYPE); - value.setMustBePresent(false); - assignment.setExpression(new ObjectFactory().createAttributeDesignator(value)); - adviceExpression.getAttributeAssignmentExpression().add(assignment); - adviceExpressions.getAdviceExpression().add(adviceExpression); - rule.setAdviceExpressions(adviceExpressions); - } - decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); - policyAdapter.setPolicyData(decisionPolicy); - - }else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) { - boolean isCompound = false; - ConditionType condition = new ConditionType(); - int index = dynamicFieldOneRuleAlgorithms.size() - 1; - - for (String labelAttr : dynamicLabelRuleAlgorithms) { - // if the rule algorithm as a label means it is a compound - if (dynamicFieldOneRuleAlgorithms.get(index).equals(labelAttr)) { - ApplyType decisionApply = new ApplyType(); - - String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index); - String value1 = dynamicFieldOneRuleAlgorithms.get(index); - String value2 = dynamicFieldTwoRuleAlgorithms.get(index); - decisionApply.setFunctionId(dropDownMap.get(selectedFunction)); - decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1))); - decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2))); - condition.setExpression(new ObjectFactory().createApply(decisionApply)); - isCompound = true; - } - - // if rule algorithm not a compound - if (!isCompound) { - condition.setExpression(new ObjectFactory().createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index)))); - } - } - if (!permitRule) { - ApplyType notOuterApply = new ApplyType(); - notOuterApply.setFunctionId(FUNCTION_NOT); - notOuterApply.getExpression().add(condition.getExpression()); - condition.setExpression(new ObjectFactory().createApply(notOuterApply)); - } - rule.setCondition(condition); - allOfInRule.getMatch().add(accessMatch); - - AnyOfType anyOfInRule = new AnyOfType(); - anyOfInRule.getAllOf().add(allOfInRule); - - TargetType targetInRule = new TargetType(); - targetInRule.getAnyOf().add(anyOfInRule); - - rule.setTarget(targetInRule); - - decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); - policyAdapter.setPolicyData(decisionPolicy); - - } else { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."+ policyAdapter.getData().getClass().getCanonicalName()); - } - - } - - private void createRainydayRule(PolicyType decisionPolicy, String errorcode, String treatment, boolean permitRule) { - RuleType rule = new RuleType(); - - rule.setRuleId(UUID.randomUUID().toString()); - - if (permitRule) { - rule.setEffect(EffectType.PERMIT); - } else { - rule.setEffect(EffectType.DENY); - } - rule.setTarget(new TargetType()); - - // Create Target in Rule - AllOfType allOfInRule = new AllOfType(); - - // Creating match for DECIDE in rule target - MatchType accessMatch = new MatchType(); - AttributeValueType accessAttributeValue = new AttributeValueType(); - accessAttributeValue.setDataType(STRING_DATATYPE); - accessAttributeValue.getContent().add("DECIDE"); - accessMatch.setAttributeValue(accessAttributeValue); - AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); - URI accessURI = null; - try { - accessURI = new URI(ACTION_ID); - } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI"); - } - accessAttributeDesignator.setCategory(CATEGORY_ACTION); - accessAttributeDesignator.setDataType(STRING_DATATYPE); - accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); - accessMatch.setAttributeDesignator(accessAttributeDesignator); - accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - allOfInRule.getMatch().add(accessMatch); - - // Creating match for ErrorCode in rule target - MatchType errorcodeMatch = new MatchType(); - AttributeValueType errorcodeAttributeValue = new AttributeValueType(); - errorcodeAttributeValue.setDataType(STRING_DATATYPE); - errorcodeAttributeValue.getContent().add(errorcode); - errorcodeMatch.setAttributeValue(errorcodeAttributeValue); - AttributeDesignatorType errorcodeAttributeDesignator = new AttributeDesignatorType(); - errorcodeAttributeDesignator.setCategory(CATEGORY_RESOURCE); - errorcodeAttributeDesignator.setDataType(STRING_DATATYPE); - errorcodeAttributeDesignator.setAttributeId("ErrorCode"); - errorcodeMatch.setAttributeDesignator(errorcodeAttributeDesignator); - errorcodeMatch.setMatchId(FUNCTION_STRING_REGEXP_MATCH); - - allOfInRule.getMatch().add(errorcodeMatch); - - AnyOfType anyOfInRule = new AnyOfType(); - anyOfInRule.getAllOf().add(allOfInRule); - - TargetType targetInRule = new TargetType(); - targetInRule.getAnyOf().add(anyOfInRule); - - rule.setTarget(targetInRule); - - AdviceExpressionsType adviceExpressions = new AdviceExpressionsType(); - AdviceExpressionType adviceExpression = new AdviceExpressionType(); - adviceExpression.setAdviceId(RAINY_DAY); - adviceExpression.setAppliesTo(EffectType.PERMIT); - - AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType(); - assignment.setAttributeId("treatment"); - assignment.setCategory(CATEGORY_RESOURCE); - - AttributeValueType treatmentAttributeValue = new AttributeValueType(); - treatmentAttributeValue.setDataType(STRING_DATATYPE); - treatmentAttributeValue.getContent().add(treatment); - assignment.setExpression(new ObjectFactory().createAttributeValue(treatmentAttributeValue)); - - adviceExpression.getAttributeAssignmentExpression().add(assignment); - adviceExpressions.getAdviceExpression().add(adviceExpression); - rule.setAdviceExpressions(adviceExpressions); - decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); - policyAdapter.setPolicyData(decisionPolicy); - - } - - // if compound setting the inner apply here - protected ApplyType getInnerDecisionApply(String value1Label) { - ApplyType decisionApply = new ApplyType(); - int index = 0; - // check the index for the label. - for (String labelAttr : dynamicLabelRuleAlgorithms) { - if (labelAttr.equals(value1Label)) { - String value1 = dynamicFieldOneRuleAlgorithms.get(index); - populateDataTypeList(value1); - - // check if the row contains label again - for (String labelValue : dynamicLabelRuleAlgorithms) { - if (labelValue.equals(value1)) { - return getCompoundDecisionApply(index); - } - } - - // Getting the values from the form. - String functionKey = dynamicFieldComboRuleAlgorithms.get(index); - String value2 = dynamicFieldTwoRuleAlgorithms.get(index); - decisionApply.setFunctionId(dropDownMap.get(functionKey)); - // if two text field are rule attributes. - if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) { - ApplyType innerDecisionApply1 = new ApplyType(); - ApplyType innerDecisionApply2 = new ApplyType(); - AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType(); - AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType(); - //If selected function is Integer function set integer functionID - if(functionKey.toLowerCase().contains("integer")){ - innerDecisionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY ); - innerDecisionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY); - attributeDesignator1.setDataType(INTEGER_DATATYPE); - attributeDesignator2.setDataType(INTEGER_DATATYPE); - } else{ - //If selected function is not a Integer function set String functionID - innerDecisionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY); - innerDecisionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY); - attributeDesignator1.setDataType(STRING_DATATYPE); - attributeDesignator2.setDataType(STRING_DATATYPE); - } - attributeDesignator1.setCategory(CATEGORY_RESOURCE); - attributeDesignator2.setCategory(CATEGORY_RESOURCE); - //Here set actual field values - attributeDesignator1.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8)); - attributeDesignator2.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8)); - innerDecisionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator1)); - innerDecisionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator2)); - decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply1)); - decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply2)); - } else { - // if either of one text field is rule attribute. - if (!value1.startsWith("S_")) { - ApplyType innerDecisionApply = new ApplyType(); - AttributeDesignatorType attributeDesignator = new AttributeDesignatorType(); - AttributeValueType decisionConditionAttributeValue = new AttributeValueType(); - - if (functionKey.toLowerCase().contains("integer")) { - innerDecisionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY); - decisionConditionAttributeValue.setDataType(INTEGER_DATATYPE); - attributeDesignator.setDataType(INTEGER_DATATYPE); - } else { - innerDecisionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY); - decisionConditionAttributeValue.setDataType(STRING_DATATYPE); - attributeDesignator.setDataType(STRING_DATATYPE); - } - - String attributeId = null; - String attributeValue = null; - - // Find which textField has rule attribute and set it as - // attributeId and the other as attributeValue. - attributeId = value1; - attributeValue = value2; - - if (attributeId != null) { - attributeDesignator.setCategory(CATEGORY_RESOURCE); - attributeDesignator.setAttributeId(attributeId); - } - decisionConditionAttributeValue.getContent().add(attributeValue); - innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator)); - decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue)); - decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply)); - } else { - value1 = value1.substring(2, value1.length()); - VariableReferenceType variableReferenceType = new VariableReferenceType(); - variableReferenceType.setVariableId(value1); - - String dataType = dataTypeList.get(index); - - AttributeValueType decisionConditionAttributeValue = new AttributeValueType(); - decisionConditionAttributeValue.setDataType(dataType); - decisionConditionAttributeValue.getContent().add(value2); - decisionApply.getExpression().add(new ObjectFactory().createVariableReference(variableReferenceType)); - decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue)); - } - } - } - index++; - } - return decisionApply; - } - - // if the rule algorithm is multiple compound one setting the apply - protected ApplyType getCompoundDecisionApply(int index) { - ApplyType decisionApply = new ApplyType(); - String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index); - String value1 = dynamicFieldOneRuleAlgorithms.get(index); - String value2 = dynamicFieldTwoRuleAlgorithms.get(index); - decisionApply.setFunctionId(dropDownMap.get(selectedFunction)); - decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1))); - decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2))); - return decisionApply; - } - - private VariableDefinitionType createDynamicVariable(String key, String value, String dataType) { - VariableDefinitionType dynamicVariable = new VariableDefinitionType(); - AttributeValueType dynamicAttributeValue = new AttributeValueType(); - - dynamicAttributeValue.setDataType(dataType); - dynamicAttributeValue.getContent().add(value); - - dynamicVariable.setVariableId(key); - dynamicVariable.setExpression(new ObjectFactory().createAttributeValue(dynamicAttributeValue)); - - return dynamicVariable; - - } - - private void populateDataTypeList(String value1) { - String dataType = null; - if(value1.contains("S_")) { - value1 = value1.substring(2, value1.length()); - DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1.substring(2, value1.length())); - if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) { - dataType = STRING_DATATYPE; - } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) { - dataType = BOOLEAN_DATATYPE; - } else { - dataType = INTEGER_DATATYPE; - } - } else { - dataType = "OTHER"; - } - - dataTypeList.add(dataType); - } - - private Map createDropDownMap(){ - JPAUtils jpaUtils = null; - try { - jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf()); - } catch (Exception e) { - LOGGER.error("Exception Occured"+e); - } - Map dropDownOptions = new HashMap<>(); - if(jpaUtils!=null){ - Map> functionMap = jpaUtils.getFunctionDatatypeMap(); - for (Map.Entry> map: functionMap.entrySet()) { - for (FunctionDefinition functionDef : map.getValue()) { - dropDownOptions.put(functionDef.getShortname(),functionDef.getXacmlid()); - } - } - } - return dropDownOptions; - } - - private String getDataType(String key) { - - DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key); - String dataType = null; - - if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) { - dataType = STRING_DATATYPE; - } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) { - dataType = BOOLEAN_DATATYPE; - } else { - dataType = INTEGER_DATATYPE; - } - - return dataType; - } - - @Override - public Object getCorrectPolicyDataObject() { - return policyAdapter.getData(); - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/FirewallConfigPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/FirewallConfigPolicy.java deleted file mode 100644 index 9f780fd28..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/FirewallConfigPolicy.java +++ /dev/null @@ -1,1305 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.StringReader; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.json.Json; -import javax.json.JsonArray; -import javax.json.JsonObject; -import javax.json.JsonReader; -import javax.persistence.EntityManager; -import javax.persistence.Query; - -import org.apache.commons.io.FilenameUtils; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -import org.openecomp.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.jpa.ActionList; -import org.openecomp.policy.rest.jpa.AddressGroup; -import org.openecomp.policy.rest.jpa.GroupServiceList; -import org.openecomp.policy.rest.jpa.PolicyEntity; -import org.openecomp.policy.rest.jpa.PortList; -import org.openecomp.policy.rest.jpa.PrefixList; -import org.openecomp.policy.rest.jpa.ProtocolList; -import org.openecomp.policy.rest.jpa.ServiceList; -import org.openecomp.policy.rest.jpa.TermList; -import org.openecomp.policy.rest.jpa.UserInfo; - -import com.att.research.xacml.std.IdentifierImpl; -import com.fasterxml.jackson.databind.JsonNode; -import com.github.fge.jackson.JsonLoader; -import com.github.fge.jsonpatch.diff.JsonDiff; - -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.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -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; - -public class FirewallConfigPolicy extends Policy { - - private static final Logger LOGGER = FlexLogger.getLogger(FirewallConfigPolicy.class); - - public FirewallConfigPolicy() { - super(); - } - - public FirewallConfigPolicy(PolicyRestAdapter policyAdapter) { - this.policyAdapter = policyAdapter; - this.policyAdapter.setConfigType(policyAdapter.getConfigType()); - } - - // Saving the Configurations file at server location for config policy. - protected void saveConfigurations(String policyName, String jsonBody) { - String configurationName = policyName; - FileWriter fw = null; - try{ - if(configurationName.endsWith(".xml")){ - configurationName = configurationName.replace(".xml", ""); - } - fw = new FileWriter(CONFIG_HOME + File.separator + configurationName + ".json"); - BufferedWriter bw = new BufferedWriter(fw); - bw.write(jsonBody); - bw.close(); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Configuration is succesfully saved"); - } - } catch (IOException e) { - LOGGER.error("Exception Occured"+e); - }finally{ - try{ - if(fw != null){ - fw.close(); - } - }catch(Exception e){ - LOGGER.error("Exception Occured"+e); - } - } - } - - //Utility to read json data from the existing file to a string - static String readFile(String path, Charset encoding) throws IOException { - byte[] encoded = Files.readAllBytes(Paths.get(path)); - return new String(encoded, encoding); - } - - @Override - public Map savePolicies() throws Exception { - Map successMap = new HashMap<>(); - if(isPolicyExists()){ - successMap.put("EXISTS", "This Policy already exist on the PAP"); - return successMap; - } - if(!isPreparedToSave()){ - prepareToSave(); - } - - // Until here we prepared the data and here calling the method to create xml. - Path newPolicyPath = null; - newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - Boolean dbIsUpdated = false; - if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())){ - if (policyAdapter.isEditPolicy()) { - dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody()); - } else { - dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody()); - } - } else { - dbIsUpdated = true; - } - - if(dbIsUpdated) { - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); - } else { - PolicyLogger.error("Failed to Update the Database Dictionary Tables."); - - //remove the new json file - String jsonBody = policyAdapter.getPrevJsonBody(); - if (jsonBody!=null){ - saveConfigurations(policyName, jsonBody); - } else { - saveConfigurations(policyName, ""); - } - successMap.put("fwdberror", "DB UPDATE"); - } - - return successMap; - } - - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things - @Override - public boolean prepareToSave() throws Exception{ - - if(isPreparedToSave()){ - //we have already done this - return true; - } - - int version = 0; - String policyID = policyAdapter.getPolicyID(); - version = policyAdapter.getHighestVersion(); - - // Create the Instance for pojo, PolicyType object is used in marshaling. - if ("Config".equals(policyAdapter.getPolicyType())) { - PolicyType policyConfig = new PolicyType(); - - policyConfig.setVersion(Integer.toString(version)); - policyConfig.setPolicyId(policyID); - policyConfig.setTarget(new TargetType()); - policyAdapter.setData(policyConfig); - } - policyName = policyAdapter.getNewFileName(); - - //String oldPolicyName = policyName.replace(".xml", ""); - String scope = policyName.substring(0, policyName.indexOf('.')); - String dbPolicyName = policyName.substring(policyName.indexOf('.')+1).replace(".xml", ""); - - int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.')+1)); - dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.')+1); - if(oldversion > 1){ - oldversion = oldversion - 1; - dbPolicyName = dbPolicyName + oldversion + ".xml"; - } - EntityManager em = XACMLPapServlet.getEmf().createEntityManager(); - Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName"); - createPolicyQuery.setParameter("scope", scope); - createPolicyQuery.setParameter("policyName", dbPolicyName); - List createPolicyQueryList = createPolicyQuery.getResultList(); - if(!createPolicyQueryList.isEmpty()){ - PolicyEntity entitydata = (PolicyEntity) createPolicyQueryList.get(0); - policyAdapter.setPrevJsonBody(entitydata.getConfigurationData().getConfigBody()); - } - em.close(); - if (policyAdapter.getData() != null) { - String jsonBody = policyAdapter.getJsonBody(); - saveConfigurations(policyName, jsonBody); - - // Make sure the filename ends with an extension - if (!policyName.endsWith(".xml")) { - policyName = policyName + ".xml"; - } - - PolicyType configPolicy = (PolicyType) policyAdapter.getData(); - - configPolicy.setDescription(policyAdapter.getPolicyDescription()); - - configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); - - AllOfType allOfOne = new AllOfType(); - String fileName = policyAdapter.getNewFileName(); - String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length()); - } - allOfOne.getMatch().add(createMatch("PolicyName", name)); - AllOfType allOf = new AllOfType(); - - // Match for ConfigName - allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName())); - // Match for riskType - allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); - // Match for riskLevel - allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); - // Match for riskguard - allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); - // Match for ttlDate - allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); - AnyOfType anyOf = new AnyOfType(); - anyOf.getAllOf().add(allOfOne); - anyOf.getAllOf().add(allOf); - - TargetType target = new TargetType(); - target.getAnyOf().add(anyOf); - - // Adding the target to the policy element - configPolicy.setTarget((TargetType) target); - - RuleType rule = new RuleType(); - rule.setRuleId(policyAdapter.getRuleID()); - rule.setEffect(EffectType.PERMIT); - - // Create Target in Rule - AllOfType allOfInRule = new AllOfType(); - - // Creating match for ACCESS in rule target - MatchType accessMatch = new MatchType(); - AttributeValueType accessAttributeValue = new AttributeValueType(); - accessAttributeValue.setDataType(STRING_DATATYPE); - accessAttributeValue.getContent().add("ACCESS"); - accessMatch.setAttributeValue(accessAttributeValue); - AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); - URI accessURI = null; - try { - accessURI = new URI(ACTION_ID); - } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating ACCESS URI"); - } - accessAttributeDesignator.setCategory(CATEGORY_ACTION); - accessAttributeDesignator.setDataType(STRING_DATATYPE); - accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); - accessMatch.setAttributeDesignator(accessAttributeDesignator); - accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - // Creating Config Match in rule Target - MatchType configMatch = new MatchType(); - AttributeValueType configAttributeValue = new AttributeValueType(); - configAttributeValue.setDataType(STRING_DATATYPE); - - configAttributeValue.getContent().add("Config"); - - configMatch.setAttributeValue(configAttributeValue); - AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType(); - URI configURI = null; - try { - configURI = new URI(RESOURCE_ID); - } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI"); - } - - configAttributeDesignator.setCategory(CATEGORY_RESOURCE); - configAttributeDesignator.setDataType(STRING_DATATYPE); - configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue()); - configMatch.setAttributeDesignator(configAttributeDesignator); - configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - allOfInRule.getMatch().add(accessMatch); - allOfInRule.getMatch().add(configMatch); - - AnyOfType anyOfInRule = new AnyOfType(); - anyOfInRule.getAllOf().add(allOfInRule); - - TargetType targetInRule = new TargetType(); - targetInRule.getAnyOf().add(anyOfInRule); - - rule.setTarget(targetInRule); - rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); - - configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); - policyAdapter.setPolicyData(configPolicy); - - } else { - PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); - } - setPreparedToSave(true); - return true; - } - - // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { - - //Firewall Config ID Assignment - AdviceExpressionsType advices = new AdviceExpressionsType(); - AdviceExpressionType advice = new AdviceExpressionType(); - advice.setAdviceId("firewallConfigID"); - advice.setAppliesTo(EffectType.PERMIT); - // For Configuration - AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); - assignment1.setAttributeId("type"); - assignment1.setCategory(CATEGORY_RESOURCE); - assignment1.setIssuer(""); - AttributeValueType configNameAttributeValue = new AttributeValueType(); - configNameAttributeValue.setDataType(STRING_DATATYPE); - configNameAttributeValue.getContent().add("Configuration"); - assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); - advice.getAttributeAssignmentExpression().add(assignment1); - - // For Config file Url if configurations are provided. - //URL ID Assignment - AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); - assignment2.setAttributeId("URLID"); - assignment2.setCategory(CATEGORY_RESOURCE); - assignment2.setIssuer(""); - AttributeValueType AttributeValue = new AttributeValueType(); - AttributeValue.setDataType(URI_DATATYPE); - if (policyName.endsWith(".xml")) { - policyName = policyName.substring(0, policyName.lastIndexOf(".xml")); - } - String content = CONFIG_URL + "/Config/" + policyName + ".json"; - - AttributeValue.getContent().add(content); - assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); - advice.getAttributeAssignmentExpression().add(assignment2); - - //Policy Name Assignment - AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); - assignment3.setAttributeId("PolicyName"); - assignment3.setCategory(CATEGORY_RESOURCE); - assignment3.setIssuer(""); - AttributeValueType attributeValue3 = new AttributeValueType(); - attributeValue3.setDataType(STRING_DATATYPE); - fileName = FilenameUtils.removeExtension(fileName); - fileName = fileName + ".xml"; - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); - } - attributeValue3.getContent().add(name); - assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); - advice.getAttributeAssignmentExpression().add(assignment3); - - //Version Number Assignment - AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); - assignment4.setAttributeId("VersionNumber"); - assignment4.setCategory(CATEGORY_RESOURCE); - assignment4.setIssuer(""); - AttributeValueType configNameAttributeValue4 = new AttributeValueType(); - configNameAttributeValue4.setDataType(STRING_DATATYPE); - configNameAttributeValue4.getContent().add(Integer.toString(version)); - assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); - advice.getAttributeAssignmentExpression().add(assignment4); - - //Ecomp Name Assignment - AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); - assignment5.setAttributeId("matching:" + ECOMPID); - assignment5.setCategory(CATEGORY_RESOURCE); - assignment5.setIssuer(""); - AttributeValueType configNameAttributeValue5 = new AttributeValueType(); - configNameAttributeValue5.setDataType(STRING_DATATYPE); - assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); - advice.getAttributeAssignmentExpression().add(assignment5); - - //Config Name Assignment - AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); - assignment6.setAttributeId("matching:" + CONFIGID); - assignment6.setCategory(CATEGORY_RESOURCE); - assignment6.setIssuer(""); - AttributeValueType configNameAttributeValue6 = new AttributeValueType(); - configNameAttributeValue6.setDataType(STRING_DATATYPE); - configNameAttributeValue6.getContent().add(policyAdapter.getConfigName()); - assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); - advice.getAttributeAssignmentExpression().add(assignment6); - - //Risk Attributes - AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); - assignment7.setAttributeId("RiskType"); - assignment7.setCategory(CATEGORY_RESOURCE); - assignment7.setIssuer(""); - - AttributeValueType configNameAttributeValue7 = new AttributeValueType(); - configNameAttributeValue7.setDataType(STRING_DATATYPE); - configNameAttributeValue7.getContent().add(policyAdapter.getRiskType()); - assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); - - advice.getAttributeAssignmentExpression().add(assignment7); - - AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); - assignment8.setAttributeId("RiskLevel"); - assignment8.setCategory(CATEGORY_RESOURCE); - assignment8.setIssuer(""); - - AttributeValueType configNameAttributeValue8 = new AttributeValueType(); - configNameAttributeValue8.setDataType(STRING_DATATYPE); - configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel()); - assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8)); - - advice.getAttributeAssignmentExpression().add(assignment8); - - AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); - assignment9.setAttributeId("guard"); - assignment9.setCategory(CATEGORY_RESOURCE); - assignment9.setIssuer(""); - - AttributeValueType configNameAttributeValue9 = new AttributeValueType(); - configNameAttributeValue9.setDataType(STRING_DATATYPE); - configNameAttributeValue9.getContent().add(policyAdapter.getGuard()); - assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); - - advice.getAttributeAssignmentExpression().add(assignment9); - - AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); - assignment10.setAttributeId("TTLDate"); - assignment10.setCategory(CATEGORY_RESOURCE); - assignment10.setIssuer(""); - - AttributeValueType configNameAttributeValue10 = new AttributeValueType(); - configNameAttributeValue10.setDataType(STRING_DATATYPE); - configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate()); - assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10)); - - advice.getAttributeAssignmentExpression().add(assignment10); - advices.getAdviceExpression().add(advice); - return advices; - } - - - private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException { - CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - JsonObject json = null; - if (jsonBody != null) { - - //Read jsonBody to JsonObject - json = stringToJson(jsonBody); - - JsonArray firewallRules = null; - JsonArray serviceGroup = null; - JsonArray addressGroup = null; - //insert data into tables - try { - firewallRules = json.getJsonArray("firewallRuleList"); - serviceGroup = json.getJsonArray("serviceGroups"); - addressGroup = json.getJsonArray("addressGroups"); - /* - * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables - */ - if (firewallRules != null) { - for(int i = 0;i result = dbConnection.getDataById(TermList.class, "termName", ruleName); - if(result != null && !result.isEmpty()){ - TermList termEntry = (TermList) result.get(0); - dbConnection.delete(termEntry); - } - - //getting fromZone Array field from the firewallRulesList - JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones"); - String fromZoneString = null; - - for (int fromZoneIndex = 0;fromZoneIndex p1.id AND protocollist.protocolname = p1.protocolname;"; - dbConnection.updateQuery(protoDelete); - - //PortList Table - String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 " - + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; "; - dbConnection.updateQuery(portListDelete); - - //PrefixList Table - String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 " - + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND " - + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; "; - dbConnection.updateQuery(prefixListDelete); - - //GroupServiceList - String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 " - + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND " - + "groupservicelist.serviceList = g1.serviceList; "; - dbConnection.updateQuery(groupServiceDelete); - }catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values"); - return false; - } - return true; - - } else { - return false; - } - - } - - - private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) { - CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - JsonObject oldJson = null; - JsonObject newJson = null; - - if (jsonBody != null || prevJsonBody != null) { - - oldJson = stringToJson(prevJsonBody); - newJson = stringToJson(jsonBody); - - //if no changes to the json then return true - if (oldJson != null && oldJson.equals(newJson)) { - return true; - } - - JsonArray firewallRules = null; - JsonArray serviceGroup = null; - JsonArray addressGroup = null; - - firewallRules = newJson.getJsonArray("firewallRuleList"); - serviceGroup = newJson.getJsonArray("serviceGroups"); - addressGroup = newJson.getJsonArray("addressGroups"); - - //insert data into tables - try { - JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody); - - for (int i = 0; i result = dbConnection.getDataById(TermList.class, "termName", ruleName); - if(result != null && !result.isEmpty()){ - TermList termEntry = (TermList) result.get(0); - dbConnection.delete(termEntry); - } - - //getting fromZone Array field from the firewallRulesList - JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones"); - String fromZoneString = null; - - for (int fromZoneIndex = 0; fromZoneIndex actionResult = dbConnection.getDataById(ActionList.class, "actionName", action); - if(actionResult == null || actionResult.isEmpty()){ - ActionList actionEntry = new ActionList(); - actionEntry.setActionName(action); - actionEntry.setDescription(action); - dbConnection.save(actionEntry); - } - } - } - - if (path.contains("serviceGroups")) { - /* - * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables - */ - for(int si = 0; si < serviceGroup.size(); si++) { - /* - * Populate ArrayLists with values from the JSON - */ - //create the JSON object from the JSON Array for each iteration through the for loop - JsonObject svcGroupListobj = serviceGroup.getJsonObject(si); - - String groupName = svcGroupListobj.get("name").toString().replace('"', '\''); - - String description = null; - if (svcGroupListobj.containsKey("description")){ - description = svcGroupListobj.get("description").toString().replace('"', '\''); - } - - JsonArray membersArray = svcGroupListobj.getJsonArray("members"); - - Boolean isServiceGroup = false; - if (membersArray!=null){ - String membersType = membersArray.getJsonObject(0).get("type").toString(); - if (membersType.contains("REFERENCE")) { - isServiceGroup = true; - } - } - - //Insert values into GROUPSERVICELIST table if name begins with Group - if (isServiceGroup) { - List result = dbConnection.getDataById(GroupServiceList.class, "name", groupName); - if(result != null && !result.isEmpty()){ - GroupServiceList groupEntry = (GroupServiceList) result.get(0); - dbConnection.delete(groupEntry); - } - - String name = null; - for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) { - JsonObject membersObj = membersArray.getJsonObject(membersIndex); - String type = membersObj.get("type").toString().replace("\"", ""); - - String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){ - value = membersObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ - value = null; - } else { - value = membersObj.get("value").toString(); - } - - if(value != null){ - value = value.replace("\"", ""); - } - - if (name != null) { - name = name.concat(",").concat(value); - } else { - name = value; - } - } - String nameInsert = "'"+name+"'"; - GroupServiceList groupServiceEntry = new GroupServiceList(); - groupServiceEntry.setGroupName(groupName); - groupServiceEntry.setServiceList(nameInsert); - dbConnection.save(groupServiceEntry); - } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table - String type = svcGroupListobj.get("type").toString().replace('"', '\''); - String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\''); - String ports = svcGroupListobj.get("ports").toString().replace('"', '\''); - - List result = dbConnection.getDataById(ServiceList.class, "name", groupName); - if(result != null && !result.isEmpty()){ - ServiceList serviceEntry = (ServiceList) result.get(0); - dbConnection.delete(serviceEntry); - } - - ServiceList serviceListEntry = new ServiceList(); - serviceListEntry.setServiceName(groupName); - serviceListEntry.setServiceDescription(description); - serviceListEntry.setServiceType(type); - serviceListEntry.setServiceTransProtocol(transportProtocol); - serviceListEntry.setServiceAppProtocol("null"); - serviceListEntry.setServicePorts(ports); - dbConnection.save(serviceListEntry); - - List protocolResult = dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol); - if(protocolResult == null || protocolResult.isEmpty()){ - ProtocolList protocolEntry = new ProtocolList(); - protocolEntry.setProtocolName(transportProtocol); - protocolEntry.setDescription(transportProtocol); - dbConnection.save(protocolEntry); - } - - List portResult = dbConnection.getDataById(PortList.class, "portName", ports); - if(portResult == null || portResult.isEmpty()){ - PortList portEntry = new PortList(); - portEntry.setPortName(ports); - portEntry.setDescription(ports); - dbConnection.save(portEntry); - } - } - } - } - - if (path.contains("addressGroups")) { - /* - * Inserting addressGroup data into the ADDRESSGROUP table - */ - for(int ai=0; ai < addressGroup.size() ; ai++) { - - /* - * Populate ArrayLists with values from the JSON - */ - //create the JSON object from the JSON Array for each iteration through the for loop - JsonObject addressGroupObj = addressGroup.getJsonObject(ai); - - //create JSON array for members - JsonArray membersArray = addressGroupObj.getJsonArray("members"); - String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\''); - - String description = null; - if (addressGroupObj.containsKey("description")){ - description = addressGroupObj.get("description").toString().replace('"', '\''); - } - - String prefixIP = null; - String type = null; - for (int membersIndex=0; membersIndex < membersArray.size(); membersIndex++) { - JsonObject membersObj = membersArray.getJsonObject(membersIndex); - type = membersObj.get("type").toString().replace("\"", ""); - - String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){ - value = membersObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ - value = null; - } else { - value = membersObj.get("value").toString(); - } - - if(value != null){ - value = value.replace("\"", ""); - } - - if (prefixIP != null) { - prefixIP = prefixIP.concat(",").concat(value); - } else { - prefixIP = value; - } - } - - String prefixList = "'"+prefixIP+"'"; - Boolean isAddressGroup = type.contains("REFERENCE"); - - if (isAddressGroup) { - List result = dbConnection.getDataById(AddressGroup.class, "name", addressGroupName); - if(result != null && !result.isEmpty()){ - AddressGroup addressGroupEntry = (AddressGroup) result.get(0); - dbConnection.delete(addressGroupEntry); - } - AddressGroup newAddressGroup = new AddressGroup(); - newAddressGroup.setGroupName(addressGroupName); - newAddressGroup.setDescription(description); - newAddressGroup.setServiceList(prefixList); - dbConnection.save(newAddressGroup); - } else { - List result = dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName); - if(result != null && !result.isEmpty()){ - PrefixList prefixListEntry = (PrefixList) result.get(0); - dbConnection.delete(prefixListEntry); - } - PrefixList newPrefixList = new PrefixList(); - newPrefixList.setPrefixListName(addressGroupName); - newPrefixList.setDescription(description); - newPrefixList.setPrefixListValue(prefixList); - dbConnection.save(newPrefixList); - } - } - } - } - - /* - * Remove duplicate values from 'lookup' dictionary tables - */ - //ProtocolList Table - String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 " - + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;"; - dbConnection.updateQuery(protoDelete); - - //PortList Table - String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 " - + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; "; - dbConnection.updateQuery(portListDelete); - - //PrefixList Table - String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 " - + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND " - + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; "; - dbConnection.updateQuery(prefixListDelete); - - //GroupServiceList - String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 " - + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND " - + "groupservicelist.serviceList = g1.serviceList; "; - dbConnection.updateQuery(groupServiceDelete); - }catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries"); - return false; - } - return true; - } else { - return false; - } - - } - - private JsonObject stringToJson(String jsonString) { - JsonObject json = null; - if (jsonString != null) { - //Read jsonBody to JsonObject - StringReader in = null; - in = new StringReader(jsonString); - - JsonReader jsonReader = Json.createReader(in); - json = jsonReader.readObject(); - jsonReader.close(); - } - return json; - } - - private JsonNode createPatch(String json, String oldJson) { - JsonNode oldJason = null; - JsonNode updatedJason = null; - - try { - oldJason = JsonLoader.fromString(oldJson); - updatedJason = JsonLoader.fromString(json); - } catch (IOException e) { - LOGGER.error("Exception Occured"+e); - } - return JsonDiff.asJson(oldJason, updatedJason); - } - - @Override - public Object getCorrectPolicyDataObject() { - return policyAdapter.getPolicyData(); - } - -} \ No newline at end of file diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java deleted file mode 100644 index 5938faa66..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java +++ /dev/null @@ -1,555 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - -import java.io.File; -import java.io.PrintWriter; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang.StringUtils; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.jpa.MicroServiceModels; - -import com.att.research.xacml.std.IdentifierImpl; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Splitter; - -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.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -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; - -public class MicroServiceConfigPolicy extends Policy { - - private static final Logger LOGGER = FlexLogger.getLogger(MicroServiceConfigPolicy.class); - - private static Map mapAttribute = new HashMap<>(); - private static Map matchMap = new HashMap<>(); - - public MicroServiceConfigPolicy() { - super(); - } - - public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter){ - this.policyAdapter = policyAdapter; - } - - //save configuration of the policy based on the policyname - private void saveConfigurations(String policyName, String jsonBody) { - try { - if(policyName.endsWith(".xml")){ - policyName = policyName.replace(".xml", ""); - } - PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json"); - out.println(jsonBody); - out.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured While writing Configuration data"+e); - } - } - - - @Override - public Map savePolicies() throws Exception { - - Map successMap = new HashMap<>(); - if(isPolicyExists()){ - successMap.put("EXISTS", "This Policy already exist on the PAP"); - return successMap; - } - - if(!isPreparedToSave()){ - //Prep and configure the policy for saving - prepareToSave(); - } - - // Until here we prepared the data and here calling the method to create xml. - Path newPolicyPath = null; - newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); - - return successMap; - } - - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things - @Override - public boolean prepareToSave() throws Exception{ - - if(isPreparedToSave()){ - //we have already done this - return true; - } - - int version = 0; - String policyID = policyAdapter.getPolicyID(); - version = policyAdapter.getHighestVersion(); - - // Create the Instance for pojo, PolicyType object is used in marshalling. - if (policyAdapter.getPolicyType().equals("Config")) { - PolicyType policyConfig = new PolicyType(); - - policyConfig.setVersion(Integer.toString(version)); - policyConfig.setPolicyId(policyID); - policyConfig.setTarget(new TargetType()); - policyAdapter.setData(policyConfig); - } - policyName = policyAdapter.getNewFileName(); - if (policyAdapter.getData() != null) { - // Save the Configurations file with the policy name with extention based on selection. - String jsonBody = policyAdapter.getJsonBody(); - saveConfigurations(policyName, jsonBody); - - // Make sure the filename ends with an extension - if (policyName.endsWith(".xml") == false) { - policyName = policyName + ".xml"; - } - - - PolicyType configPolicy = (PolicyType) policyAdapter.getData(); - - configPolicy.setDescription(policyAdapter.getPolicyDescription()); - - configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); - - AllOfType allOfOne = new AllOfType(); - String fileName = policyAdapter.getNewFileName(); - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); - } - - //setup values for pulling out matching attributes - ObjectMapper mapper = new ObjectMapper(); - JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody()); - String matching = null; - - if (policyAdapter.getTtlDate()==null){ - policyAdapter.setTtlDate("NA"); - } - if (policyAdapter.getServiceType().contains("-v")){ - matching = getValueFromDictionary(policyAdapter.getServiceType()); - } else { - String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""}); - matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion); - } - - if (matching != null && !matching.isEmpty()){ - matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching); - if(policyAdapter.getJsonBody() != null){ - pullMatchValue(rootNode); - } - } - - // Match for policyName - allOfOne.getMatch().add(createMatch("PolicyName", name)); - - AllOfType allOf = new AllOfType(); - - // Adding the matches to AllOfType element Match for Ecomp - allOf.getMatch().add(createMatch("ECOMPName", policyAdapter.getEcompName())); - if (matchMap==null || matchMap.isEmpty()){ - // Match for ConfigName - allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName())); - // Match for Service - allOf.getMatch().add(createDynamicMatch("service", policyAdapter.getServiceType())); - // Match for uuid - allOf.getMatch().add(createDynamicMatch("uuid", policyAdapter.getUuid())); - // Match for location - allOf.getMatch().add(createDynamicMatch("location", policyAdapter.getLocation())); - }else { - for (Entry matchValue : matchMap.entrySet()){ - String value = matchValue.getValue(); - String key = matchValue.getKey().trim(); - if (value.contains("matching-true")){ - if (mapAttribute.containsKey(key)){ - allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key))); - } - } - } - } - // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); - // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); - // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); - // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); - - AnyOfType anyOf = new AnyOfType(); - anyOf.getAllOf().add(allOfOne); - anyOf.getAllOf().add(allOf); - - TargetType target = new TargetType(); - ((TargetType) target).getAnyOf().add(anyOf); - - // Adding the target to the policy element - configPolicy.setTarget((TargetType) target); - - RuleType rule = new RuleType(); - rule.setRuleId(policyAdapter.getRuleID()); - - rule.setEffect(EffectType.PERMIT); - - // Create Target in Rule - AllOfType allOfInRule = new AllOfType(); - - // Creating match for ACCESS in rule target - MatchType accessMatch = new MatchType(); - AttributeValueType accessAttributeValue = new AttributeValueType(); - accessAttributeValue.setDataType(STRING_DATATYPE); - accessAttributeValue.getContent().add("ACCESS"); - accessMatch.setAttributeValue(accessAttributeValue); - AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); - URI accessURI = null; - try { - accessURI = new URI(ACTION_ID); - } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating ACCESS URI"); - } - accessAttributeDesignator.setCategory(CATEGORY_ACTION); - accessAttributeDesignator.setDataType(STRING_DATATYPE); - accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); - accessMatch.setAttributeDesignator(accessAttributeDesignator); - accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - // Creating Config Match in rule Target - MatchType configMatch = new MatchType(); - AttributeValueType configAttributeValue = new AttributeValueType(); - configAttributeValue.setDataType(STRING_DATATYPE); - configAttributeValue.getContent().add("Config"); - configMatch.setAttributeValue(configAttributeValue); - AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType(); - URI configURI = null; - try { - configURI = new URI(RESOURCE_ID); - } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating Config URI"); - } - configAttributeDesignator.setCategory(CATEGORY_RESOURCE); - configAttributeDesignator.setDataType(STRING_DATATYPE); - configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue()); - configMatch.setAttributeDesignator(configAttributeDesignator); - configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); - - allOfInRule.getMatch().add(accessMatch); - allOfInRule.getMatch().add(configMatch); - - AnyOfType anyOfInRule = new AnyOfType(); - anyOfInRule.getAllOf().add(allOfInRule); - - TargetType targetInRule = new TargetType(); - targetInRule.getAnyOf().add(anyOfInRule); - - rule.setTarget(targetInRule); - rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); - - configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); - policyAdapter.setPolicyData(configPolicy); - - } else { - PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); - } - setPreparedToSave(true); - return true; - } - - private void pullMatchValue(JsonNode rootNode) { - Iterator> fieldsIterator = rootNode.fields(); - String newValue = null; - while (fieldsIterator.hasNext()) { - Map.Entry field = fieldsIterator.next(); - final String key = field.getKey(); - final JsonNode value = field.getValue(); - if (value.isContainerNode() && !value.isArray()) { - pullMatchValue(value); // RECURSIVE CALL - } else { - newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""}); - mapAttribute.put(key, newValue); - } - } - - } - - private String getValueFromDictionary(String service){ - String ruleTemplate=null; - String modelName = service.split("-v")[0]; - String modelVersion = service.split("-v")[1]; - - CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - List result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+modelVersion); - if(result != null && !result.isEmpty()){ - MicroServiceModels model = (MicroServiceModels) result.get(0); - ruleTemplate = model.getAnnotation(); - } - return ruleTemplate; - } - - // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { - AdviceExpressionsType advices = new AdviceExpressionsType(); - AdviceExpressionType advice = new AdviceExpressionType(); - advice.setAdviceId("MSID"); - advice.setAppliesTo(EffectType.PERMIT); - // For Configuration - AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); - assignment1.setAttributeId("type"); - assignment1.setCategory(CATEGORY_RESOURCE); - assignment1.setIssuer(""); - - AttributeValueType configNameAttributeValue = new AttributeValueType(); - configNameAttributeValue.setDataType(STRING_DATATYPE); - configNameAttributeValue.getContent().add("Configuration"); - assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); - - advice.getAttributeAssignmentExpression().add(assignment1); - // For Config file Url if configurations are provided. - AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); - assignment2.setAttributeId("URLID"); - assignment2.setCategory(CATEGORY_RESOURCE); - assignment2.setIssuer(""); - - AttributeValueType AttributeValue = new AttributeValueType(); - AttributeValue.setDataType(URI_DATATYPE); - String configName; - if(policyName.endsWith(".xml")){ - configName = policyName.replace(".xml", ""); - }else{ - configName = policyName; - } - String content = CONFIG_URL +"/Config/" + configName + ".json"; - AttributeValue.getContent().add(content); - assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); - - advice.getAttributeAssignmentExpression().add(assignment2); - AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); - assignment3.setAttributeId("PolicyName"); - assignment3.setCategory(CATEGORY_RESOURCE); - assignment3.setIssuer(""); - - AttributeValueType attributeValue3 = new AttributeValueType(); - attributeValue3.setDataType(STRING_DATATYPE); - fileName = FilenameUtils.removeExtension(fileName); - fileName = fileName + ".xml"; - String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); - if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); - } - attributeValue3.getContent().add(name); - assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); - advice.getAttributeAssignmentExpression().add(assignment3); - - AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); - assignment4.setAttributeId("VersionNumber"); - assignment4.setCategory(CATEGORY_RESOURCE); - assignment4.setIssuer(""); - - AttributeValueType configNameAttributeValue4 = new AttributeValueType(); - configNameAttributeValue4.setDataType(STRING_DATATYPE); - configNameAttributeValue4.getContent().add(Integer.toString(version)); - assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); - - advice.getAttributeAssignmentExpression().add(assignment4); - - AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); - assignment5.setAttributeId("matching:" + ECOMPID); - assignment5.setCategory(CATEGORY_RESOURCE); - assignment5.setIssuer(""); - - AttributeValueType configNameAttributeValue5 = new AttributeValueType(); - configNameAttributeValue5.setDataType(STRING_DATATYPE); - configNameAttributeValue5.getContent().add(policyAdapter.getEcompName()); - assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); - - advice.getAttributeAssignmentExpression().add(assignment5); - - AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); - assignment7.setAttributeId("matching:service"); - assignment7.setCategory(CATEGORY_RESOURCE); - assignment7.setIssuer(""); - - AttributeValueType configNameAttributeValue7 = new AttributeValueType(); - configNameAttributeValue7.setDataType(STRING_DATATYPE); - configNameAttributeValue7.getContent().add(policyAdapter.getServiceType()); - assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); - - advice.getAttributeAssignmentExpression().add(assignment7); - - if (matchMap==null || matchMap.isEmpty()){ - AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); - assignment6.setAttributeId("matching:" + CONFIGID); - assignment6.setCategory(CATEGORY_RESOURCE); - assignment6.setIssuer(""); - - AttributeValueType configNameAttributeValue6 = new AttributeValueType(); - configNameAttributeValue6.setDataType(STRING_DATATYPE); - configNameAttributeValue6.getContent().add(policyAdapter.getConfigName()); - assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); - - advice.getAttributeAssignmentExpression().add(assignment6); - - - AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); - assignment8.setAttributeId("matching:uuid"); - assignment8.setCategory(CATEGORY_RESOURCE); - assignment8.setIssuer(""); - - AttributeValueType configNameAttributeValue8 = new AttributeValueType(); - configNameAttributeValue8.setDataType(STRING_DATATYPE); - configNameAttributeValue8.getContent().add(policyAdapter.getUuid()); - assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8)); - - advice.getAttributeAssignmentExpression().add(assignment8); - - AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); - assignment9.setAttributeId("matching:Location"); - assignment9.setCategory(CATEGORY_RESOURCE); - assignment9.setIssuer(""); - - AttributeValueType configNameAttributeValue9 = new AttributeValueType(); - configNameAttributeValue9.setDataType(STRING_DATATYPE); - configNameAttributeValue9.getContent().add(policyAdapter.getLocation()); - assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); - - advice.getAttributeAssignmentExpression().add(assignment9); - } else { - for (Entry matchValue : matchMap.entrySet()){ - String value = matchValue.getValue(); - String key = matchValue.getKey().trim(); - if (value.contains("matching-true")){ - if (mapAttribute.containsKey(key)){ - AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); - assignment9.setAttributeId("matching:" + key); - assignment9.setCategory(CATEGORY_RESOURCE); - assignment9.setIssuer(""); - - AttributeValueType configNameAttributeValue9 = new AttributeValueType(); - configNameAttributeValue9.setDataType(STRING_DATATYPE); - configNameAttributeValue9.getContent().add(mapAttribute.get(key)); - assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); - - advice.getAttributeAssignmentExpression().add(assignment9); - - } - } - } - } - - AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); - assignment10.setAttributeId("Priority"); - assignment10.setCategory(CATEGORY_RESOURCE); - assignment10.setIssuer(""); - - AttributeValueType configNameAttributeValue10 = new AttributeValueType(); - configNameAttributeValue10.setDataType(STRING_DATATYPE); - configNameAttributeValue10.getContent().add(policyAdapter.getPriority()); - assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10)); - - advice.getAttributeAssignmentExpression().add(assignment10); - - //Risk Attributes - AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType(); - assignment11.setAttributeId("RiskType"); - assignment11.setCategory(CATEGORY_RESOURCE); - assignment11.setIssuer(""); - - AttributeValueType configNameAttributeValue11 = new AttributeValueType(); - configNameAttributeValue11.setDataType(STRING_DATATYPE); - configNameAttributeValue11.getContent().add(policyAdapter.getRiskType()); - assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11)); - - advice.getAttributeAssignmentExpression().add(assignment11); - - AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType(); - assignment12.setAttributeId("RiskLevel"); - assignment12.setCategory(CATEGORY_RESOURCE); - assignment12.setIssuer(""); - - AttributeValueType configNameAttributeValue12 = new AttributeValueType(); - configNameAttributeValue12.setDataType(STRING_DATATYPE); - configNameAttributeValue12.getContent().add(policyAdapter.getRiskLevel()); - assignment12.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue12)); - - advice.getAttributeAssignmentExpression().add(assignment12); - - AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType(); - assignment13.setAttributeId("guard"); - assignment13.setCategory(CATEGORY_RESOURCE); - assignment13.setIssuer(""); - - AttributeValueType configNameAttributeValue13 = new AttributeValueType(); - configNameAttributeValue13.setDataType(STRING_DATATYPE); - configNameAttributeValue13.getContent().add(policyAdapter.getGuard()); - assignment13.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue13)); - - advice.getAttributeAssignmentExpression().add(assignment13); - - AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType(); - assignment14.setAttributeId("TTLDate"); - assignment14.setCategory(CATEGORY_RESOURCE); - assignment14.setIssuer(""); - - AttributeValueType configNameAttributeValue14 = new AttributeValueType(); - configNameAttributeValue14.setDataType(STRING_DATATYPE); - configNameAttributeValue14.getContent().add(policyAdapter.getTtlDate()); - assignment14.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue14)); - - advice.getAttributeAssignmentExpression().add(assignment14); - - advices.getAdviceExpression().add(advice); - return advices; - } - - @Override - public Object getCorrectPolicyDataObject() { - return policyAdapter.getPolicyData(); - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/Policy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/Policy.java deleted file mode 100644 index bdd36123f..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/Policy.java +++ /dev/null @@ -1,416 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.Map; - -import javax.json.Json; -import javax.json.JsonReader; - -import org.apache.commons.io.FilenameUtils; -import org.json.JSONObject; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -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.xacml.util.XACMLPolicyWriter; - -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.util.XACMLProperties; -import com.att.research.xacmlatt.pdp.policy.PolicyDef; -import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef; - -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; - -public abstract class Policy { - - private static final Logger LOGGER = FlexLogger.getLogger(Policy.class); - - - /** - * Common Fields - */ - public static final String GET_INT_TYPE = "Integer"; - public static final String GET_STRING_TYPE = "String"; - - public static final String ECOMPID = "ECOMPName"; - public static final String CONFIGID = "ConfigName"; - public static final String CLOSEDLOOPID = "ServiceType"; - - public static final String CONFIG_POLICY = "Config"; - public static final String ACTION_POLICY = "Action"; - public static final String DECISION_POLICY = "Decision"; - - protected String policyName = null; - - protected boolean isValidForm = true; - - private Path finalPolicyPath = null; - - private boolean preparedToSave = false; - - private boolean policyExists = false; - - public Path getFinalPolicyPath() { - return finalPolicyPath; - } - - public void setFinalPolicyPath(Path finalPolicyPath) { - this.finalPolicyPath = finalPolicyPath; - } - - // 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_BOOLEAN_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:boolean-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_REGEXP_MATCH = "urn:oasis:names:tc:xacml:1.0:function:string-regexp-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 final String String = null; - - public static String CONFIG_HOME = null; - public static String ACTION_HOME = null; - public static String CONFIG_URL = null; - - protected Map performer = new HashMap<>(); - - private static String actionHome = null; - private static String configHome = null; - - public PolicyRestAdapter policyAdapter = null; - String ruleID = ""; - - public Policy() { - CONFIG_HOME = getConfigHome(); - ACTION_HOME = getActionHome(); - CONFIG_URL = "$URL"; - performer.put("PDP", "PDPAction"); - performer.put("PEP", "PEPAction"); - } - - //Each policy type seems to either use policyData or data field policy adapter when - //getting the xml to save the policy. Instead of keep this hardcoded in the save method, - //this method makes it usable outside. - /** - * Return the data field of the PolicyAdapter that will be used when saving this policy - * with the savePolicies method. - * @return Either the PolicyAdapter.getData() or PolicyAdapter.getPolicyData() - */ - public abstract Object getCorrectPolicyDataObject(); - public abstract Map savePolicies() throws Exception; - - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things - public abstract boolean prepareToSave() throws Exception; - - - // create match for ecomp and config name - protected MatchType createMatch(String key, String value) { - MatchType match = new MatchType(); - - AttributeValueType attributeValue = new AttributeValueType(); - attributeValue.setDataType(STRING_DATATYPE); - attributeValue.getContent().add(value); - match.setAttributeValue(attributeValue); - AttributeDesignatorType attributeDesignator = new AttributeDesignatorType(); - URI uri = null; - try { - uri = new URI(key); - } catch (URISyntaxException e) { - LOGGER.error("Exception Occured"+e); - } - attributeDesignator.setCategory(CATEGORY_ACCESS_SUBJECT); - attributeDesignator.setDataType(STRING_DATATYPE); - attributeDesignator.setAttributeId(new IdentifierImpl(uri).stringValue()); - match.setAttributeDesignator(attributeDesignator); - match.setMatchId(FUNCTION_STRING_REGEX_MATCH); - return match; - } - - // Creating the match for dynamically added components. - protected MatchType createDynamicMatch(String key, String value) { - MatchType dynamicMatch = new MatchType(); - AttributeValueType dynamicAttributeValue = new AttributeValueType(); - String dataType = null; - dataType = STRING_DATATYPE; - dynamicAttributeValue.setDataType(dataType); - dynamicAttributeValue.getContent().add(value); - dynamicMatch.setAttributeValue(dynamicAttributeValue); - - AttributeDesignatorType dynamicAttributeDesignator = new AttributeDesignatorType(); - - URI dynamicURI = null; - try { - dynamicURI = new URI(key); - } catch (URISyntaxException e) { - LOGGER.error("Exception Occured"+e);// log msg - } - dynamicAttributeDesignator.setCategory(CATEGORY_RESOURCE); - dynamicAttributeDesignator.setDataType(dataType); - dynamicAttributeDesignator.setAttributeId(new IdentifierImpl(dynamicURI).stringValue()); - dynamicMatch.setAttributeDesignator(dynamicAttributeDesignator); - dynamicMatch.setMatchId(FUNCTION_STRING_REGEX_MATCH); - - return dynamicMatch; - } - - //validation for numeric - protected boolean isNumeric(String str){ - for (char c : str.toCharArray()){ - if (!Character.isDigit(c)) return false; - } - return true; - } - - // 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 reading json"+e); - return false; - }finally{ - if(jsonReader != null){ - jsonReader.close(); - } - } - return true; - } - - // the Policy Name as Unique One throws error - @SuppressWarnings("static-access") - protected Path getNextFilename(Path parent, String policyType, String polcyFileName, Integer version) { - policyType = FilenameUtils.removeExtension(policyType); - polcyFileName = FilenameUtils.removeExtension(polcyFileName); - Path newFile = null; - String policyDir = EMPTY_STRING; - String absolutePath = parent.toString(); - if (absolutePath != null && !absolutePath.equals(EMPTY_STRING)) { - policyDir = absolutePath.substring(absolutePath.lastIndexOf("\\") + 1, absolutePath.length()); - if (policyDir == null || policyDir.equals(EMPTY_STRING)) { - policyDir = absolutePath.substring(absolutePath.lastIndexOf("/") + 1, absolutePath.length()); - } - } - - String fileName = "default"; - if (policyDir != null && !policyDir.equals(EMPTY_STRING)) { - fileName = policyType + "_" + String.format(polcyFileName) + "." + version + ".xml"; - } - if (fileName != null) { - newFile = Paths.get(parent.toString(), fileName); - } - if (Files.notExists(newFile)) { - return newFile; - } - return null; - } - - protected Path getNextLoopFilename(Path parentPath, String policyType, String policyConfigType, String policyFileName, Integer version) { - policyType = FilenameUtils.removeExtension(policyType); - policyConfigType = FilenameUtils.removeExtension(policyConfigType); - policyFileName = FilenameUtils.removeExtension(policyFileName); - Path newFile = null; - String policyDir = EMPTY_STRING; - String absolutePath = parentPath.toString(); - if (absolutePath != null && !absolutePath.equals(EMPTY_STRING)) { - policyDir = absolutePath.substring(absolutePath.lastIndexOf("\\") + 1, absolutePath.length()); - if (policyDir == null || policyDir.equals(EMPTY_STRING)) { - policyDir = absolutePath.substring(absolutePath.lastIndexOf("/") + 1, absolutePath.length()); - } - } - - String fileName = "default"; - if (policyDir != null && !policyDir.equals(EMPTY_STRING)) { - if(policyConfigType.equals("ClosedLoop_PM")){ - fileName = policyType + "_" + "PM" + "_" +java.lang.String.format(policyFileName) + "." +version +".xml"; - }else if(policyConfigType.equals("ClosedLoop_Fault")){ - fileName = policyType + "_" + "Fault" + "_" +java.lang.String.format(policyFileName) + "." + version + ".xml"; - }else if(policyConfigType.equals("ClosedLoop_Fault")){ - fileName = policyType + "_" + "Fault" + "_" +java.lang.String.format(policyFileName) + "." + version + ".xml"; - }else if(policyConfigType.equals("Micro Service")){ - fileName = policyType + "_" + "MS" + "_" + java.lang.String.format(policyFileName) + "." + version + ".xml"; - } - } - if (fileName != null) { - newFile = Paths.get(parentPath.toString(), fileName); - } - if (Files.notExists(newFile)) { - return newFile; - } - return null; - } - - - //create policy once all the validations are completed - protected Map createPolicy(final Path policyPath, final Object policyData) { - Map success = new HashMap<>(); - // - // Is the root a PolicySet or Policy? - // - - if (policyData instanceof PolicyType) { - // - // Write it out - // - //Does not need to be XACMLPolicyWriterWithPapNotify since it is already in the PAP - //and this transaction is intercepted up stream. - InputStream inputStream = null; - try { - inputStream = XACMLPolicyWriter.getXmlAsInputStream((PolicyType) policyData); - PolicyDef policyDef = DOMPolicyDef.load(inputStream); - if (policyDef == null) { - success.put("validation", "PolicyDef Validation Failed"); - }else{ - success.put("success", "success"); - } - } catch (Exception e) { - LOGGER.error("PolicyDef Validation failed"+e); - success.put("error", "Validation Failed"); - }finally{ - try { - if(inputStream != null) - inputStream.close(); - } catch (IOException e) { - LOGGER.error("Exception Occured while closing the input stream"+e); - } - } - } else { - PolicyLogger.error("Unknown data type sent back."); - return success; - } - return success; - } - - public static String getConfigHome(){ - try { - loadWebapps(); - } catch (Exception e) { - return null; - } - return configHome; - } - - public static String getActionHome(){ - try { - loadWebapps(); - } catch (Exception e) { - return null; - } - return actionHome; - } - - private static void loadWebapps() throws Exception{ - if(actionHome == null || configHome == null){ - Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); - //Sanity Check - if (webappsPath == null) { - PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); - throw new Exception("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); - } - Path webappsPathConfig; - Path webappsPathAction; - if(webappsPath.toString().contains("\\")){ - webappsPathConfig = Paths.get(webappsPath.toString()+"\\Config"); - webappsPathAction = Paths.get(webappsPath.toString()+"\\Action"); - }else{ - webappsPathConfig = Paths.get(webappsPath.toString()+"/Config"); - webappsPathAction = Paths.get(webappsPath.toString()+"/Action"); - } - if(Files.notExists(webappsPathConfig)){ - try { - Files.createDirectories(webappsPathConfig); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", "Failed to create config directory"); - } - } - if(Files.notExists(webappsPathAction)){ - try { - Files.createDirectories(webappsPathAction); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", "Failed to create config directory"); - } - } - actionHome = webappsPathAction.toString(); - configHome = webappsPathConfig.toString(); - } - } - - public boolean validateConfigForm() { - return true; - } - - /** - * @return the preparedToSave - */ - public boolean isPreparedToSave() { - return preparedToSave; - } - - /** - * @param preparedToSave the preparedToSave to set - */ - protected void setPreparedToSave(boolean preparedToSave) { - this.preparedToSave = preparedToSave; - } - - public boolean isPolicyExists() { - return policyExists; - } - - public void setPolicyExists(boolean policyExists) { - this.policyExists = policyExists; - } - - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDao.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDao.java deleted file mode 100644 index 2297413e8..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDao.java +++ /dev/null @@ -1,2798 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.ProtocolException; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.InvalidPathException; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.Key; -import java.util.Base64; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -import javax.crypto.Cipher; -import javax.crypto.spec.SecretKeySpec; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.LockModeType; -import javax.persistence.PersistenceException; -import javax.persistence.Query; -import javax.persistence.RollbackException; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathFactory; - -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.io.IOUtils; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -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.DatabaseLockEntity; -import org.openecomp.policy.rest.jpa.GroupEntity; -import org.openecomp.policy.rest.jpa.PdpEntity; -import org.openecomp.policy.rest.jpa.PolicyDBDaoEntity; -import org.openecomp.policy.rest.jpa.PolicyEntity; -import org.openecomp.policy.rest.util.Webapps; -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.StdPDPGroup; -import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; -import org.openecomp.policy.xacml.util.XACMLPolicyWriter; -import org.w3c.dom.Document; -import org.xml.sax.InputSource; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDP; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.att.research.xacml.util.XACMLProperties; - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; - -public class PolicyDBDao { - private static final Logger logger = FlexLogger.getLogger(PolicyDBDao.class); - private List otherServers; - private EntityManagerFactory emf; - private static PolicyDBDao currentInstance = null; - private PAPPolicyEngine papEngine; - - public static final String JSON_CONFIG = "JSON"; - public static final String XML_CONFIG = "XML"; - public static final String PROPERTIES_CONFIG = "PROPERTIES"; - public static final String OTHER_CONFIG = "OTHER"; - public static final String AUDIT_USER = "audit"; - - /** - * Get an instance of a PolicyDBDao. It creates one if it does not exist. - * Only one instance is allowed to be created per server. - * @param emf The EntityFactoryManager to be used for database connections - * @return The new instance of PolicyDBDao or throw exception if the given emf is null. - * @throws IllegalStateException if a PolicyDBDao has already been constructed. Call getPolicyDBDaoInstance() to get this. - */ - public static PolicyDBDao getPolicyDBDaoInstance(EntityManagerFactory emf) throws Exception{ - logger.debug("getPolicyDBDaoInstance(EntityManagerFactory emf) as getPolicyDBDaoInstance("+emf+") called"); - if(currentInstance == null){ - if(emf != null){ - currentInstance = new PolicyDBDao(emf); - return currentInstance; - } - throw new IllegalStateException("The EntityManagerFactory is Null"); - } - return currentInstance; - } - - /** - * Gets the current instance of PolicyDBDao. - * @return The instance of PolicyDBDao or throws exception if the given instance is null. - * @throws IllegalStateException if a PolicyDBDao instance is null. Call createPolicyDBDaoInstance(EntityManagerFactory emf) to get this. - */ - public static PolicyDBDao getPolicyDBDaoInstance() throws Exception{ - logger.debug("getPolicyDBDaoInstance() as getPolicyDBDaoInstance() called"); - if(currentInstance != null){ - return currentInstance; - } - throw new IllegalStateException("The PolicyDBDao.currentInstance is Null. Use getPolicyDBDao(EntityManagerFactory emf)"); - } - public void setPapEngine(PAPPolicyEngine papEngine2){ - this.papEngine = (PAPPolicyEngine) papEngine2; - } - private PolicyDBDao(EntityManagerFactory emf){ - logger.debug("PolicyDBDao(EntityManagerFactory emf) as PolicyDBDao("+emf+") called"); - this.emf = emf; - - //not needed in this release - if(!register()){ - PolicyLogger.error("This server's PolicyDBDao instance could not be registered and may not reveive updates"); - } - - otherServers = getRemotePolicyDBDaoList(); - if(logger.isDebugEnabled()){ - logger.debug("Number of remote PolicyDBDao instances: "+otherServers.size()); - } - if(otherServers.isEmpty()){ - logger.warn("List of PolicyDBDao servers is empty or could not be retrieved"); - } - } - - //not static because we are going to be using the instance's emf - //waitTime in ms to wait for lock, or -1 to wait forever (no) - private void startTransactionSynced(EntityManager entityMgr,int waitTime){ - logger.debug("\n\nstartTransactionSynced(EntityManager entityMgr,int waitTime) as " - + "\n startTransactionSynced("+entityMgr+","+waitTime+") called\n\n"); - DatabaseLockEntity lock = null; - - entityMgr.setProperty("javax.persistence.query.timeout", waitTime); - entityMgr.getTransaction().begin(); - - if(logger.isDebugEnabled()){ - Map properties = entityMgr.getProperties(); - logger.debug("\n\nstartTransactionSynced():" - + "\n entityManager.getProperties() = " + properties - + "\n\n"); - } - try{ - if(logger.isDebugEnabled()){ - logger.debug("\n\nstartTransactionSynced():" - + "\n ATTEMPT to get the DB lock" - + "\n\n"); - } - lock = entityMgr.find(DatabaseLockEntity.class, 1, LockModeType.PESSIMISTIC_WRITE); - if(logger.isDebugEnabled()){ - logger.debug("\n\nstartTransactionSynced():" - + "\n GOT the DB lock" - + "\n\n"); - } - } catch(Exception e){ - System.out.println("Could not get lock entity"); - logger.error("Exception Occured"+e); - } - if(lock == null){ - throw new IllegalStateException("The lock row does not exist in the table. Please create a primary key with value = 1."); - } - - } - /** - * Gets the list of other registered PolicyDBDaos from the database - * @return List (type PolicyDBDaoEntity) of other PolicyDBDaos - */ - private List getRemotePolicyDBDaoList(){ - logger.debug("getRemotePolicyDBDaoList() as getRemotePolicyDBDaoList() called"); - List policyDBDaoEntityList = new LinkedList<>(); - EntityManager em = emf.createEntityManager(); - startTransactionSynced(em, 1000); - try{ - Query getPolicyDBDaoEntityQuery = em.createNamedQuery("PolicyDBDaoEntity.findAll"); - policyDBDaoEntityList = getPolicyDBDaoEntityQuery.getResultList(); - - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Exception querying for other registered PolicyDBDaos"); - logger.warn("List of remote PolicyDBDaos will be empty"); - } - try{ - em.getTransaction().commit(); - } catch(Exception e){ - try{ - em.getTransaction().rollback(); - } catch(Exception e2){ - - } - } - em.close(); - return policyDBDaoEntityList; - } - - public PolicyDBDaoTransaction getNewTransaction(){ - logger.debug("getNewTransaction() as getNewTransaction() called"); - return (PolicyDBDaoTransaction)(new PolicyDBDaoTransactionInstance()); - } - - /* - * Because the normal transactions are not used in audits, we can use the same transaction - * mechanism to get a transaction and obtain the emlock and the DB lock. We just need to - * provide different transaction timeout values in ms because the audit will run longer - * than normal transactions. - */ - public PolicyDBDaoTransaction getNewAuditTransaction(){ - logger.debug("getNewAuditTransaction() as getNewAuditTransaction() called"); - //Use the standard transaction wait time in ms - int auditWaitMs = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); - //Use the (extended) audit timeout time in ms - int auditTimeoutMs = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); - return (PolicyDBDaoTransaction)(new PolicyDBDaoTransactionInstance(auditTimeoutMs, auditWaitMs)); - } - - - /** - * Checks if two strings are equal. Null strings ARE allowed. - * @param one A String or null to compare - * @param two A String or null to compare - */ - private static boolean stringEquals(String one, String two){ - logger.debug("stringEquals(String one, String two) as stringEquals("+one+", "+two+") called"); - if(one == null && two == null){ - return true; - } - if(one == null || two == null){ - return false; - } - return one.equals(two); - } - - /** - * Computes the scope in dotted format based on an absolute path and a path that divides the scope. - * @param fullPath An absolute path including scope folders and other folders(does not have to be absolute, must just contain scope and other folders before) - * @param pathToExclude The path that acts as a division between the scope and the other folders - * @return The scope in dotted format (org.openecomp) - */ - private static String computeScope(String fullPath, String pathToExclude){ - logger.debug("computeScope(String fullPath, String pathToExclude) as computeScope("+fullPath+", "+pathToExclude+") called"); - int excludeIndex = fullPath.indexOf(pathToExclude); - String scopePath = fullPath.substring(excludeIndex+pathToExclude.length()); - String scope = scopePath.replace('\\', '.'); - scope = scope.replace('/', '.'); - if(scope.charAt(0) == '.'){ - scope = scope.substring(1); - } - if(scope.charAt(scope.length()-1) == '.'){ - scope = scope.substring(0, scope.length()-1); - } - return scope; - } - - /** - * Returns the url of this local pap server, removing the username and password, if they are present - * @return The url of this local pap server - */ - private String[] getPapUrlUserPass(){ - logger.debug("getPapUrl() as getPapUrl() called"); - String url = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); - if(url == null){ - return null; - } - return splitPapUrlUserPass(url); - - - } - private String[] splitPapUrlUserPass(String url){ - String[] urlUserPass = new String[3]; - String[] commaSplit = url.split(","); - urlUserPass[0] = commaSplit[0]; - if(commaSplit.length > 2){ - urlUserPass[1] = commaSplit[1]; - urlUserPass[2] = commaSplit[2]; - } - if(urlUserPass[1] == null || urlUserPass[1].equals("")){ - String usernamePropertyValue = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); - if(usernamePropertyValue != null){ - urlUserPass[1] = usernamePropertyValue; - } - } - if(urlUserPass[2] == null || urlUserPass[2].equals("")){ - String passwordPropertyValue = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); - if(passwordPropertyValue != null){ - urlUserPass[2] = passwordPropertyValue; - } - } - //if there is no comma, for some reason there is no username and password, so don't try to cut them off - return urlUserPass; - } - - private static String encryptPassword(String password) throws Exception{ - Cipher cipher = Cipher.getInstance("AES"); - cipher.init(Cipher.ENCRYPT_MODE, aesKey()); - byte[] encryption = cipher.doFinal(password.getBytes("UTF-8")); - System.out.println(encryption); - return new String(Base64.getMimeEncoder().encode(encryption),"UTF-8"); - } - - private static String decryptPassword(String encryptedPassword) throws Exception{ - Cipher cipher = Cipher.getInstance("AES"); - cipher.init(Cipher.DECRYPT_MODE, aesKey()); - byte[] password = cipher.doFinal(Base64.getDecoder().decode(encryptedPassword.getBytes("UTF-8"))); - return new String(password,"UTF-8"); - } - private static Key aesKey(){ - byte[] aesValue = (new String("njrmbklcxtoplawf")).getBytes(); - return new SecretKeySpec(aesValue,"AES"); - } - /** - * Register the PolicyDBDao instance in the PolicyDBDaoEntity table - * @return Boolean, were we able to register? - */ - private boolean register(){ - logger.debug("register() as register() called"); - String[] url = getPapUrlUserPass(); - EntityManager em = emf.createEntityManager(); - try{ - startTransactionSynced(em, 1000); - } catch(IllegalStateException e){ - logger.debug ("\nPolicyDBDao.register() caught an IllegalStateException: \n" +e + "\n"); - DatabaseLockEntity lock; - lock = em.find(DatabaseLockEntity.class, 1); - if(lock==null){ - lock = new DatabaseLockEntity(); - em.persist(lock); - lock.setKey(1); - try{ - em.flush(); - em.getTransaction().commit(); - em.close(); - } catch(Exception e2){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "COULD NOT CREATE DATABASELOCK ROW. WILL TRY ONE MORE TIME"); - } - em = null; - em = emf.createEntityManager(); - try{ - startTransactionSynced(em, 1000); - } catch(Exception e3){ - String msg = "DATABASE LOCKING NOT WORKING. CONCURRENCY CONTROL NOT WORKING"; - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e3, "PolicyDBDao", msg); - throw new IllegalStateException("msg" + "\n" + e3); - } - } - } - logger.debug("\nPolicyDBDao.register. Database locking and concurrency control is initialized\n"); - PolicyDBDaoEntity foundPolicyDBDaoEntity = em.find(PolicyDBDaoEntity.class, url[0]); - Query getPolicyDBDaoEntityQuery = em.createQuery("SELECT e FROM PolicyDBDaoEntity e WHERE e.policyDBDaoUrl=:url"); - getPolicyDBDaoEntityQuery.setParameter("url", url[0]); - if(foundPolicyDBDaoEntity == null){ - PolicyDBDaoEntity newPolicyDBDaoEntity = new PolicyDBDaoEntity(); - em.persist(newPolicyDBDaoEntity); - newPolicyDBDaoEntity.setPolicyDBDaoUrl(url[0]); - newPolicyDBDaoEntity.setDescription("PAP server at "+url[0]); - newPolicyDBDaoEntity.setUsername(url[1]); - try{ - newPolicyDBDaoEntity.setPassword(encryptPassword(url[2])); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not encrypt PAP password"); - } - try{ - em.getTransaction().commit(); - } catch(Exception e){ - try{ - em.getTransaction().rollback(); - } catch(Exception e2){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "Could not add new PolicyDBDao to the database"); - } - } - } else { - //just want to update in order to change modified date - String encryptedPassword = null; - try{ - encryptedPassword = encryptPassword(url[2]); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not encrypt PAP password"); - } - if(url[1] != null && !stringEquals(url[1], foundPolicyDBDaoEntity.getUsername())){ - foundPolicyDBDaoEntity.setUsername(url[1]); - } - if(encryptedPassword != null && !stringEquals(encryptedPassword, foundPolicyDBDaoEntity.getPassword())){ - foundPolicyDBDaoEntity.setPassword(encryptedPassword); - } - foundPolicyDBDaoEntity.preUpdate(); - try{ - em.getTransaction().commit(); - } catch(Exception e){ - try{ - em.getTransaction().rollback(); - } catch(Exception e2){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "Could not update PolicyDBDao in the database"); - } - } - } - em.close(); - logger.debug("\nPolicyDBDao.register(). Success!!\n"); - return true; - } - public void notifyOthers(long entityId,String entityType){ - notifyOthers(entityId,entityType,null); - } - public void notifyOthers(long entityId, String entityType, String newGroupId){ - logger.debug("notifyOthers(long entityId, String entityType, long newGroupId) as notifyOthers("+entityId+","+entityType+","+newGroupId+") called"); - LinkedList notifyThreads = new LinkedList<>(); - - //we're going to run notifications in parallel threads to speed things up - for(Object obj : otherServers){ - - Thread newNotifyThread = new Thread(new NotifyOtherThread(obj, entityId, entityType, newGroupId)); - - newNotifyThread.start(); - - notifyThreads.add(newNotifyThread); - - } - //we want to wait for all notifications to complete or timeout before we unlock the interface and allow more changes - for(Thread t : notifyThreads){ - try { - t.join(); - } catch (Exception e) { - logger.warn("Could not join a notifcation thread" + e); - } - } - - - } - - private class NotifyOtherThread implements Runnable { - public NotifyOtherThread(Object obj, long entityId, String entityType, String newGroupId){ - this.obj = obj; - this.entityId = entityId; - this.entityType = entityType; - this.newGroupId = newGroupId; - } - private Object obj; - private long entityId; - private String entityType; - private String newGroupId; - @Override - public void run(){ - //naming of 'o' is for backwards compatibility with the rest of the function - PolicyDBDaoEntity dbdEntity = (PolicyDBDaoEntity)obj; - String o = dbdEntity.getPolicyDBDaoUrl(); - String username = dbdEntity.getUsername(); - String password; - try{ - password = decryptPassword(dbdEntity.getPassword()); - } catch(Exception e){ - //if we can't decrypt, might as well try it anyway - password = dbdEntity.getPassword(); - } - Base64.Encoder encoder = Base64.getEncoder(); - String encoding = encoder.encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8)); - HttpURLConnection connection = null; - UUID requestID = UUID.randomUUID(); - URL url; - try { - String papUrl = getPapUrlUserPass()[0]; - if(papUrl == null){ - papUrl = "undefined"; - } - logger.debug("We are going to try to notify "+o); - //is this our own url? - String ourUrl = o; - try{ - ourUrl = splitPapUrlUserPass((String)o)[0]; - }catch(Exception e){ - ourUrl = o; - } - if(o == null){ - o = "undefined"; - } - if(papUrl.equals(ourUrl)){ - logger.debug(((String)o)+" is our url, skipping notify"); - return; - } - if(newGroupId == null){ - url = new URL(((String)o)+"?policydbdaourl="+papUrl+"&entityid="+entityId+"&entitytype="+entityType); - } else { - url = new URL(((String)o)+"?policydbdaourl="+papUrl+"&entityid="+entityId+"&entitytype="+entityType+"&extradata="+newGroupId); - } - } catch (MalformedURLException e) { - logger.warn("Caught MalformedURLException on: new URL()", e); - return; - } - // - // Open up the connection - // - logger.debug("Connecting with url: "+url); - try { - connection = (HttpURLConnection)url.openConnection(); - } catch (Exception e) { - logger.warn("Caught exception on: url.openConnection()",e); - return; - } - // - // Setup our method and headers - // - try { - connection.setRequestMethod("PUT"); - } catch (ProtocolException e) { - //why would this error ever occur? - logger.warn("Caught ProtocolException on connection.setRequestMethod(\"PUT\");",e); - return; - } - 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()); - int readTimeout; - try{ - readTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_NOTIFY_TIMEOUT)); - - } catch(Exception e){ - logger.error("xacml.rest.pap.notify.timeoutms property not set, using a default."); - readTimeout = 10000; - } - connection.setReadTimeout(readTimeout); - connection.setConnectTimeout(readTimeout); - 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 (Exception e) { - logger.warn("Caught exception on: connection.connect()",e); - return; - } - try { - if (connection.getResponseCode() == 200) { - logger.info("Received response 200 from pap server on notify"); - //notified = true; - } else { - logger.warn("connection response code not 200, received: "+connection.getResponseCode()); - } - } catch (Exception e) { - logger.warn("Caught Exception on: connection.getResponseCode() ", e); - } - - - connection.disconnect(); - } - } - - private static String evaluateXPath(String expression, String xml) { - InputSource source = new InputSource(new StringReader(xml)); - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - String description = ""; - try{ - DocumentBuilder db = dbf.newDocumentBuilder(); - Document document = db.parse(source); - - XPathFactory xpathFactory = XPathFactory.newInstance(); - XPath xpath = xpathFactory.newXPath(); - - - description = xpath.evaluate(expression, document); - }catch(Exception e){ - logger.error("Exception Occured while evaluating path"+e); - } - - return description; - } - - private static String getDescriptionFromXacml(String xacmlData){ - String openTag = ""; - String closeTag = ""; - int descIndex = xacmlData.indexOf(openTag); - int endDescIndex = xacmlData.indexOf(closeTag); - String desc = xacmlData.substring(descIndex+openTag.length(),endDescIndex); - return desc; - } - - private final String POLICY_NOTIFICATION = "policy"; - private final String PDP_NOTIFICATION = "pdp"; - private final String GROUP_NOTIFICATION = "group"; - public void handleIncomingHttpNotification(String url, String entityId, String entityType, String extraData, XACMLPapServlet xacmlPapServlet){ - logger.info("DBDao url: " + url + " has reported an update on "+entityType+" entity "+entityId); - PolicyDBDaoTransaction transaction = this.getNewTransaction(); - //although its named retries, this is the total number of tries - int retries; - try{ - retries = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INCOMINGNOTIFICATION_TRIES)); - - } catch(Exception e){ - logger.error("xacml.rest.pap.incomingnotification.tries property not set, using a default of 3."+e); - retries = 3; - } - //if someone sets it to some dumb value, we need to make sure it will try at least once - if(retries < 1){ - retries = 1; - } - int pauseBetweenRetries = 1000; - switch(entityType){ - - case POLICY_NOTIFICATION: - for(int i=0; i pdpsInGroup = transaction.getPdpsInGroup(Long.parseLong(groupRecord.getGroupId())); - for(Object pdpO : pdpsInGroup){ - PdpEntity pdp = (PdpEntity)pdpO; - try { - papEngine.newPDP(pdp.getPdpId(), localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort()); - } catch (NullPointerException | PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to get create pdp with papEngine.newPDP(pdp.getPdpId(), localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort());"); - throw new PAPException("Could not create pdp "+pdp); - } - } - //add possible policies to group (filesystem only, apparently) - } else { - if(!(localGroup instanceof StdPDPGroup)){ - throw new PAPException("group is not a StdPDPGroup"); - } - //clone the object - //because it will be comparing the new group to its own version - StdPDPGroup localGroupClone = new StdPDPGroup(localGroup.getId(),localGroup.isDefaultGroup(),localGroup.getName(),localGroup.getDescription(),((StdPDPGroup)localGroup).getDirectory()); - localGroupClone.setEcompPdps(localGroup.getEcompPdps()); - localGroupClone.setPipConfigs(localGroup.getPipConfigs()); - localGroupClone.setStatus(localGroup.getStatus()); - //we are updating a group or adding a policy or changing default - //set default if it should be - if(!localGroupClone.isDefaultGroup() && groupRecord.isDefaultGroup()){ - try { - papEngine.SetDefaultGroup(localGroup); - return; - } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to set default group with papEngine.SetDefaultGroup("+localGroupClone+");"); - throw new PAPException("Could not set default group to "+localGroupClone); - } - } - boolean needToUpdate = false; - if(updateGroupPoliciesInFileSystem(localGroupClone,localGroup, groupRecord, transaction)){ - needToUpdate = true; - } - if(!stringEquals(localGroupClone.getId(),groupRecord.getGroupId()) || !stringEquals(localGroupClone.getName(),groupRecord.getgroupName())){ - //changing ids - //we do not want to change the id, the papEngine will do this for us, it needs to know the old id - localGroupClone.setName(groupRecord.getgroupName()); - needToUpdate = true; - } - if(!stringEquals(localGroupClone.getDescription(),groupRecord.getDescription())){ - localGroupClone.setDescription(groupRecord.getDescription()); - needToUpdate = true; - } - if(needToUpdate){ - try { - - papEngine.updateGroup(localGroupClone); - } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to update group with papEngine.updateGroup("+localGroupClone+");"); - throw new PAPException("Could not update group "+localGroupClone); - } - } - - } - //call command that corresponds to the change that was made - } - //this will also handle removes, since incoming pdpGroup has no policies internally, we are just going to add them all in from the db - private boolean updateGroupPoliciesInFileSystem(EcompPDPGroup pdpGroup,EcompPDPGroup oldPdpGroup, GroupEntity groupRecord, PolicyDBDaoTransaction transaction) throws PAPException{ - if(!(pdpGroup instanceof StdPDPGroup)){ - throw new PAPException("group is not a StdPDPGroup"); - } - StdPDPGroup group = (StdPDPGroup)pdpGroup; - //this must always be true since we don't explicitly know when a delete is occuring - boolean didUpdate = true; - HashMap currentPolicySet = new HashMap(oldPdpGroup.getPolicies().size()); - HashSet newPolicySet = new HashSet<>(); - for(PDPPolicy pdpPolicy : oldPdpGroup.getPolicies()){ - currentPolicySet.put(pdpPolicy.getId(), pdpPolicy); - } - for(PolicyEntity policy : groupRecord.getPolicies()){ - String pdpPolicyName = getPdpPolicyName(policy.getPolicyName(), policy.getScope()); - if(group.getPolicy(pdpPolicyName) == null){ - didUpdate = true; - if(currentPolicySet.containsKey(pdpPolicyName)){ - newPolicySet.add(currentPolicySet.get(pdpPolicyName)); - } else{ - InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes()); - group.copyPolicyToFile(pdpPolicyName,policyStream); - ((StdPDPPolicy)(group.getPolicy(pdpPolicyName))).setName(removeExtensionAndVersionFromPolicyName(policy.getPolicyName())); - try { - policyStream.close(); - } catch (IOException e) { - didUpdate = false; - PolicyLogger.error(e.getMessage() +e); - } - } - } - } - if(didUpdate){ - newPolicySet.addAll(group.getPolicies()); - group.setPolicies(newPolicySet); - } - return didUpdate; - - } - private String removeExtensionAndVersionFromPolicyName(String originalPolicyName){ - return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0]; - } - - /** - * Splits apart the policy name and version from a policy file path - * @param originalPolicyName: a policy file name ex: Config_policy.2.xml - * @return An array [0]: The policy name, [1]: the policy version, as a string - */ - private String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName){ - String policyName = originalPolicyName; - String[] nameAndVersion = new String[2]; - try{ - policyName = removeFileExtension(policyName); - nameAndVersion[0] = policyName.substring(0,policyName.lastIndexOf('.')); - if(isNullOrEmpty(nameAndVersion[0])){ - throw new Exception(); - } - } catch(Exception e){ - nameAndVersion[0] = originalPolicyName; - } - try{ - nameAndVersion[1] = policyName.substring(policyName.lastIndexOf('.')+1); - if(isNullOrEmpty(nameAndVersion[1])){ - throw new Exception(); - } - } catch(Exception e){ - nameAndVersion[1] = "1"; - } - return nameAndVersion; - } - - private void handleIncomingPdpChange(String url, String pdpId, PolicyDBDaoTransaction transaction) throws PAPException{ - //get pdp - long pdpIdLong = -1; - try{ - pdpIdLong = Long.parseLong(pdpId); - }catch(NumberFormatException e){ - throw new IllegalArgumentException("pdpId "+pdpId+" cannot be parsed into a long"); - } - PdpEntity pdpRecord = null; - try{ - pdpRecord = transaction.getPdp(pdpIdLong); - }catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get pdp record with transaction.getPdp("+pdpIdLong+");"); - throw new PAPException("Could not get local pdp "+pdpIdLong); - } - if(pdpRecord == null){ - throw new PersistenceException("The pdpRecord returned is null"); - } - PDP localPdp = null; - try { - localPdp = papEngine.getPDP(pdpRecord.getPdpId()); - } catch (PAPException e) { - logger.warn("Caught PAPException trying to get local pdp with papEngine.getPDP("+pdpId+");",e); - } - if(localPdp != null && pdpRecord.isDeleted()){ - try { - papEngine.removePDP((EcompPDP) localPdp); - } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to get remove pdp with papEngine.removePDP("+localPdp+");"); - throw new PAPException("Could not remove pdp "+pdpId); - } - } - else if(localPdp == null){ - //add new pdp - //get group - EcompPDPGroup localGroup = null; - try { - localGroup = papEngine.getGroup(pdpRecord.getGroup().getGroupId()); - } catch (PAPException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "Caught PAPException trying to get local group to add pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); - throw new PAPException("Could not get local group"); - } - try { - papEngine.newPDP(pdpRecord.getPdpId(), localGroup, pdpRecord.getPdpName(), pdpRecord.getDescription(), pdpRecord.getJmxPort()); - } catch (NullPointerException | PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to create pdp with papEngine.newPDP("+pdpRecord.getPdpId()+", "+localGroup+", "+pdpRecord.getPdpName()+", "+pdpRecord.getDescription()+", "+pdpRecord.getJmxPort()+");"); - throw new PAPException("Could not create pdp "+pdpRecord); - } - } else { - boolean needToUpdate = false; - if(!stringEquals(localPdp.getId(),pdpRecord.getPdpId()) || !stringEquals(localPdp.getName(),pdpRecord.getPdpName())){ - //again, we don't want to change the id, the papEngine will do this - localPdp.setName(pdpRecord.getPdpName()); - needToUpdate = true; - } - if(!stringEquals(localPdp.getDescription(),pdpRecord.getDescription())){ - localPdp.setDescription(pdpRecord.getDescription()); - needToUpdate = true; - } - String localPdpGroupId = null; - try{ - localPdpGroupId = papEngine.getPDPGroup((EcompPDP) localPdp).getId(); - } catch(PAPException e){ - //could be null or something, just warn at this point - logger.warn("Caught PAPException trying to get id of local group that pdp is in with localPdpGroupId = papEngine.getPDPGroup(localPdp).getId();",e); - } - if(!stringEquals(localPdpGroupId,pdpRecord.getGroup().getGroupId())){ - EcompPDPGroup newPdpGroup = null; - try{ - newPdpGroup = papEngine.getGroup(pdpRecord.getGroup().getGroupId()); - }catch(PAPException e){ - //ok, now we have an issue. Time to stop things - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to get id of local group to move pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); - throw new PAPException("Could not get local group"); - } - try{ - papEngine.movePDP((EcompPDP) localPdp, newPdpGroup); - }catch(PAPException e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to move pdp with papEngine.movePDP(localPdp, newPdpGroup);"); - throw new PAPException("Could not move pdp "+localPdp); - } - } - if(((PdpEntity) localPdp).getJmxPort() != pdpRecord.getJmxPort()){ - ((PdpEntity) localPdp).setJmxPort(pdpRecord.getJmxPort()); - needToUpdate = true; - } - if(needToUpdate){ - try { - papEngine.updatePDP((EcompPDP) localPdp); - } catch (PAPException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to update pdp with papEngine.updatePdp("+localPdp+");"); - throw new PAPException("Could not update pdp "+localPdp); - } - } - } - //compare to local situation - //call command to update - } - private void handleIncomingPolicyChange(String url, String policyId,String oldPathString){ - String policyName = null; - EntityManager em = emf.createEntityManager(); - Query getPolicyEntityQuery = em.createNamedQuery("PolicyEntity.FindById"); - getPolicyEntityQuery.setParameter("id", Long.valueOf(policyId)); - - @SuppressWarnings("unchecked") - List policies = getPolicyEntityQuery.getResultList(); - PolicyEntity policy = null; - if (!policies.isEmpty()){ - policy = policies.get(0); - } - String action = "unknown action"; - try { - if(policy != null){ - policyName = policy.getPolicyName(); - logger.debug("Deleting Policy: " + policy.getPolicyName()); - action = "delete"; - Path subFile = null; - - if (policy.getConfigurationData()!= null){ - subFile = getPolicySubFile(policy.getConfigurationData().getConfigurationName(), "Config"); - }else if(policy.getActionBodyEntity()!= null){ - subFile = getPolicySubFile(policy.getActionBodyEntity().getActionBodyName(), "Action"); - } - - if(subFile != null){ - Files.deleteIfExists(subFile); - } - if (policy.getConfigurationData()!= null){ - writePolicySubFile(policy, "Config"); - }else if(policy.getActionBodyEntity()!= null){ - writePolicySubFile(policy, "Action"); - } - } - } catch (IOException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "Error occurred while performing [" + action + "] of Policy File: " + policyName); - } - } - - private String getPdpPolicyName(String name, String scope){ - String finalName = ""; - finalName += scope; - finalName += "."; - finalName += removeFileExtension(name); - finalName += ".xml"; - return finalName; - } - private String removeFileExtension(String fileName){ - return fileName.substring(0, fileName.lastIndexOf('.')); - } - - private Path getPolicySubFile(String filename, String subFileType){ - logger.debug("getPolicySubFile(" + filename + ", " + subFileType + ")"); - Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS).toString(), subFileType); - File file = null; - - filename = FilenameUtils.removeExtension(filename); - - for(File tmpFile : filePath.toFile().listFiles()){ - if (FilenameUtils.removeExtension(tmpFile.getName()).equals(filename)){ - file = tmpFile; - } - } - - Path finalPath = null; - if (file!= null){ - finalPath = Paths.get(file.getAbsolutePath()); - } - - logger.debug("end of getPolicySubFile: " + finalPath); - return finalPath; - } - - private boolean writePolicySubFile(PolicyEntity policy, String policyType){ - logger.info("writePolicySubFile with policyName[" + policy.getPolicyName() + "] and policyType[" + policyType + "]"); - String type = null; - String subTypeName = null; - String subTypeBody = null; - if (policyType.equalsIgnoreCase("config")){ - type = "Config"; - subTypeName = FilenameUtils.removeExtension(policy.getConfigurationData().getConfigurationName()); - subTypeBody = policy.getConfigurationData().getConfigBody(); - - String configType = policy.getConfigurationData().getConfigType(); - - - if (configType != null) { - if (configType.equals(JSON_CONFIG)) { - subTypeName = subTypeName + ".json"; - } - if (configType.equals(XML_CONFIG)) { - subTypeName = subTypeName + ".xml"; - } - if (configType.equals(PROPERTIES_CONFIG)) { - subTypeName = subTypeName + ".properties"; - } - if (configType.equals(OTHER_CONFIG)) { - subTypeName = subTypeName + ".txt"; - } - } - - }else if (policyType.equalsIgnoreCase("action")){ - type = "Action"; - subTypeName = policy.getActionBodyEntity().getActionBodyName(); - subTypeBody = policy.getActionBodyEntity().getActionBody(); - - - } - Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS).toString(), type); - - if(subTypeBody == null){ - subTypeBody = ""; - } - boolean success = false; - try { - Files.deleteIfExists(Paths.get(filePath.toString(), subTypeName)); - File file = Paths.get(filePath.toString(),subTypeName).toFile(); - file.createNewFile(); - FileWriter fileWriter = new FileWriter(file, false); // false to overwrite - fileWriter.write(subTypeBody); - fileWriter.close(); - success = true; - - } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Exception occured while creating Configuration File for Policy : " + policy.getPolicyName()); - } - - return success; - - } - - public void auditLocalDatabase(PAPPolicyEngine papEngine2){ - logger.debug("PolicyDBDao.auditLocalDatabase() is called"); - try{ - deleteAllGroupTables(); - auditGroups(papEngine2); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "auditLocalDatabase() error"); - logger.error("Exception Occured"+e); - } - } - - public void deleteAllGroupTables(){ - logger.debug("PolicyDBDao.deleteAllGroupTables() called"); - EntityManager em = emf.createEntityManager(); - em.getTransaction().begin(); - - Query deletePdpEntityEntityTableUpdate = em.createNamedQuery("PdpEntity.deleteAll"); - deletePdpEntityEntityTableUpdate.executeUpdate(); - - Query deleteGroupEntityTableUpdate = em.createNamedQuery("GroupEntity.deleteAll"); - deleteGroupEntityTableUpdate.executeUpdate(); - - em.getTransaction().commit(); - em.close(); - } - - @SuppressWarnings("unchecked") - public void auditGroups(PAPPolicyEngine papEngine2){ - logger.debug("PolicyDBDao.auditGroups() called"); - - EntityManager em = emf.createEntityManager(); - em.getTransaction().begin(); - final String AUDIT_STR = "Audit"; - try{ - - Set groups = papEngine2.getEcompPDPGroups(); - - for (EcompPDPGroup grp : groups){ - try{ - GroupEntity groupEntity = new GroupEntity(); - em.persist(groupEntity); - groupEntity.setGroupName(grp.getName()); - groupEntity.setDescription(grp.getDescription()); - groupEntity.setDefaultGroup(grp.isDefaultGroup()); - groupEntity.setCreatedBy(AUDIT_STR); - groupEntity.setGroupId(createNewPDPGroupId(grp.getId())); - groupEntity.setModifiedBy(AUDIT_STR); - Set pdps = grp.getEcompPdps(); - - for(EcompPDP pdp : pdps){ - PdpEntity pdpEntity = new PdpEntity(); - em.persist(pdpEntity); - pdpEntity.setGroup(groupEntity); - pdpEntity.setJmxPort(pdp.getJmxPort()); - pdpEntity.setPdpId(pdp.getId()); - pdpEntity.setPdpName(pdp.getName()); - pdpEntity.setModifiedBy(AUDIT_STR); - pdpEntity.setCreatedBy(AUDIT_STR); - - } - - Set policies = grp.getPolicies(); - - for(PDPPolicy policy : policies){ - try{ - String[] stringArray = getNameScopeAndVersionFromPdpPolicy(policy.getId()); - List policyEntityList; - Query getPolicyEntitiesQuery = em.createNamedQuery("PolicyEntity.findByNameAndScope"); - getPolicyEntitiesQuery.setParameter("name", stringArray[0]); - getPolicyEntitiesQuery.setParameter("scope", stringArray[1]); - - policyEntityList = getPolicyEntitiesQuery.getResultList(); - PolicyEntity policyEntity = null; - if(!policyEntityList.isEmpty()){ - policyEntity = policyEntityList.get(0); - } - if(policyEntity != null){ - groupEntity.addPolicyToGroup(policyEntity); - } - }catch(Exception e2){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "Exception auditGroups inner catch"); - } - } - }catch(Exception e1){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "Exception auditGroups middle catch"); - } - } - }catch(Exception e){ - em.getTransaction().rollback(); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Exception auditGroups outer catch"); - em.close(); - return; - } - - em.getTransaction().commit(); - em.close(); - - } - - private String getConfigFile(String filename, PolicyRestAdapter policy){ - if(policy == null){ - return getConfigFile(filename, (String)null); - } - return getConfigFile(filename, policy.getConfigType()); - } - //copied from ConfigPolicy.java and modified - // Here we are adding the extension for the configurations file based on the - // config type selection for saving. - private String getConfigFile(String filename, String configType) { - logger.debug("getConfigFile(String filename, String scope, String configType) as getConfigFile("+filename+", "+configType+") called"); - filename = FilenameUtils.removeExtension(filename); - String id = configType; - - if (id != null) { - if (id.equals(ConfigPolicy.JSON_CONFIG) || id.contains("Firewall")) { - filename = filename + ".json"; - } - if (id.equals(ConfigPolicy.XML_CONFIG)) { - filename = filename + ".xml"; - } - if (id.equals(ConfigPolicy.PROPERTIES_CONFIG)) { - filename = filename + ".properties"; - } - if (id.equals(ConfigPolicy.OTHER_CONFIG)) { - filename = filename + ".txt"; - } - } - return filename; - } - - private String[] getNameScopeAndVersionFromPdpPolicy(String fileName){ - String[] splitByDots = fileName.split("\\."); - if(splitByDots.length < 3){ - //should we throw something - return null; - } - String policyName = splitByDots[splitByDots.length-3]; - String version = splitByDots[splitByDots.length-2]; - //policy names now include version - String scope = ""; - for(int i=0;i 0){ - scope = scope.substring(1); - } - String[] returnArray = new String[3]; - returnArray[0] = policyName + "." + version + ".xml"; - returnArray[2] = version; - returnArray[1] = scope; - return returnArray; - } - - //copied from StdEngine.java - public static String createNewPDPGroupId(String name) { - String id = name; - // replace "bad" characters with sequences that will be ok for file names and properties keys. - id = id.replace(" ", "_sp_"); - id = id.replace("\t", "_tab_"); - id = id.replace("\\", "_bksl_"); - id = id.replace("/", "_sl_"); - id = id.replace(":", "_col_"); - id = id.replace("*", "_ast_"); - id = id.replace("?", "_q_"); - id = id.replace("\"", "_quo_"); - id = id.replace("<", "_lt_"); - id = id.replace(">", "_gt_"); - id = id.replace("|", "_bar_"); - id = id.replace("=", "_eq_"); - id = id.replace(",", "_com_"); - id = id.replace(";", "_scom_"); - - return id; - } - - /** - * Checks if any of the given strings are empty or null - * @param strings One or more Strings (or nulls) to check if they are null or empty - * @return true if one or more of the given strings are empty or null - */ - private static boolean isNullOrEmpty(String... strings){ - for(String s : strings){ - if(!(s instanceof String)){ - return true; - } - if(s.equals("")){ - return true; - } - } - return false; - } - - - private class PolicyDBDaoTransactionInstance implements PolicyDBDaoTransaction { - private EntityManager em; - private final Object emLock = new Object(); - long policyId; - long groupId; - long pdpId; - String newGroupId; - private boolean operationRun = false; - private final Thread transactionTimer; - - private PolicyDBDaoTransactionInstance(){ - //call the constructor with arguments - this(Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)), - Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT))); - } - //timeout is how long the transaction can sit before rolling back - //wait time is how long to wait for the transaction to start before throwing an exception - private PolicyDBDaoTransactionInstance(int transactionTimeout, int transactionWaitTime){ - if(logger.isDebugEnabled()){ - logger.debug("\n\nPolicyDBDaoTransactionInstance() as PolicyDBDaoTransactionInstance() called:" - + "\n transactionTimeout = " + transactionTimeout - + "\n transactionWaitTime = " + transactionWaitTime + "\n\n"); - } - this.em = emf.createEntityManager(); - policyId = -1; - groupId = -1; - pdpId = -1; - newGroupId = null; - synchronized(emLock){ - try{ - startTransactionSynced(this.em,transactionWaitTime); - } catch(Exception e){ - throw new PersistenceException("Could not lock transaction within "+transactionWaitTime+" milliseconds"); - } - } - class TransactionTimer implements Runnable { - - private int sleepTime; - public TransactionTimer(int timeout){ - this.sleepTime = timeout; - } - @Override - public void run() { - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nTransactionTimer.run() - SLEEPING: " - + "\n sleepTime (ms) = " + sleepTime - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - try { - Thread.sleep(sleepTime); - } catch (InterruptedException e) { - //probably, the transaction was completed, the last thing we want to do is roll back - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nTransactionTimer.run() - WAKE Interrupt: " - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - return; - } - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nTransactionTimer.run() - WAKE Timeout: " - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - rollbackTransaction(); - } - - } - - transactionTimer = new Thread(new TransactionTimer(transactionTimeout),"transactionTimerThread"); - transactionTimer.start(); - - - } - - private void checkBeforeOperationRun(){ - checkBeforeOperationRun(false); - } - private void checkBeforeOperationRun(boolean justCheckOpen){ - if(!isTransactionOpen()){ - PolicyLogger.error("There is no transaction currently open"); - throw new IllegalStateException("There is no transaction currently open"); - } - if(operationRun && !justCheckOpen){ - PolicyLogger.error("An operation has already been performed and the current transaction should be committed"); - throw new IllegalStateException("An operation has already been performed and the current transaction should be committed"); - } - operationRun = true; - } - @Override - public void commitTransaction() { - synchronized(emLock){ - logger.debug("commitTransaction() as commitTransaction() called"); - if(!isTransactionOpen()){ - logger.warn("There is no open transaction to commit"); - try{ - em.close(); - } catch(Exception e){ - logger.error("Exception Occured"+e); - } - return; - } - try{ - em.getTransaction().commit(); - } catch(RollbackException e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught RollbackException on em.getTransaction().commit()"); - throw new PersistenceException("The commit failed. Message:\n"+e.getMessage()); - } - em.close(); - // need to revisit - if(policyId >= 0){ - if(newGroupId != null){ - try{ - notifyOthers(policyId,POLICY_NOTIFICATION,newGroupId); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on notifyOthers("+policyId+","+POLICY_NOTIFICATION+","+newGroupId+")"); - } - } else { - try{ - notifyOthers(policyId,POLICY_NOTIFICATION); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on notifyOthers("+policyId+","+POLICY_NOTIFICATION+")"); - } - } - } - if(groupId >= 0){ - //we don't want commit to fail just because this does - if(newGroupId != null){ - try{ - notifyOthers(groupId,GROUP_NOTIFICATION,newGroupId); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on notifyOthers("+groupId+","+GROUP_NOTIFICATION+","+newGroupId+")"); - } - } else { - try{ - notifyOthers(groupId,GROUP_NOTIFICATION); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on notifyOthers("+groupId+","+GROUP_NOTIFICATION+")"); - } - } - } - if(pdpId >= 0){ - //we don't want commit to fail just because this does - try{ - notifyOthers(pdpId,PDP_NOTIFICATION); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on notifyOthers("+pdpId+","+PDP_NOTIFICATION+")"); - } - } - } - if(transactionTimer instanceof Thread){ - transactionTimer.interrupt(); - } - } - - @Override - public void rollbackTransaction() { - logger.debug("rollbackTransaction() as rollbackTransaction() called"); - synchronized(emLock){ - if(isTransactionOpen()){ - - try{ - em.getTransaction().rollback(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not rollback transaction"); - } - try{ - em.close(); - }catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not close EntityManager"); - } - - } else { - try{ - em.close(); - }catch(Exception e){ - logger.warn("Could not close already closed transaction"); - } - } - - } - if(transactionTimer instanceof Thread){ - transactionTimer.interrupt(); - } - - - } - - private void createPolicy(PolicyRestAdapter policy, String username, String policyScope, String policyName, String policyDataString) { - logger.debug("createPolicy(PolicyRestAdapter policy, String username, String policyScope, String policyName, String policyDataString) as createPolicy("+policy+", "+username+", "+policyScope+", "+policyName+", "+policyDataString+") called"); - synchronized(emLock){ - checkBeforeOperationRun(); - String configName = policyName; - if(policyName.contains("Config_")){ - policyName = policyName.replace(".Config_", ":Config_"); - }else if(policyName.contains("Action_")){ - policyName = policyName.replace(".Action_", ":Action_"); - }else if(policyName.contains("Decision_")){ - policyName = policyName.replace(".Decision_", ":Decision_"); - } - policyName = policyName.split(":")[1]; - Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName"); - createPolicyQuery.setParameter("scope", policyScope); - createPolicyQuery.setParameter("policyName", policyName); - List createPolicyQueryList = createPolicyQuery.getResultList(); - PolicyEntity newPolicyEntity; - boolean update; - if(createPolicyQueryList.size() < 1){ - newPolicyEntity = new PolicyEntity(); - update = false; - } else if(createPolicyQueryList.size() > 1){ - PolicyLogger.error("Somehow, more than one policy with the same scope, name, and deleted status were found in the database"); - throw new PersistenceException("Somehow, more than one policy with the same scope, name, and deleted status were found in the database"); - } else { - newPolicyEntity = (PolicyEntity)createPolicyQueryList.get(0); - update = true; - } - - ActionBodyEntity newActionBodyEntity = null; - if(policy.getPolicyType().equals("Action")){ - boolean abupdate = false; - if(newPolicyEntity.getActionBodyEntity() == null){ - newActionBodyEntity = new ActionBodyEntity(); - }else{ - newActionBodyEntity = em.find(ActionBodyEntity.class, newPolicyEntity.getActionBodyEntity().getActionBodyId()); - abupdate = true; - } - - if(newActionBodyEntity != null){ - if(!abupdate){ - em.persist(newActionBodyEntity); - } - //build the file path - //trim the .xml off the end - String policyNameClean = FilenameUtils.removeExtension(configName); - String actionBodyName = policyNameClean + ".json"; - Path actionBodyPath = Paths.get(Webapps.getActionHome(), actionBodyName); - if(logger.isDebugEnabled()){ - logger.debug("\nPolicyDBDao.createPolicy" - + "\n actionBodyPath = " + actionBodyPath); - } - //get the action body - String actionBodyString = null; - String actionBodyPathStr = null; - InputStream fileContentStream = null; - - if (Files.exists(actionBodyPath)) { - try { - actionBodyPathStr = (actionBodyPath != null ? actionBodyPath.toString() : null); - fileContentStream = new FileInputStream(actionBodyPathStr); - actionBodyString = IOUtils.toString(fileContentStream); - if(logger.isDebugEnabled()){ - logger.debug("\nPolicyDBDao.createPolicy" - + "\n actionBodyPathStr = " + actionBodyPathStr - + "\n actionBodyString = " + actionBodyString); - } - } catch (FileNotFoundException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught FileNotFoundException on new actionBodyPathStr FileInputStream("+actionBodyPathStr+")"); - throw new IllegalArgumentException("The actionBodyPathStr file path " + actionBodyPathStr + " does not exist" - + "\nEXCEPTION: " + e); - } catch(IOException e2){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "Caught IOException on actionBodyPath newIOUtils.toString("+fileContentStream+")"); - throw new IllegalArgumentException("The actionBodyPath file path cannot be read" + fileContentStream - + "\nEXCEPTION: " + e2); - } finally { - IOUtils.closeQuietly(fileContentStream); - } - - if(actionBodyString == null){ - throw new IllegalArgumentException("The file path (" + actionBodyPathStr + ") cannot be read"); - } - } else { - actionBodyString = "{}"; - } - - newActionBodyEntity.setActionBody(actionBodyString); - newActionBodyEntity.setActionBodyName(actionBodyName); - newActionBodyEntity.setModifiedBy("PolicyDBDao.createPolicy()"); - newActionBodyEntity.setDeleted(false); - if(!abupdate){ - newActionBodyEntity.setCreatedBy("PolicyDBDao.createPolicy()"); - } - if(logger.isDebugEnabled()){ - logger.debug("\nPolicyDBDao.createPolicy" - + "\n newActionBodyEntity.getActionBody() = " + newActionBodyEntity.getActionBody() - + "\n newActionBodyEntity.getActionBodyName() = " + newActionBodyEntity.getActionBodyName() - + "\n newActionBodyEntity.getModifiedBy() = " + newActionBodyEntity.getModifiedBy() - + "\n newActionBodyEntity.getCreatedBy() = " + newActionBodyEntity.getCreatedBy() - + "\n newActionBodyEntity.isDeleted() = " + newActionBodyEntity.isDeleted() - + "\n FLUSHING to DB"); - } - //push the actionBodyEntity to the DB - em.flush(); - }else{ - //newActionBodyEntity == null - //We have a actionBody in the policy but we found no actionBody in the DB - String msg = "\n\nPolicyDBDao.createPolicy - Incoming Action policy had an " - + "actionBody, but it could not be found in the DB for update." - + "\n policyScope = " + policyScope - + "\n policyName = " + policyName + "\n\n"; - PolicyLogger.error("PolicyDBDao.createPolicy - Incoming Action policy had an actionBody, but it could not be found in the DB for update: policyName = " + policyName); - throw new IllegalArgumentException(msg); - } - } - - ConfigurationDataEntity newConfigurationDataEntity; - if(policy.getPolicyType().equals("Config")){ - boolean configUpdate; - if(newPolicyEntity.getConfigurationData() == null){ - newConfigurationDataEntity = new ConfigurationDataEntity(); - configUpdate = false; - } else { - newConfigurationDataEntity = em.find(ConfigurationDataEntity.class, newPolicyEntity.getConfigurationData().getConfigurationDataId()); - configUpdate = true; - } - - if(newConfigurationDataEntity != null){ - if(!configUpdate){ - em.persist(newConfigurationDataEntity); - } - if(!stringEquals(newConfigurationDataEntity.getConfigurationName(),getConfigFile(configName,policy))){ - newConfigurationDataEntity.setConfigurationName(getConfigFile(configName,policy)); - } - if(newConfigurationDataEntity.getConfigType() == null || !newConfigurationDataEntity.getConfigType().equals(policy.getConfigType())){ - newConfigurationDataEntity.setConfigType(policy.getConfigType()); - } - if(!configUpdate){ - newConfigurationDataEntity.setCreatedBy(username); - } - if(newConfigurationDataEntity.getModifiedBy() == null || !newConfigurationDataEntity.getModifiedBy().equals(username)){ - newConfigurationDataEntity.setModifiedBy(username); - } - if(newConfigurationDataEntity.getDescription() == null || !newConfigurationDataEntity.getDescription().equals("")){ - newConfigurationDataEntity.setDescription(""); - } - if(newConfigurationDataEntity.getConfigBody() == null || newConfigurationDataEntity.getConfigBody().isEmpty() || - (!newConfigurationDataEntity.getConfigBody().equals(policy.getConfigBodyData()))){ - //hopefully one of these won't be null - if(policy.getConfigBodyData() == null || policy.getConfigBodyData().isEmpty()){ - newConfigurationDataEntity.setConfigBody(policy.getJsonBody()); - }else{ - newConfigurationDataEntity.setConfigBody(policy.getConfigBodyData()); - } - } - if(newConfigurationDataEntity.isDeleted() == true){ - newConfigurationDataEntity.setDeleted(false); - } - - em.flush(); - }else{ - //We have a configurationData body in the policy but we found no configurationData body in the DB - String msg = "\n\nPolicyDBDao.createPolicy - Incoming Config policy had a " - + "configurationData body, but it could not be found in the DB for update." - + "\n policyScope = " + policyScope - + "\n policyName = " + policyName + "\n\n"; - PolicyLogger.error("PolicyDBDao.createPolicy - Incoming Config policy had a configurationData body, but it could not be found in the DB for update: policyName = " + policyName); - throw new IllegalArgumentException(msg); - } - - } else { - newConfigurationDataEntity = null; - } - if(!update){ - em.persist(newPolicyEntity); - } - - policyId = newPolicyEntity.getPolicyId(); - - if(!stringEquals(newPolicyEntity.getPolicyName(),policyName)){ - newPolicyEntity.setPolicyName(policyName); - } - if(!stringEquals(newPolicyEntity.getCreatedBy(),username)){ - newPolicyEntity.setCreatedBy(username); - } - if(!stringEquals(newPolicyEntity.getDescription(),policy.getPolicyDescription())){ - newPolicyEntity.setDescription(policy.getPolicyDescription()); - } - if(!stringEquals(newPolicyEntity.getModifiedBy(),username)){ - newPolicyEntity.setModifiedBy(username); - } - if(!stringEquals(newPolicyEntity.getPolicyData(),policyDataString)){ - newPolicyEntity.setPolicyData(policyDataString); - } - if(!stringEquals(newPolicyEntity.getScope(),policyScope)){ - newPolicyEntity.setScope(policyScope); - } - if(newPolicyEntity.isDeleted() == true){ - newPolicyEntity.setDeleted(false); - } - newPolicyEntity.setConfigurationData(newConfigurationDataEntity); - newPolicyEntity.setActionBodyEntity(newActionBodyEntity); - - - em.flush(); - this.policyId = newPolicyEntity.getPolicyId(); - } - - return; - } - - @SuppressWarnings("unused") - public PolicyEntity getPolicy(int policyID){ - return getPolicy(policyID,null,null); - } - public PolicyEntity getPolicy(String policyName,String scope){ - return getPolicy(-1,policyName,scope); - } - private PolicyEntity getPolicy(int policyID, String policyName,String scope){ - logger.debug("getPolicy(int policyId, String policyName) as getPolicy("+policyID+","+policyName+") called"); - if(policyID < 0 && isNullOrEmpty(policyName,scope)){ - throw new IllegalArgumentException("policyID must be at least 0 or policyName must be not null or blank"); - } - - synchronized(emLock){ - checkBeforeOperationRun(true); - //check if group exists - String policyId; - Query policyQuery; - if(!isNullOrEmpty(policyName,scope)){ - policyId = policyName; - policyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope"); - policyQuery.setParameter("name", policyId); - policyQuery.setParameter("scope", scope); - } else{ - policyId = String.valueOf(policyID); - policyQuery = em.createNamedQuery("PolicyEntity.FindById"); - policyQuery.setParameter("id", policyId); - } - List policyQueryList; - try{ - policyQueryList = policyQuery.getResultList(); - }catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get policy with policyQuery.getResultList()"); - throw new PersistenceException("Query failed trying to get policy "+policyId); - } - if(policyQueryList.size() < 1){ - PolicyLogger.error("Policy does not exist with id "+policyId); - throw new PersistenceException("Group policy is being added to does not exist with id "+policyId); - } else if(policyQueryList.size() > 1){ - PolicyLogger.error("Somehow, more than one policy with the id "+policyId+" were found in the database"); - throw new PersistenceException("Somehow, more than one policy with the id "+policyId+" were found in the database"); - } - return (PolicyEntity)policyQueryList.get(0); - } - } - - @Override - public void renamePolicy(String oldPath, String newPath,String username){ -/* String[] oldPolicy = getScopeAndNameAndType(oldPath); - String[] newPolicy = getScopeAndNameAndType(newPath); - if(oldPolicy == null || newPolicy == null){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW+"Could not parse one or more of the path names: " - +oldPath+", "+newPath); - throw new IllegalArgumentException("Could not parse one or more of the path names"); - } - synchronized (emLock) { - checkBeforeOperationRun(); - - PolicyEntity existingPolicy; - boolean existingPolicyDeleted = false; - List groups = null; - try{ - existingPolicy = getPolicy(newPolicy[1],newPolicy[0]); - } catch(Exception e){ - existingPolicy = null; - } - if(existingPolicy != null && !existingPolicy.isDeleted()){ - logger.error("The policy named "+existingPolicy.getPolicyName()+" already exists, cannot rename policy: "+newPolicy); - throw new IllegalArgumentException("The policy named "+existingPolicy.getPolicyName()+" already exists, cannot rename policy: "+newPolicy); - } else if(existingPolicy != null && existingPolicy.isDeleted()){ - try{ - Query getGroups = em.createQuery("SELECT g FROM GroupEntity g JOIN g.policies p WHERE p.policyId=:pid"); - - getGroups.setParameter("pid", existingPolicy.getPolicyId()); - groups = getGroups.getResultList(); - }catch(Exception e){ - groups = new LinkedList<>(); - } - for(Object o : groups){ - GroupEntity group = (GroupEntity)o; - group.removePolicyFromGroup(existingPolicy); - } - try{ - em.flush(); - }catch(Exception e){ - logger.error("Error while removing the policy from groups: "+existingPolicy.getPolicyName()); - } - try{ - em.remove(existingPolicy); - em.flush(); - }catch(Exception e){ - logger.error("Could not remove the existing deleted policy: "+existingPolicy.getPolicyName()); - } - existingPolicyDeleted = true; - //create the new policy - //for each of the groups, add the new policy - } - - PolicyEntity policyToRename; - try{ - policyToRename = getPolicy(oldPolicy[1],oldPolicy[0]); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "PolicyDBDao", "Could not get policy record to rename: " - +oldPolicy[1]); - throw new PersistenceException("Could not get policy record to rename"); - } - String policyDataString = null; - InputStream fileContentStream = null; - String policyFilePath = Paths.get(oldPath).toAbsolutePath().toString(); - //I want to try the old path first, then if it doesn't work, try the new path - for(int i=0;i<2;i++){ - try { - fileContentStream = new FileInputStream(policyFilePath); - policyDataString = IOUtils.toString(fileContentStream); - } catch (FileNotFoundException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught FileNotFoundException on new FileInputStream("+policyFilePath+")"); - //if we can't find the oldPath, we'll try the new path - if(i == 0){ - policyFilePath = Paths.get(newPath).toAbsolutePath().toString(); - continue; - } - throw new IllegalArgumentException("The file path does not exist"); - } catch(IOException e2){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "Caught IOException on newIOUtils.toString("+fileContentStream+")"); - throw new IllegalArgumentException("The file path cannot be read"); - } finally { - IOUtils.closeQuietly(fileContentStream); - } - if(policyDataString == null){ - throw new IllegalArgumentException("The file path cannot be read"); - } - //escape the loop - i=2; - } - policyToRename.setPolicyName(newPolicy[1]); - policyToRename.setPolicyData(policyDataString); - policyToRename.setScope(newPolicy[0]); - policyToRename.setModifiedBy(username); - if(policyToRename.getConfigurationData() != null){ - String configType = policyToRename.getConfigurationData().getConfigType(); - policyToRename.getConfigurationData().setConfigurationName(getConfigFile(newPolicy[1], configType)); - policyToRename.getConfigurationData().setModifiedBy(username); - } - if(policyToRename.getActionBodyEntity() != null){ - String newActionName = newPolicy[0]+"."+removeFileExtension(newPolicy[1])+".json"; - policyToRename.getActionBodyEntity().setActionBodyName(newActionName); - policyToRename.getActionBodyEntity().setModifiedBy(username); - } - if(existingPolicyDeleted){ - for(Object o : groups){ - - GroupEntity group = (GroupEntity)o; - group.addPolicyToGroup(policyToRename); - } - } - em.flush(); - this.policyId = policyToRename.getPolicyId(); - this.newGroupId = oldPath; - }*/ - } - - @Override - public GroupEntity getGroup(long groupKey){ - logger.debug("getGroup(int groupKey) as getGroup("+groupKey+") called"); - if(groupKey < 0){ - throw new IllegalArgumentException("groupKey must be at least 0"); - } - synchronized(emLock){ - checkBeforeOperationRun(true); - //check if group exists - Query groupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupKey=:groupKey"); - groupQuery.setParameter("groupKey", groupKey); - List groupQueryList; - try{ - groupQueryList = groupQuery.getResultList(); - }catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get group with groupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to get group "+groupKey); - } - if(groupQueryList.size() < 1){ - PolicyLogger.error("Group does not exist with groupKey "+groupKey); - throw new PersistenceException("Group does not exist with groupKey "+groupKey); - } else if(groupQueryList.size() > 1){ - PolicyLogger.error("Somehow, more than one group with the groupKey "+groupKey+" were found in the database"); - throw new PersistenceException("Somehow, more than one group with the groupKey "+groupKey+" were found in the database"); - } - return (GroupEntity)groupQueryList.get(0); - } - } - - @Override - public GroupEntity getGroup(String groupId){ - logger.debug("getGroup(String groupId) as getGroup("+groupId+") called"); - if(isNullOrEmpty(groupId)){ - throw new IllegalArgumentException("groupId must not be null or empty"); - } - synchronized(emLock){ - checkBeforeOperationRun(true); - //check if group exists - Query groupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId"); - groupQuery.setParameter("groupId", groupId); - List groupQueryList; - try{ - groupQueryList = groupQuery.getResultList(); - }catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get group with groupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to get group "+groupId); - } - if(groupQueryList.size() < 1){ - PolicyLogger.error("Group does not exist with id "+groupId); - throw new PersistenceException("Group does not exist with id "+groupId); - } else if(groupQueryList.size() > 1){ - PolicyLogger.error("Somehow, more than one group with the id "+groupId+" were found in the database"); - throw new PersistenceException("Somehow, more than one group with the id "+groupId+" were found in the database"); - } - return (GroupEntity)groupQueryList.get(0); - } - } - @Override - public List getPdpsInGroup(long groupKey){ - logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup("+groupKey+") called"); - if(groupKey < 0){ - throw new IllegalArgumentException("groupId must not be < 0"); - } - synchronized(emLock){ - checkBeforeOperationRun(true); - Query pdpsQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group"); - pdpsQuery.setParameter("group", getGroup(groupKey)); - return pdpsQuery.getResultList(); - } - } - @Override - public PdpEntity getPdp(long pdpKey){ - logger.debug("getPdp(int pdpKey) as getPdp("+pdpKey+") called"); - if(pdpKey < 0){ - throw new IllegalArgumentException("pdpKey must be at least 0"); - } - synchronized(emLock){ - checkBeforeOperationRun(true); - //check if group exists - Query pdpQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpKey=:pdpKey"); - pdpQuery.setParameter("pdpKey", pdpKey); - List pdpQueryList; - try{ - pdpQueryList = pdpQuery.getResultList(); - }catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get pdp with pdpQuery.getResultList()"); - throw new PersistenceException("Query failed trying to get pdp "+pdpKey); - } - if(pdpQueryList.size() < 1){ - PolicyLogger.error("Pdp does not exist with pdpKey "+pdpKey); - throw new PersistenceException("Pdp does not exist with pdpKey "+pdpKey); - } else if(pdpQueryList.size() > 1){ - PolicyLogger.error("Somehow, more than one pdp with the pdpKey "+pdpKey+" were found in the database"); - throw new PersistenceException("Somehow, more than one pdp with the pdpKey "+pdpKey+" were found in the database"); - } - return (PdpEntity)pdpQueryList.get(0); - } - } - - public void deletePolicy(String policyToDeletes){ - /*synchronized(emLock){ - checkBeforeOperationRun(); - logger.debug("deletePolicy(String policyToDeletes) as deletePolicy("+policyToDeletes+") called"); - String[] scopeNameAndType = getScopeAndNameAndType(policyToDeletes); - if(scopeNameAndType == null){ - throw new IllegalArgumentException("Could not parse file path"); - } - String realScope = scopeNameAndType[0]; - String realName = scopeNameAndType[1]; - Query deletePolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName AND p.deleted=:deleted"); - deletePolicyQuery.setParameter("scope",realScope); - deletePolicyQuery.setParameter("policyName", realName); - deletePolicyQuery.setParameter("deleted", false); - List deletePolicyQueryList = deletePolicyQuery.getResultList(); - if(deletePolicyQueryList.size() < 1){ - logger.warn("The policy being deleted could not be found."); - return; - } else if(deletePolicyQueryList.size() > 1){ - PolicyLogger.error("Somehow, more than one policy with the same scope, name, and deleted status were found in the database"); - throw new PersistenceException("Somehow, more than one policy with the same scope, name, and deleted status were found in the database"); - } else { - PolicyEntity policyToDelete = (PolicyEntity)deletePolicyQueryList.get(0); - policyToDelete.setDeleted(true); - if(policyToDelete.getConfigurationData() != null){ - ConfigurationDataEntity cde = em.find(ConfigurationDataEntity.class,policyToDelete.getConfigurationData().getConfigurationDataId()); - if(cde != null){ - cde.setDeleted(true); - } - } - if(policyToDelete.getActionBodyEntity() != null){ - ActionBodyEntity abe = em.find(ActionBodyEntity.class,policyToDelete.getActionBodyEntity().getActionBodyId()); - if(abe != null){ - abe.setDeleted(true); - } - } - - em.flush(); - this.policyId = policyToDelete.getPolicyId(); - - } - } -*/ - } - - - @Override - public boolean isTransactionOpen() { - logger.debug("isTransactionOpen() as isTransactionOpen() called"); - synchronized(emLock){ - return em.isOpen() && em.getTransaction().isActive(); - } - } - - - @Override - public void clonePolicy(String oldPolicyPath, String newPolicyPath, String username){ - /*String[] oldPolicyData = getScopeAndNameAndType(oldPolicyPath); - String[] newPolicyData = getScopeAndNameAndType(newPolicyPath); - if(oldPolicyData == null || newPolicyData == null){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW+"Could not parse one or more of the path names: " - +oldPolicyPath+", "+newPolicyPath); - throw new IllegalArgumentException("Could not parse the oldPolicyPath or newPolicyPath"); - } - PolicyEntity oldPolicy; - try{ - oldPolicy = getPolicy(oldPolicyData[1],oldPolicyData[0]); - }catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "PolicyDBDao", "Could not get policy record to clone: " - +oldPolicyData[1]); - throw new PersistenceException("Could not get policy record to clone"); - } - ConfigurationDataEntity clonedConfig = null; - if(oldPolicy.getConfigurationData() != null){ - clonedConfig = new ConfigurationDataEntity(); - em.persist(clonedConfig); - clonedConfig.setConfigBody(oldPolicy.getConfigurationData().getConfigBody()); - clonedConfig.setConfigType(oldPolicy.getConfigurationData().getConfigType()); - clonedConfig.setCreatedBy(username); - clonedConfig.setConfigurationName(getConfigFile(newPolicyData[1], oldPolicy.getConfigurationData().getConfigType())); - clonedConfig.setDescription(oldPolicy.getConfigurationData().getDescription()); - clonedConfig.setModifiedBy(username); - em.flush(); - } - ActionBodyEntity clonedAction = null; - if(oldPolicy.getActionBodyEntity() != null){ - clonedAction = new ActionBodyEntity(); - em.persist(clonedAction); - clonedAction.setActionBody(oldPolicy.getActionBodyEntity().getActionBody()); - clonedAction.setActionBodyName(newPolicyData[0]+"."+newPolicyData[1]+".json"); - clonedAction.setCreatedBy(username); - clonedAction.setModifiedBy(username); - em.flush(); - } - -*/ - } - - private String processConfigPath(String configPath){ - String webappsPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS); - if(webappsPath == null){ - logger.error("Webapps property does not exist"); - throw new IllegalArgumentException("Webapps property does not exist"); - } - configPath = configPath.replace("$URL", webappsPath); - //make sure the correct slashes are in - try{ - configPath = Paths.get(configPath).toString(); - } catch(InvalidPathException e){ - logger.error("Invalid config path: "+configPath); - throw new IllegalArgumentException("Invalid config path: "+configPath); - } - return configPath; - } - private String readConfigFile(String configPath){ - String configDataString = null; - InputStream configContentStream = null; - try { - configContentStream = new FileInputStream(configPath); - configDataString = IOUtils.toString(configContentStream); - } catch (FileNotFoundException e) { - logger.error("Caught FileNotFoundException on new FileInputStream("+configPath+")",e); - throw new IllegalArgumentException("The config file path does not exist"); - } catch(IOException e2){ - logger.error("Caught IOException on newIOUtils.toString("+configContentStream+")",e2); - throw new IllegalArgumentException("The config file path cannot be read"); - } finally { - IOUtils.closeQuietly(configContentStream); - } - if(configDataString == null){ - throw new IllegalArgumentException("The config file path cannot be read"); - } - return configDataString; - } - - @Override - public void createPolicy(Policy policy, String username){ - InputStream policyXmlStream = null; - try{ - logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy("+policy+","+username+") called"); - String policyScope = policy.policyAdapter.getDomainDir().replace(File.separator, "."); - //Does not need to be XACMLPolicyWriterWithPapNotify since it is already in the PAP - //and this transaction is intercepted up stream. - String policyDataString; - try { - policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream((PolicyType)policy.getCorrectPolicyDataObject()); - policyDataString = IOUtils.toString(policyXmlStream); - } catch (IOException e) { - policyDataString = "could not read"; - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught IOException on IOUtils.toString("+policyXmlStream+")"); - throw new IllegalArgumentException("Cannot parse the policy xml from the PolicyRestAdapter."); - } - IOUtils.closeQuietly(policyXmlStream); - String configPath = ""; - if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Config")) { - configPath = evaluateXPath("/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()", policyDataString); - } else if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Action")) { - configPath = evaluateXPath("/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, " +policy.policyAdapter.getActionAttribute()+ ")]/AttributeAssignmentExpression[@AttributeId='body']/AttributeValue/text()", policyDataString); - } - - String prefix = null; - if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Config")) { - - prefix = configPath.substring(configPath.indexOf(policyScope+".")+policyScope.concat(".").length(), configPath.indexOf(policy.policyAdapter.getPolicyName())); - if(isNullOrEmpty(policy.policyAdapter.getConfigBodyData())){ - String configData = ""; - try{ - String newConfigPath = configPath; - try{ - newConfigPath = processConfigPath(newConfigPath); - }catch(Exception e2){ - logger.error("Could not process config path: "+newConfigPath,e2); - } - configData = readConfigFile(newConfigPath); - }catch(Exception e){ - logger.error("Could not read config body data for "+configPath,e); - } - policy.policyAdapter.setConfigBodyData(configData); - } - } else if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Action")) { - prefix = "Action_"; - } else if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Decision")) { - prefix = "Decision_"; - } - - if(!(policy.policyAdapter.getData() instanceof PolicyType)){ - PolicyLogger.error("The data field is not an instance of PolicyType"); - throw new IllegalArgumentException("The data field is not an instance of PolicyType"); - } - String finalName = policyScope + "." + prefix+policy.policyAdapter.getPolicyName()+"."+((PolicyType)policy.policyAdapter.getData()).getVersion()+".xml"; - if(policy.policyAdapter.getConfigType() == null || policy.policyAdapter.getConfigType().equals("")){ - //get the config file extension - String ext = ""; - if (configPath != null) { - if (!configPath.equalsIgnoreCase("")) { - ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length());; - } - } - - if(ext.contains("txt")){ - policy.policyAdapter.setConfigType(OTHER_CONFIG); - } else if(ext.contains("json")){ - policy.policyAdapter.setConfigType(JSON_CONFIG); - } else if(ext.contains("xml")){ - policy.policyAdapter.setConfigType(XML_CONFIG); - } else if(ext.contains("properties")){ - policy.policyAdapter.setConfigType(PROPERTIES_CONFIG); - } else { - if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Action")){ - policy.policyAdapter.setConfigType(JSON_CONFIG); - } - } - } - - createPolicy(policy.policyAdapter, username, policyScope,finalName,policyDataString); - }finally{ - if(policyXmlStream != null){ - try { - policyXmlStream.close(); - } catch (IOException e) { - logger.error("Exception Occured while closing input stream"+e); - } - } - } - } - - @Override - public void close(){ - synchronized(emLock){ - if(em.isOpen()){ - if(em.getTransaction().isActive()){ - em.getTransaction().rollback(); - } - em.close(); - } - if(transactionTimer instanceof Thread){ - transactionTimer.interrupt(); - } - } - } - - - - @Override - public void createGroup(String groupId, String groupName, String groupDescription, String username) { - logger.debug("deletePolicy(String policyToDeletes) as createGroup("+groupId+", "+groupName+", "+groupDescription+") called"); - if(isNullOrEmpty(groupId, groupName, username)){ - throw new IllegalArgumentException("groupId, groupName, and username must not be null or empty"); - } - if(!(groupDescription instanceof String)){ - groupDescription = ""; - } - - synchronized(emLock){ - checkBeforeOperationRun(); - Query checkGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - checkGroupQuery.setParameter("groupId", groupId); - checkGroupQuery.setParameter("deleted", false); - List checkGroupQueryList; - try{ - checkGroupQueryList = checkGroupQuery.getResultList(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on checkGroupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check for existing group"); - } - if(checkGroupQueryList.size() > 0){ - PolicyLogger.error("The group being added already exists with id "+groupId); - throw new PersistenceException("The group being added already exists with id "+groupId); - } - GroupEntity newGroup = new GroupEntity(); - em.persist(newGroup); - newGroup.setCreatedBy(username); - newGroup.setModifiedBy(username); - newGroup.setGroupName(groupName); - newGroup.setGroupId(groupId); - newGroup.setDescription(groupDescription); - - em.flush(); - this.groupId = newGroup.getGroupKey(); - } - } - - @Override - public void updateGroup(EcompPDPGroup group, String username){ - logger.debug("updateGroup(PDPGroup group) as updateGroup("+group+","+username+") called"); - if(group == null){ - throw new IllegalArgumentException("PDPGroup group must not be null"); - } - if(isNullOrEmpty(group.getId(), username)){ - throw new IllegalArgumentException("group.getId() and username must not be null or empty"); - } - - synchronized(emLock){ - checkBeforeOperationRun(); - Query getGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - getGroupQuery.setParameter("groupId", group.getId()); - getGroupQuery.setParameter("deleted", false); - List getGroupQueryList; - try{ - getGroupQueryList = getGroupQuery.getResultList(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on getGroupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to get group "+group.getId()+" for editing"); - } - if(getGroupQueryList.size() < 1){ - PolicyLogger.error("The group cannot be found to update with id "+group.getId()); - throw new PersistenceException("The group cannot be found to update with id "+group.getId()); - } else if(getGroupQueryList.size() > 1){ - PolicyLogger.error("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database"); - throw new PersistenceException("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database"); - } - GroupEntity groupToUpdate = (GroupEntity)getGroupQueryList.get(0); - if(!stringEquals(groupToUpdate.getModifiedBy(), username)){ - groupToUpdate.setModifiedBy(username); - } - if(group.getDescription() != null && !stringEquals(group.getDescription(),groupToUpdate.getDescription())){ - groupToUpdate.setDescription(group.getDescription()); - } - //let's find out what policies have been deleted - StdPDPGroup oldGroup = null; - try { - oldGroup = (StdPDPGroup) papEngine.getGroup(group.getId()); - } catch (PAPException e1) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "We cannot get the group from the papEngine to delete policies"); - } - if(oldGroup == null){ - PolicyLogger.error("We cannot get the group from the papEngine to delete policies"); - } else { - - Set newPolicySet = new HashSet<>(group.getPolicies().size()); - //a multiple of n runtime is faster than n^2, so I am using a hashset to do the comparison - for(PDPPolicy pol: group.getPolicies()){ - newPolicySet.add(pol.getId()); - } - for(PDPPolicy pol : oldGroup.getPolicies()){ - //should be fast since getPolicies uses a HashSet in StdPDPGroup - if(!newPolicySet.contains(pol.getId())){ - String[] scopeAndName = getNameScopeAndVersionFromPdpPolicy(pol.getId()); - PolicyEntity policyToDelete; - try{ - policyToDelete = getPolicy(scopeAndName[0],scopeAndName[1]); - }catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not get policy to remove: "+pol.getId()); - throw new PersistenceException("Could not get policy to remove: "+pol.getId()); - } - groupToUpdate.getPolicies().remove(policyToDelete); - - } - } - } - if(group.getName() != null && !stringEquals(group.getName(),groupToUpdate.getgroupName())){ - //we need to check if the new id exists in the database - String newGroupId = createNewPDPGroupId(group.getName()); - Query checkGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - checkGroupQuery.setParameter("groupId", newGroupId); - checkGroupQuery.setParameter("deleted", false); - List checkGroupQueryList; - try{ - checkGroupQueryList = checkGroupQuery.getResultList(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on checkGroupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check for existing group"); - } - if(checkGroupQueryList.size() != 0){ - PolicyLogger.error("The new group name already exists, group id "+newGroupId); - throw new PersistenceException("The new group name already exists, group id "+newGroupId); - } - groupToUpdate.setGroupId(newGroupId); - groupToUpdate.setGroupName(group.getName()); - this.newGroupId = group.getId(); - } - - em.flush(); - this.groupId = groupToUpdate.getGroupKey(); - } - } - - @Override - public void addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, String username) { - logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup("+pdpID+", "+groupID+", "+pdpName+", "+pdpDescription+", "+pdpJmxPort+", "+username+") called"); - if(isNullOrEmpty(pdpID, groupID,pdpName,username)){ - throw new IllegalArgumentException("pdpID, groupID, pdpName, and username must not be null or empty"); - } - if(!(pdpDescription instanceof String)){ - pdpDescription = ""; - } - synchronized(emLock){ - checkBeforeOperationRun(); - Query checkGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - checkGroupQuery.setParameter("groupId", groupID); - checkGroupQuery.setParameter("deleted", false); - List checkGroupQueryList; - try{ - checkGroupQueryList = checkGroupQuery.getResultList(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check for existing group on checkGroupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check for existing group"); - } - if(checkGroupQueryList.size() != 1){ - PolicyLogger.error("The group does not exist"); - throw new PersistenceException("The group does not exist"); - } - Query checkDuplicateQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); - checkDuplicateQuery.setParameter("pdpId", pdpID); - checkDuplicateQuery.setParameter("deleted", false); - List checkDuplicateList; - try{ - checkDuplicateList = checkDuplicateQuery.getResultList(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check for duplicate PDP "+pdpID+" on checkDuplicateQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check for duplicate PDP "+pdpID); - } - PdpEntity newPdp; - if(checkDuplicateList.size() > 0){ - logger.warn("PDP already exists with id "+pdpID); - newPdp = (PdpEntity)checkDuplicateList.get(0); - } else { - newPdp = new PdpEntity(); - em.persist(newPdp); - } - - newPdp.setCreatedBy(username); - newPdp.setDeleted(false); - newPdp.setDescription(pdpDescription); - newPdp.setGroup((GroupEntity)checkGroupQueryList.get(0)); - newPdp.setJmxPort(pdpJmxPort); - newPdp.setModifiedBy(username); - newPdp.setPdpId(pdpID); - newPdp.setPdpName(pdpName); - - em.flush(); - this.pdpId = newPdp.getPdpKey(); - - } - } - - - @Override - public void updatePdp(EcompPDP pdp, String username){ - logger.debug("updatePdp(PDP pdp, String username) as updatePdp("+pdp+","+username+") called"); - if(pdp == null){ - throw new IllegalArgumentException("PDP pdp must not be null"); - } - if(isNullOrEmpty(pdp.getId(),username)){ - throw new IllegalArgumentException("pdp.getId() and username must not be null or empty"); - } - - synchronized(emLock){ - checkBeforeOperationRun(); - Query getPdpQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); - getPdpQuery.setParameter("pdpId", pdp.getId()); - getPdpQuery.setParameter("deleted", false); - List getPdpQueryList; - try{ - getPdpQueryList = getPdpQuery.getResultList(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on getPdpQuery.getResultList()"); - throw new PersistenceException("Query failed trying to get PDP "+pdp.getId()); - } - if(getPdpQueryList.size() < 1){ - PolicyLogger.error("The pdp cannot be found to update with id "+pdp.getId()); - throw new PersistenceException("The pdp cannot be found to update with id "+pdp.getId()); - } else if(getPdpQueryList.size() > 1){ - PolicyLogger.error("Somehow, more than one pdp with the same id "+pdp.getId()+" and deleted status were found in the database"); - throw new PersistenceException("Somehow, more than one pdp with the same id "+pdp.getId()+" and deleted status were found in the database"); - } - PdpEntity pdpToUpdate = (PdpEntity)getPdpQueryList.get(0); - if(!stringEquals(pdpToUpdate.getModifiedBy(), username)){ - pdpToUpdate.setModifiedBy(username); - } - if(pdp.getDescription() != null && !stringEquals(pdp.getDescription(),pdpToUpdate.getDescription())){ - pdpToUpdate.setDescription(pdp.getDescription()); - } - if(pdp.getName() != null && !stringEquals(pdp.getName(),pdpToUpdate.getPdpName())){ - pdpToUpdate.setPdpName(pdp.getName()); - } - if(pdp.getJmxPort() != null && !pdp.getJmxPort().equals(pdpToUpdate.getJmxPort())){ - pdpToUpdate.setJmxPort(pdp.getJmxPort()); - } - - em.flush(); - this.pdpId = pdpToUpdate.getPdpKey(); - } - } - - @Override - public void movePdp(EcompPDP pdp, EcompPDPGroup group, String username){ - logger.debug("movePdp(PDP pdp, PDPGroup group, String username) as movePdp("+pdp+","+group+","+username+") called"); - if(pdp == null || group == null){ - throw new IllegalArgumentException("PDP pdp and PDPGroup group must not be null"); - } - if(isNullOrEmpty(username,pdp.getId(),group.getId())){ - throw new IllegalArgumentException("pdp.getId(), group.getId(), and username must not be null or empty"); - } - - synchronized(emLock){ - checkBeforeOperationRun(); - //check if pdp exists - Query getPdpQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); - getPdpQuery.setParameter("pdpId", pdp.getId()); - getPdpQuery.setParameter("deleted", false); - List getPdpQueryList; - try{ - getPdpQueryList = getPdpQuery.getResultList(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on getPdpQuery.getResultList()"); - throw new PersistenceException("Query failed trying to get pdp to move with id "+pdp.getId()); - } - if(getPdpQueryList.size() < 1){ - PolicyLogger.error("The pdp cannot be found to move with id "+pdp.getId()); - throw new PersistenceException("The pdp cannot be found to move with id "+pdp.getId()); - } else if(getPdpQueryList.size() > 1){ - PolicyLogger.error("Somehow, more than one pdp with the same id "+pdp.getId()+" and deleted status were found in the database"); - throw new PersistenceException("Somehow, more than one pdp with the same id "+pdp.getId()+" and deleted status were found in the database"); - } - - //check if new group exists - Query checkGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - checkGroupQuery.setParameter("groupId", group.getId()); - checkGroupQuery.setParameter("deleted", false); - List checkGroupQueryList; - try{ - checkGroupQueryList = checkGroupQuery.getResultList(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get group on checkGroupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to get new group "+group.getId()); - } - if(checkGroupQueryList.size() != 1){ - PolicyLogger.error("The group "+group.getId()+" does not exist"); - throw new PersistenceException("The group "+group.getId()+" does not exist"); - } - GroupEntity groupToMoveInto = (GroupEntity)checkGroupQueryList.get(0); - PdpEntity pdpToUpdate = (PdpEntity)getPdpQueryList.get(0); - pdpToUpdate.setGroup(groupToMoveInto); - if(!stringEquals(pdpToUpdate.getModifiedBy(), username)){ - pdpToUpdate.setModifiedBy(username); - } - - em.flush(); - this.pdpId = pdpToUpdate.getPdpKey(); - } - } - - @Override - public void changeDefaultGroup(EcompPDPGroup group, String username){ - logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup("+group+","+username+") called"); - if(group == null){ - throw new IllegalArgumentException("PDPGroup group must not be null"); - } - if(isNullOrEmpty(group.getId(),username)){ - throw new IllegalArgumentException("group.getId() and username must not be null or empty"); - } - - synchronized(emLock){ - checkBeforeOperationRun(); - Query getGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - getGroupQuery.setParameter("groupId", group.getId()); - getGroupQuery.setParameter("deleted", false); - List getGroupQueryList; - try{ - getGroupQueryList = getGroupQuery.getResultList(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on getGroupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to get group "+group.getId()); - } - if(getGroupQueryList.size() < 1){ - PolicyLogger.error("The group cannot be found to set default with id "+group.getId()); - throw new PersistenceException("The group cannot be found to set default with id "+group.getId()); - } else if(getGroupQueryList.size() > 1){ - PolicyLogger.error("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database"); - throw new PersistenceException("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database"); - } - GroupEntity newDefaultGroup = (GroupEntity)getGroupQueryList.get(0); - newDefaultGroup.setDefaultGroup(true); - if(!stringEquals(newDefaultGroup.getModifiedBy(), username)){ - newDefaultGroup.setModifiedBy(username); - } - - em.flush(); - this.groupId = newDefaultGroup.getGroupKey(); - Query setAllGroupsNotDefault = em.createQuery("UPDATE GroupEntity g SET g.defaultGroup=:defaultGroup WHERE g.deleted=:deleted AND g.groupKey<>:groupKey"); - //not going to set modified by for all groups - setAllGroupsNotDefault.setParameter("defaultGroup", false); - setAllGroupsNotDefault.setParameter("deleted", false); - setAllGroupsNotDefault.setParameter("groupKey", newDefaultGroup.getGroupKey()); - try{ - logger.info("set " + setAllGroupsNotDefault.executeUpdate() + " groups as not default"); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on setAllGroupsNotDefault.executeUpdate()"); - throw new PersistenceException("Could not set all other groups default to false"); - } - - em.flush(); - } - } - - - @Override - public void deleteGroup(EcompPDPGroup group, EcompPDPGroup moveToGroup, String username) throws PAPException { - logger.debug("deleteGroup(PDPGroup group, PDPGroup moveToGroup, String username) as deleteGroup("+group+", "+moveToGroup+","+username+") called"); - if(group == null){ - throw new IllegalArgumentException("PDPGroup group cannot be null"); - } - if(isNullOrEmpty(username,group.getId())){ - throw new IllegalArgumentException("group.getId() and and username must not be null or empty"); - } - - if(group.isDefaultGroup()){ - PolicyLogger.error("The default group "+group.getId()+" was attempted to be deleted. It cannot be."); - throw new PAPException("You cannot delete the default group."); - } - synchronized(emLock){ - checkBeforeOperationRun(); - Query deleteGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - deleteGroupQuery.setParameter("groupId", group.getId()); - deleteGroupQuery.setParameter("deleted", false); - List deleteGroupQueryList; - try{ - deleteGroupQueryList = deleteGroupQuery.getResultList(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if group exists deleteGroupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check if group exists"); - } - if(deleteGroupQueryList.size() < 1){ - logger.warn("The group could not be found with id " + group.getId()); - return; - } else if(deleteGroupQueryList.size() > 1){ - PolicyLogger.error("Somehow, more than one group with the id "+group.getId()+" were found in the database that are not deleted"); - throw new PersistenceException("Somehow, more than one group with the id "+group.getId()+" were found in the database that are not deleted"); - } - - Query pdpsInGroupQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group and p.deleted=:deleted"); - pdpsInGroupQuery.setParameter("group", ((GroupEntity)deleteGroupQueryList.get(0))); - pdpsInGroupQuery.setParameter("deleted", false); - List pdpsInGroupList; - try{ - pdpsInGroupList = pdpsInGroupQuery.getResultList(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get PDPs in group on pdpsInGroupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to get PDPs in group"); - } - if(pdpsInGroupList.size() > 0){ - if(moveToGroup != null){ - Query checkMoveToGroupQuery = em.createQuery("SELECT o FROM GroupEntity o WHERE o.groupId=:groupId AND o.deleted=:deleted"); - checkMoveToGroupQuery.setParameter("groupId", moveToGroup.getId()); - checkMoveToGroupQuery.setParameter("deleted", false); - List checkMoveToGroupList; - try{ - checkMoveToGroupList = checkMoveToGroupQuery.getResultList(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if group exists checkMoveToGroupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check if group exists"); - } - if(checkMoveToGroupList.size() < 1){ - PolicyLogger.error("The group could not be found with id " + moveToGroup.getId()); - throw new PersistenceException("The group could not be found with id " + moveToGroup.getId()); - } else if(checkMoveToGroupList.size() > 1){ - PolicyLogger.error("Somehow, more than one group with the id "+moveToGroup.getId()+" were found in the database that are not deleted"); - throw new PersistenceException("Somehow, more than one group with the id "+moveToGroup.getId()+" were found in the database that are not deleted"); - } else { - GroupEntity newGroup = (GroupEntity)checkMoveToGroupList.get(0); - for(Object pdpObject : pdpsInGroupList){ - PdpEntity pdp = (PdpEntity)pdpObject; - pdp.setGroup(newGroup); - if(!stringEquals(pdp.getModifiedBy(),username)){ - pdp.setModifiedBy(username); - } - try{ - - em.flush(); - this.newGroupId = newGroup.getGroupId(); - } catch(PersistenceException e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PersistenceException trying to set pdp group to null on em.flush()"); - throw new PersistenceException("Query failed trying to set pdp group to "); - } - } - } - } else { - PolicyLogger.error("Group "+group.getId()+" is trying to be delted with PDPs. No group was provided to move them to"); - throw new PAPException("Group has PDPs. Must provide a group for them to move to"); - } - } - - //delete group here - GroupEntity groupToDelete = (GroupEntity)deleteGroupQueryList.get(0); - groupToDelete.setDeleted(true); - if(!stringEquals(groupToDelete.getModifiedBy(), username)){ - groupToDelete.setModifiedBy(username); - } - em.flush(); - this.groupId = groupToDelete.getGroupKey(); - } - } - - @Override - public void addPolicyToGroup(String groupID, String policyID, String username) { - logger.debug("addPolicyToGroup(String groupID, String policyID, String username) as addPolicyToGroup("+groupID+", "+policyID+","+username+") called"); - if(isNullOrEmpty(groupID, policyID, username)){ - throw new IllegalArgumentException("groupID, policyID, and username must not be null or empty"); - } - synchronized(emLock){ - checkBeforeOperationRun(); - //check if group exists - Query groupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - groupQuery.setParameter("groupId", groupID); - groupQuery.setParameter("deleted", false); - List groupQueryList; - try{ - groupQueryList = groupQuery.getResultList(); - }catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if group exists groupQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check if group "+groupID+" exists"); - } - if(groupQueryList.size() < 1){ - PolicyLogger.error("Group policy is being added to does not exist with id "+groupID); - throw new PersistenceException("Group policy is being added to does not exist with id "+groupID); - } else if(groupQueryList.size() > 1){ - PolicyLogger.error("Somehow, more than one group with the id "+groupID+" were found in the database that are not deleted"); - throw new PersistenceException("Somehow, more than one group with the id "+groupID+" were found in the database that are not deleted"); - } - //we need to convert the form of the policy id that is used groups into the form that is used - //for the database. (com.Config_mypol.1.xml) to (Config_mypol.xml) - String[] policyNameScopeAndVersion = getNameScopeAndVersionFromPdpPolicy(policyID); - Query policyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName AND p.scope=:scope AND p.deleted=:deleted"); - policyQuery.setParameter("policyName", policyNameScopeAndVersion[0]); - policyQuery.setParameter("scope", policyNameScopeAndVersion[1]); - policyQuery.setParameter("deleted", false); - List policyQueryList; - try{ - policyQueryList = policyQuery.getResultList(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if policy exists policyQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check if policy "+policyNameScopeAndVersion[0]+" exists"); - } - if(policyQueryList.size() < 1){ - PolicyLogger.error("Policy being added to the group does not exist with policy id "+policyNameScopeAndVersion[0]); - throw new PersistenceException("Policy being added to the group does not exist with policy id "+policyNameScopeAndVersion[0]); - } else if(policyQueryList.size() > 1){ - PolicyLogger.error("Somehow, more than one policy with the id "+policyNameScopeAndVersion[0]+" were found in the database that are not deleted"); - throw new PersistenceException("Somehow, more than one group with the id "+policyNameScopeAndVersion[0]+" were found in the database that are not deleted"); - } - GroupEntity group = (GroupEntity)groupQueryList.get(0); - PolicyEntity policy = (PolicyEntity)policyQueryList.get(0); - Iterator policyIt = group.getPolicies().iterator(); - String policyName = getPolicyNameAndVersionFromPolicyFileName(policy.getPolicyName())[0]; - try{ - while(policyIt.hasNext()){ - PolicyEntity pol = policyIt.next(); - if(getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0].equals(policyName)){ - policyIt.remove(); - } - } - }catch(Exception e){ - PolicyLogger.error("Could not delete old versions for policy "+policy.getPolicyName()+", ID: "+policy.getPolicyId()); - } - group.addPolicyToGroup(policy); - em.flush(); - } - } - - //this means delete pdp not just remove from group - @Override - public void removePdpFromGroup(String pdpID, String username) { - logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup("+pdpID+","+username+") called"); - if(isNullOrEmpty(pdpID,username)){ - throw new IllegalArgumentException("pdpID and username must not be null or empty"); - } - synchronized(emLock){ - checkBeforeOperationRun(); - Query pdpQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); - pdpQuery.setParameter("pdpId", pdpID); - pdpQuery.setParameter("deleted", false); - List pdpList; - try{ - pdpList = pdpQuery.getResultList(); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if pdp exists pdpQuery.getResultList()"); - throw new PersistenceException("Query failed trying to check if pdp "+pdpID+" exists"); - } - if(pdpList.size() > 1){ - PolicyLogger.error("Somehow, more than one pdp with the id "+pdpID+" were found in the database that are not deleted"); - throw new PersistenceException("Somehow, more than one pdp with the id "+pdpID+" were found in the database that are not deleted"); - } else if(pdpList.size() < 1){ - PolicyLogger.error("Pdp being removed does not exist with id "+pdpID); - return; - } - PdpEntity pdp = (PdpEntity)pdpList.get(0); - pdp.setGroup(null); - if(!stringEquals(pdp.getModifiedBy(),username)){ - pdp.setModifiedBy(username); - } - pdp.setDeleted(true); - - em.flush(); - this.pdpId = pdp.getPdpKey(); - } - } - } - - private PolicyDBDao(){ - - } - - public static PolicyDBDaoTestClass getPolicyDBDaoTestClass(){ - return new PolicyDBDao().new PolicyDBDaoTestClass(); - } - - final class PolicyDBDaoTestClass { - String getConfigFile(String filename, String scope, PolicyRestAdapter policy){ - return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy); - } - String computeScope(String fullPath, String pathToExclude){ - return PolicyDBDao.computeScope(fullPath, pathToExclude); - } - String encryptPassword(String password) throws Exception{ - return PolicyDBDao.encryptPassword(password); - } - String decryptPassword(String password) throws Exception{ - return PolicyDBDao.decryptPassword(password); - } - String getDescriptionFromXacml(String xacmlData){ - return PolicyDBDao.getDescriptionFromXacml(xacmlData); - } - String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName){ - return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName); - } - } - -} \ No newline at end of file diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java deleted file mode 100644 index 7b8801cd8..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java +++ /dev/null @@ -1,188 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - -import java.util.List; - -import javax.persistence.PersistenceException; - -import org.openecomp.policy.rest.jpa.GroupEntity; -import org.openecomp.policy.rest.jpa.PdpEntity; -import org.openecomp.policy.xacml.api.pap.EcompPDP; -import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; - -import com.att.research.xacml.api.pap.PAPException; - -public interface PolicyDBDaoTransaction { - - /** - * Commits (makes permanent) the current transaction. Also, notifies other PolicyDBDao instances on other PAP servers of the update. - * @throws IllegalStateException if the PolicyDBDao transaction has not been used or has been committed already. - * @throws PersistenceException if the commit fails for some reason - */ - public void commitTransaction(); - - /** - * Create or update a policy - * @param policy A Policy object representing the policy to store or update - * @param username A string of the username you want to be stored for doing this operation - * @throws IllegalStateException If a transaction is open that has not yet been committed - * @throws PersistenceException If a database error occurs - * @throws IllegalArgumentException If the Policy's PolicyRestAdapter contains incorrect data. - */ - public void createPolicy(Policy policy, String username) throws IllegalStateException, PersistenceException, IllegalArgumentException; - - /** - * Check if the PolicyDBDaoTransaction is currently open - * @return False if the PolicyDBDao transaction has not been used or has been committed already, true if it is open. - */ - public boolean isTransactionOpen(); - - - - /** - * Delete an existing policy - * @param policyToDelete The file path of the policy to delete - * @throws IllegalArgumentException If the file path given can not be parsed - * @throws IllegalStateException If a transaction is open that has not yet been committed - * @throws PersistenceException If a database error occurs - */ - public void deletePolicy(String policyToDelete) throws IllegalStateException, PersistenceException, IllegalArgumentException; - - /** - * Rollback (undo) the current transaction. - */ - public void rollbackTransaction(); - - /** - * Close the PolicyDBDaoTransaction without rolling back or doing anything. Just used to close the EntityManager - */ - public void close(); - - - /** - * Create a new PDP group in the database - * @param groupID The ID to name the new group (use PolicyDBDao.createNewPDPGroupId) - * @param groupName The name to use for the new group - * @param groupDescription Description of the new group (optional) - * @param username Username of the user performing the operation - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - */ - public void createGroup(String groupID, String groupName, String groupDescription, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; - - /** - * Updates a group in the database with a new name of description - * @param group The group with updated information. The id must match an existing group, but the name and description can be changed. - * @param username Username of the user performing the operation - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs or if the group can not be found - */ - public void updateGroup(EcompPDPGroup group, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; - - /** - * Updates a PDP in the database with new information - * @param pdp The PDP to update - * @param username Username of the user performing the operation - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs or if the pdp can not be found - */ - public void updatePdp(EcompPDP pdp, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; - - /** - * Change the default group in the database to the group provided. - * @param group The new group which should be set as default in the database - * @param username Username of the user performing the operation - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - */ - public void changeDefaultGroup(EcompPDPGroup group, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; - - /** - * Moves a PDP to a new group. - * @param pdp The PDP which is to be moved to a new group - * @param group The new group which the PDP should be added to - * @param username Username of the user performing the operation - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - */ - public void movePdp(EcompPDP pdp, EcompPDPGroup group, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; - - /** - * Add a new PDP to an existing group - * @param pdpID The ID to name the new PDP - * @param groupID The ID of the existing group to add the PDP to - * @param pdpName The name to use for the new PDP - * @param pdpDescription Description of the new PDP (optional) - * @param pdpJmxPort - * @param username Username of the user performing the operation - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - */ - public void addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; - - /** - * Add an existing policy to an existing group - * @param group The ID of the existing group to add the policy to - * @param policyID The ID of an existing policy - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - */ - public void addPolicyToGroup(String group, String policyID, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; - - - /** - * Delete an existing PDP group - * @param group A PDPGroup object representing the group to delete - * @param moveToGroup A PDPGroup object representing another existing group which PDPs in the group being deleted should be moved to - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - * @throws PAPException If an error relating to how groups are handled occurs - */ - public void deleteGroup(EcompPDPGroup group, EcompPDPGroup moveToGroup, String username)throws IllegalArgumentException, IllegalStateException, PersistenceException, PAPException; - - /** - * Removes an existing PDP from its group and deletes it. - * @param pdpID The ID of the existing PDP which should be deleted - * @throws IllegalArgumentException If non-optional parameters are null or empty strings - * @throws IllegalStateException If a transaction is already open - * @throws PersistenceException If a database error occurs - */ - public void removePdpFromGroup(String pdpID, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; - - public GroupEntity getGroup(long groupKey); - public GroupEntity getGroup(String groupId); - public List getPdpsInGroup(long groupKey); - public PdpEntity getPdp(long pdpKey); - - void renamePolicy(String oldPath, String newPath,String username); - - void clonePolicy(String oldPolicyPath, String newPolicyPath, String username); - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java deleted file mode 100644 index bd69a8808..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/SafePolicyBuilder.java +++ /dev/null @@ -1,86 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.controlloop.policy.guard.ControlLoopGuard; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.Constructor; - -public class SafePolicyBuilder { - - private SafePolicyBuilder(){ - //Private Constructor. - } - - public static ControlLoopGuard loadYamlGuard(String specification) { - // - // Read the yaml into our Java Object - // - PolicyLogger.info("Requested YAML to convert : " + specification); - Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); - Object obj = yaml.load(specification); - return (ControlLoopGuard) obj; - } - - public static String generateXacmlGuard(String xacmlFileContent,Map generateMap, List blacklist, List targets) { - //Setup default values and Targets. - StringBuilder targetRegex= new StringBuilder(".*|"); - if(targets!=null && !targets.isEmpty()){ - targetRegex = new StringBuilder(); - for(String t : targets){ - targetRegex.append(t + "|"); - } - } - if(generateMap.get("clname")==null|| generateMap.get("clname").isEmpty()){ - generateMap.put("clname",".*"); - } - generateMap.put("targets", targetRegex.toString().substring(0, targetRegex.length()-1)); - // Replace values. - for(Map.Entry map: generateMap.entrySet()){ - Pattern p = Pattern.compile("\\$\\{" +map.getKey() +"\\}"); - Matcher m = p.matcher(xacmlFileContent); - String finalInput = map.getValue(); - if(finalInput.contains("$")){ - finalInput = finalInput.replace("$", "\\$"); - } - xacmlFileContent=m.replaceAll(finalInput); - } - if(blacklist!=null && !blacklist.isEmpty()){ - StringBuilder rule = new StringBuilder(); - for(String blackListName : blacklist){ - if(blackListName.contains("$")){ - blackListName = blackListName.replace("$", "\\$"); - } - rule.append(""+blackListName+""); - } - Pattern p = Pattern.compile("\\$\\{blackListElement\\}"); - Matcher m = p.matcher(xacmlFileContent); - xacmlFileContent=m.replaceAll(rule.toString()); - } - PolicyLogger.info("Generated XACML from the YAML Spec: \n" + xacmlFileContent); - return xacmlFileContent; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/package-info.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/package-info.java deleted file mode 100644 index 007f08d36..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/components/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java deleted file mode 100644 index 3ddeee32e..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java +++ /dev/null @@ -1,261 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.controller; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -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.pap.xacml.rest.util.JsonMessage; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.ActionPolicyDict; -import org.openecomp.policy.rest.jpa.UserInfo; -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 -public class ActionPolicyDictionaryController { - - private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyDictionaryController.class); - - private static CommonClassDao commonClassDao; - - @Autowired - public ActionPolicyDictionaryController(CommonClassDao commonClassDao){ - ActionPolicyDictionaryController.commonClassDao = commonClassDao; - } - - public ActionPolicyDictionaryController(){} - - public UserInfo getUserInfo(String loginId){ - UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); - return name; - } - - @RequestMapping(value={"/get_ActionPolicyDictDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getActionEntitybyName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("actionPolicyDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ActionPolicyDict.class, "attributeName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e.getMessage()); - } - } - - @RequestMapping(value={"/get_ActionPolicyDictData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getActionPolicyDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("actionPolicyDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ActionPolicyDict.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e.getMessage()); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/action_dictionary/save_ActionDict"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - ActionPolicyDict actionPolicyDict = null; - ActionAdapter adapter = null; - String userId = null; - - if(fromAPI) { - actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("dictionaryFields").toString(), ActionPolicyDict.class); - adapter = (ActionAdapter)mapper.readValue(root.get("dictionaryFields").toString(), ActionAdapter.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(actionPolicyDict.getAttributeName(), "attributeName", ActionPolicyDict.class); - int id = 0; - ActionPolicyDict data = (ActionPolicyDict) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - actionPolicyDict.setId(1); - } else { - actionPolicyDict.setId(id); - } - actionPolicyDict.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionPolicyDict.class); - adapter = mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionAdapter.class); - userId = root.get("userid").textValue(); - } - String header = ""; - int counter = 0; - if(adapter.getHeaders().size() > 0){ - for(Object attribute : adapter.getHeaders()){ - if(attribute instanceof LinkedHashMap){ - String key = ((LinkedHashMap) attribute).get("option").toString(); - String value = ((LinkedHashMap) attribute).get("number").toString(); - if(counter>0){ - header = header + ":"; - } - header = header + key + "="; - header = header + value; - counter ++; - } - } - } - actionPolicyDict.setHeader(header); - if(actionPolicyDict.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(actionPolicyDict.getAttributeName(), "attributeName", ActionPolicyDict.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - actionPolicyDict.setUserCreatedBy(this.getUserInfo(userId)); - actionPolicyDict.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(actionPolicyDict); - } - }else{ - if(!isFakeUpdate) { - actionPolicyDict.setUserModifiedBy(this.getUserInfo(userId)); - actionPolicyDict.setModifiedDate(new Date()); - commonClassDao.update(actionPolicyDict); - } - } - - String responseString = null; - if(duplicateflag) { - responseString = "Duplicate"; - } else { - responseString = mapper.writeValueAsString(commonClassDao.getData(ActionPolicyDict.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate) { - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{actionPolicyDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - } - catch (Exception e){ - LOGGER.error(e.getMessage()); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/action_dictionary/remove_actionPolicyDict"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeActionPolicyDictionary(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()); - ActionPolicyDict actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("data").toString(), ActionPolicyDict.class); - commonClassDao.delete(actionPolicyDict); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(ActionPolicyDictionaryController.commonClassDao.getData(ActionPolicyDict.class)); - JSONObject j = new JSONObject("{actionPolicyDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(e.getMessage()); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } -} - -class ActionAdapter{ - private ArrayList headers; - - public ArrayList getHeaders() { - return headers; - } - - public void setHeaders(ArrayList headers) { - this.headers = headers; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/BRMSDictionaryController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/BRMSDictionaryController.java deleted file mode 100644 index 4dda095d4..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/BRMSDictionaryController.java +++ /dev/null @@ -1,552 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.controller; - -import java.io.PrintWriter; -import java.io.StringWriter; -import java.nio.charset.StandardCharsets; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.io.IOUtils; -import org.json.JSONObject; -import org.openecomp.policy.api.PEDependency; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.util.JsonMessage; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.BRMSController; -import org.openecomp.policy.rest.jpa.BRMSDependency; -import org.openecomp.policy.rest.jpa.BRMSParamTemplate; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.openecomp.policy.utils.PolicyUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -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 -public class BRMSDictionaryController{ - - private static final Logger LOGGER = FlexLogger.getLogger(BRMSDictionaryController.class); - - - private static CommonClassDao commonClassDao; - - @Autowired - public BRMSDictionaryController(CommonClassDao commonClassDao){ - BRMSDictionaryController.commonClassDao = commonClassDao; - } - - public BRMSDictionaryController() {} - - private String rule; - - public UserInfo getUserInfo(String loginId){ - UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); - return name; - } - - @RequestMapping(value={"/get_BRMSParamDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSParamDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("brmsParamDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(BRMSParamTemplate.class, "ruleName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_BRMSParamData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSParamDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("brmsParamDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(BRMSParamTemplate.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/brms_dictionary/set_BRMSParamData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void SetRuleData(HttpServletRequest request, HttpServletResponse response) throws Exception{ - StringWriter writer = new StringWriter(); - IOUtils.copy(request.getInputStream() , writer, StandardCharsets.UTF_8); - String cleanStreamBoundary = writer.toString().replaceFirst("------(.*)(?s).*octet-stream", ""); - rule = cleanStreamBoundary.substring(0, cleanStreamBoundary.lastIndexOf("end")+4); - } - - @RequestMapping(value={"/brms_dictionary/save_BRMSParam"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - - BRMSParamTemplate bRMSParamTemplateData; - String userId = null; - if(fromAPI) { - bRMSParamTemplateData = (BRMSParamTemplate)mapper.readValue(root.get("dictionaryFields").toString(), BRMSParamTemplate.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(bRMSParamTemplateData.getRuleName(), "ruleName", BRMSParamTemplate.class); - int id = 0; - BRMSParamTemplate data = (BRMSParamTemplate) duplicateData.get(0); - id = data.getId(); - bRMSParamTemplateData.setId(id); - bRMSParamTemplateData.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - bRMSParamTemplateData = (BRMSParamTemplate)mapper.readValue(root.get("brmsParamDictionaryData").toString(), BRMSParamTemplate.class); - userId = root.get("userid").textValue(); - } - - bRMSParamTemplateData.setRule(rule); - if(bRMSParamTemplateData.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(bRMSParamTemplateData.getRuleName(), "ruleName", BRMSParamTemplate.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - bRMSParamTemplateData.setUserCreatedBy(this.getUserInfo(userId)); - commonClassDao.save(bRMSParamTemplateData); - } - }else{ - commonClassDao.update(bRMSParamTemplateData); - } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(BRMSDictionaryController.commonClassDao.getData(BRMSParamTemplate.class)); - } - if(fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - responseString = "Success"; - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{brmsParamDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/brms_dictionary/remove_brmsParam"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeBRMSParamDictionary(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()); - BRMSParamTemplate bRMSParamTemplateData = (BRMSParamTemplate)mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class); - commonClassDao.delete(bRMSParamTemplateData); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(BRMSDictionaryController.commonClassDao.getData(BRMSParamTemplate.class)); - JSONObject j = new JSONObject("{brmsParamDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/get_BRMSDependencyDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSDependencyDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("brmsDependencyDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(BRMSDependency.class, "dependencyName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_BRMSDependencyData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSDependencyDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("brmsDependencyDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(BRMSDependency.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/brms_dictionary/save_BRMSDependencyData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveBRMSDependencyDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - LOGGER.debug("DictionaryController: saveBRMSDependencyDictionary() is called"); - - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - - BRMSDependency brmsDependency; - String userId = null; - if (fromAPI) { - brmsDependency = (BRMSDependency)mapper.readValue(root.get("dictionaryFields").toString(), BRMSDependency.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(brmsDependency.getDependencyName(), "dependencyName", BRMSDependency.class); - int id = 0; - BRMSDependency data = (BRMSDependency) duplicateData.get(0); - id = data.getId(); - brmsDependency.setId(id); - brmsDependency.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - brmsDependency = (BRMSDependency)mapper.readValue(root.get("brmsDependencyDictionaryData").toString(), BRMSDependency.class); - userId = root.get("userid").textValue(); - } - - LOGGER.audit("the userId from the ecomp portal is: " + userId); - String responseString = null; - - if(brmsDependency.getDependency()!=null && !brmsDependency.getDependency().trim().equals("")){ - PEDependency dependency = null; - try{ - dependency = PolicyUtils.jsonStringToObject(brmsDependency.getDependency(), PEDependency.class); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "wrong data given for BRMS PEDependency Dictionary : " + brmsDependency.getDependency()); - } - if(dependency==null){ - responseString = "Error"; - }else{ - if(brmsDependency.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(brmsDependency.getDependencyName(), "dependencyName", BRMSDependency.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - brmsDependency.setUserCreatedBy(getUserInfo(userId)); - brmsDependency.setUserModifiedBy(getUserInfo(userId)); - LOGGER.audit("DictionaryController: got the user info now about to call Save() method on brmsDependencydao"); - commonClassDao.save(brmsDependency); - } - }else{ - brmsDependency.setUserModifiedBy(this.getUserInfo(userId)); - brmsDependency.setModifiedDate(new Date()); - commonClassDao.update(brmsDependency); - } - if(duplicateflag) { - responseString = "Duplicate"; - } else { - responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSDependency.class)); - } - } - } - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate") && !responseString.equals("Error")) { - responseString = "Success"; - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{brmsDependencyDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - } catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/brms_dictionary/remove_brmsDependency"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeBRMSDependencyDictionary(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()); - BRMSDependency brmsDependency = (BRMSDependency)mapper.readValue(root.get("data").toString(), BRMSDependency.class); - commonClassDao.delete(brmsDependency); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSDependency.class)); - JSONObject j = new JSONObject("{brmsDependencyDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - - @RequestMapping(value={"/get_BRMSControllerDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSControllerDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("brmsControllerDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(BRMSController.class, "controllerName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_BRMSControllerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getBRMSControllerDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("brmsControllerDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(BRMSController.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/brms_dictionary/save_BRMSControllerData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveBRMSControllerDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - LOGGER.debug("DictionaryController: saveBRMSControllerDictionary() is called"); - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - BRMSController brmsController; - String userId = null; - if (fromAPI) { - brmsController = (BRMSController)mapper.readValue(root.get("dictionaryFields").toString(), BRMSController.class); - userId = "API"; - //check if update operation or create, get id for data to be updated - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(brmsController.getControllerName(), "controllerName", BRMSController.class); - int id = 0; - BRMSController data = (BRMSController) duplicateData.get(0); - id = data.getId(); - brmsController.setId(id); - brmsController.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - brmsController = (BRMSController)mapper.readValue(root.get("brmsControllerDictionaryData").toString(), BRMSController.class); - userId = root.get("userid").textValue(); - } - LOGGER.audit("the userId from the ecomp portal is: " + userId); - String responseString = null; - if(brmsController.getController()!=null && !brmsController.getController().trim().equals("")){ - PEDependency dependency = null; - try{ - dependency = PolicyUtils.jsonStringToObject(brmsController.getController(), PEDependency.class); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "wrong data given for BRMS Controller Dictionary : " + brmsController.getController()); - } - if(dependency==null){ - responseString = "Error"; - }else{ - if(brmsController.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(brmsController.getControllerName(), "controllerName", BRMSController.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - brmsController.setUserCreatedBy(getUserInfo(userId)); - brmsController.setUserModifiedBy(getUserInfo(userId)); - LOGGER.audit("DictionaryController: got the user info now about to call Save() method on brmsControllerdao"); - commonClassDao.save(brmsController); - } - }else{ - brmsController.setUserModifiedBy(this.getUserInfo(userId)); - brmsController.setModifiedDate(new Date()); - commonClassDao.update(brmsController); - } - if(duplicateflag) { - responseString = "Duplicate"; - } else { - responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSController.class)); - } - } - } - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate") && !responseString.equals("Error")) { - responseString = "Success"; - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{brmsControllerDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - } catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/brms_dictionary/remove_brmsController"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeBRMSControllerDictionary(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()); - BRMSController brmsController = (BRMSController)mapper.readValue(root.get("data").toString(), BRMSController.class); - commonClassDao.delete(brmsController); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSController.class)); - JSONObject j = new JSONObject("{brmsControllerDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - public BRMSDependency getDependencyDataByID(String dependencyName){ - return (BRMSDependency) commonClassDao.getEntityItem(BRMSDependency.class, "dependencyName", dependencyName); - } - - public BRMSController getControllerDataByID(String controllerName){ - return (BRMSController) commonClassDao.getEntityItem(BRMSController.class, "controllerName", controllerName); - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java deleted file mode 100644 index f97d84692..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java +++ /dev/null @@ -1,1031 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.controller; - -import java.io.PrintWriter; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -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.pap.xacml.rest.adapters.GridData; -import org.openecomp.policy.pap.xacml.rest.util.JsonMessage; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.ClosedLoopD2Services; -import org.openecomp.policy.rest.jpa.ClosedLoopSite; -import org.openecomp.policy.rest.jpa.PEPOptions; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.openecomp.policy.rest.jpa.VNFType; -import org.openecomp.policy.rest.jpa.VSCLAction; -import org.openecomp.policy.rest.jpa.VarbindDictionary; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -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 -public class ClosedLoopDictionaryController{ - - private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopDictionaryController.class); - - private static CommonClassDao commonClassDao; - - @Autowired - public ClosedLoopDictionaryController(CommonClassDao commonClassDao){ - ClosedLoopDictionaryController.commonClassDao = commonClassDao; - } - - public ClosedLoopDictionaryController(){} - - public UserInfo getUserInfo(String loginId){ - UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); - return name; - } - - - @RequestMapping(value={"/get_VSCLActionDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVSCLActionDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("vsclActionDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(VSCLAction.class, "vsclaction"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - - @RequestMapping(value={"/get_VSCLActionData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVSCLActionDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("vsclActionDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/get_VNFTypeDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVNFTypeDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("vnfTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(VNFType.class, "vnftype"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_VNFTypeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVNFTypeDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("vnfTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(VNFType.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/get_PEPOptionsDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPEPOptionsDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("pepOptionsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PEPOptions.class, "pepName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_PEPOptionsData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPEPOptionsDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("pepOptionsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/get_VarbindDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVarbindDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("varbindDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(VarbindDictionary.class, "varbindName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_VarbindDictionaryData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getVarbindDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("varbindDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/get_ClosedLoopServicesDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getClosedLoopServiceDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("closedLoopServiceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ClosedLoopD2Services.class, "serviceName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_ClosedLoopServicesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getClosedLoopServiceDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("closedLoopServiceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/get_ClosedLoopSiteDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getClosedLoopSiteDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("closedLoopSiteDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ClosedLoopSite.class, "siteName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_ClosedLoopSiteData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getClosedLoopSiteDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("closedLoopSiteDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/cl_dictionary/save_vsclAction"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveVSCLAction(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - VSCLAction vSCLAction; - String userId = null; - if (fromAPI) { - vSCLAction = (VSCLAction)mapper.readValue(root.get("dictionaryFields").toString(), VSCLAction.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(vSCLAction.getVsclaction(), "vsclaction", VSCLAction.class); - int id = 0; - VSCLAction data = (VSCLAction) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - vSCLAction.setId(1); - } else { - vSCLAction.setId(id); - } - - vSCLAction.setUserCreatedBy(this.getUserInfo(userId)); - } - - } else { - vSCLAction = (VSCLAction)mapper.readValue(root.get("vsclActionDictionaryData").toString(), VSCLAction.class); - userId = root.get("userid").textValue(); - } - if(vSCLAction.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(vSCLAction.getVsclaction(), "vsclaction", VSCLAction.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - vSCLAction.setUserCreatedBy(this.getUserInfo(userId)); - vSCLAction.setUserModifiedBy(this.getUserInfo(userId)); - vSCLAction.setModifiedDate(new Date()); - commonClassDao.save(vSCLAction); - } - }else{ - if(!isFakeUpdate) { - vSCLAction.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.update(vSCLAction); - } - } - - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class)); - } - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate) { - responseString = "Exists"; - } else { - responseString = "Success"; - } - - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{vsclActionDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/cl_dictionary/remove_VsclAction"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeVSCLAction(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()); - VSCLAction vSCLAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class); - commonClassDao.delete(vSCLAction); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class)); - JSONObject j = new JSONObject("{vsclActionDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/cl_dictionary/save_vnfType"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveVnfType(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - VNFType vNFType; - String userId = null; - - if (fromAPI) { - vNFType = (VNFType)mapper.readValue(root.get("dictionaryFields").toString(), VNFType.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(vNFType.getVnftype(), "vnftype", VNFType.class); - int id = 0; - VNFType data = (VNFType) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - vNFType.setId(1); - } else { - vNFType.setId(id); - } - vNFType.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - vNFType = (VNFType)mapper.readValue(root.get("vnfTypeDictionaryData").toString(), VNFType.class); - userId = root.get("userid").textValue(); - } - if(vNFType.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(vNFType.getVnftype(), "vnftype", VNFType.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - vNFType.setUserCreatedBy(this.getUserInfo(userId)); - vNFType.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(vNFType); - } - }else{ - if(!isFakeUpdate) { - vNFType.setUserModifiedBy(this.getUserInfo(userId)); - vNFType.setModifiedDate(new Date()); - commonClassDao.update(vNFType); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(VNFType.class)); - } - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate) { - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{vnfTypeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/cl_dictionary/remove_vnfType"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeVnfType(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()); - VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class); - commonClassDao.delete(vNFType); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(VNFType.class)); - JSONObject j = new JSONObject("{vnfTypeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/cl_dictionary/save_pepOptions"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView savePEPOptions(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PEPOptions pEPOptions; - GridData gridData; - String userId = null; - if (fromAPI) { - pEPOptions = (PEPOptions)mapper.readValue(root.get("dictionaryFields").toString(), PEPOptions.class); - gridData = (GridData)mapper.readValue(root.get("dictionaryFields").toString(), GridData.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), "pepName", PEPOptions.class); - int id = 0; - PEPOptions data = (PEPOptions) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - pEPOptions.setId(1); - } else { - pEPOptions.setId(id); - } - pEPOptions.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - pEPOptions = (PEPOptions)mapper.readValue(root.get("pepOptionsDictionaryData").toString(), PEPOptions.class); - gridData = (GridData)mapper.readValue(root.get("pepOptionsDictionaryData").toString(), GridData.class); - userId = root.get("userid").textValue(); - } - String actions = ""; - int counter = 0; - if(gridData.getAttributes().size() > 0){ - for(Object attribute : gridData.getAttributes()){ - if(attribute instanceof LinkedHashMap){ - String key = ((LinkedHashMap) attribute).get("option").toString(); - String value = ((LinkedHashMap) attribute).get("number").toString(); - if(counter>0){ - actions = actions + ":#@"; - } - actions = actions + key + "=#@"; - actions = actions + value; - counter ++; - } - } - } - pEPOptions.setActions(actions); - if(pEPOptions.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), "pepName", PEPOptions.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - pEPOptions.setUserCreatedBy(this.getUserInfo(userId)); - pEPOptions.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(pEPOptions); - } - }else{ - if(!isFakeUpdate){ - pEPOptions.setUserModifiedBy(this.getUserInfo(userId)); - pEPOptions.setModifiedDate(new Date()); - commonClassDao.update(pEPOptions); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class)); - } - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{pepOptionsDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/cl_dictionary/remove_pepOptions"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePEPOptions(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()); - PEPOptions pEPOptions = (PEPOptions)mapper.readValue(root.get("data").toString(), PEPOptions.class); - commonClassDao.delete(pEPOptions); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class)); - JSONObject j = new JSONObject("{pepOptionsDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/cl_dictionary/save_service"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveServiceType(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - ClosedLoopD2Services serviceData; - String userId = null; - if (fromAPI) { - serviceData = (ClosedLoopD2Services)mapper.readValue(root.get("dictionaryFields").toString(), ClosedLoopD2Services.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(serviceData.getServiceName(), "serviceName", ClosedLoopD2Services.class); - int id = 0; - ClosedLoopD2Services data = (ClosedLoopD2Services) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - serviceData.setId(1); - } else { - serviceData.setId(id); - } - serviceData.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - serviceData = (ClosedLoopD2Services)mapper.readValue(root.get("closedLoopServiceDictionaryData").toString(), ClosedLoopD2Services.class); - userId = root.get("userid").textValue(); - } - if(serviceData.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(serviceData.getServiceName(), "serviceName", ClosedLoopD2Services.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - serviceData.setUserCreatedBy(this.getUserInfo(userId)); - serviceData.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(serviceData); - } - }else{ - if(!isFakeUpdate){ - serviceData.setUserModifiedBy(this.getUserInfo(userId)); - serviceData.setModifiedDate(new Date()); - commonClassDao.update(serviceData); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class)); - } - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{closedLoopServiceDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/cl_dictionary/remove_Service"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeServiceType(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()); - ClosedLoopD2Services closedLoopD2Services = (ClosedLoopD2Services)mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class); - commonClassDao.delete(closedLoopD2Services); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class)); - JSONObject j = new JSONObject("{closedLoopServiceDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/cl_dictionary/save_siteName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveSiteType(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - ClosedLoopSite siteData; - String userId = null; - if (fromAPI) { - siteData = (ClosedLoopSite)mapper.readValue(root.get("dictionaryFields").toString(), ClosedLoopSite.class); - userId = "API"; - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(siteData.getSiteName(), "siteName", ClosedLoopSite.class); - int id = 0; - ClosedLoopSite data = (ClosedLoopSite) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - siteData.setId(1); - } else { - siteData.setId(id); - } - siteData.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - siteData = (ClosedLoopSite)mapper.readValue(root.get("closedLoopSiteDictionaryData").toString(), ClosedLoopSite.class); - userId = root.get("userid").textValue(); - } - if(siteData.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(siteData.getSiteName(), "siteName", ClosedLoopSite.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - siteData.setUserCreatedBy(this.getUserInfo(userId)); - siteData.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(siteData); - } - }else{ - if(!isFakeUpdate) { - siteData.setUserModifiedBy(this.getUserInfo(userId)); - siteData.setModifiedDate(new Date()); - commonClassDao.update(siteData); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{closedLoopSiteDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/cl_dictionary/remove_site"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeSiteType(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()); - ClosedLoopSite closedLoopSite = (ClosedLoopSite)mapper.readValue(root.get("data").toString(), ClosedLoopSite.class); - commonClassDao.delete(closedLoopSite); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class)); - JSONObject j = new JSONObject("{closedLoopSiteDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/cl_dictionary/save_varbind"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveVarbind(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - VarbindDictionary varbindDictionary; - String userId = null; - if (fromAPI) { - varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("dictionaryFields").toString(), VarbindDictionary.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(varbindDictionary.getVarbindName(), "varbindName", VarbindDictionary.class); - int id = 0; - VarbindDictionary data = (VarbindDictionary) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - varbindDictionary.setId(1); - } else { - varbindDictionary.setId(id); - } - varbindDictionary.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("varbindDictionaryData").toString(), VarbindDictionary.class); - userId = root.get("userid").textValue(); - } - if(varbindDictionary.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(varbindDictionary.getVarbindName(), "varbindName", VarbindDictionary.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - varbindDictionary.setUserCreatedBy(this.getUserInfo(userId)); - varbindDictionary.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(varbindDictionary); - } - }else{ - if(!isFakeUpdate){ - varbindDictionary.setUserModifiedBy(this.getUserInfo(userId)); - varbindDictionary.setModifiedDate(new Date()); - commonClassDao.update(varbindDictionary); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{varbindDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/cl_dictionary/remove_varbindDict"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeVarbind(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()); - VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class); - commonClassDao.delete(varbindDictionary); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class)); - JSONObject j = new JSONObject("{varbindDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - -} - diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java deleted file mode 100644 index c9a20066d..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java +++ /dev/null @@ -1,426 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.controller; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -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.pap.xacml.rest.util.JsonMessage; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.Datatype; -import org.openecomp.policy.rest.jpa.DecisionSettings; -import org.openecomp.policy.rest.jpa.RainyDayTreatments; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -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 -public class DecisionPolicyDictionaryController { - - private static final Logger LOGGER = FlexLogger.getLogger(DecisionPolicyDictionaryController.class); - - private static CommonClassDao commonClassDao; - - @Autowired - public DecisionPolicyDictionaryController(CommonClassDao commonClassDao){ - DecisionPolicyDictionaryController.commonClassDao = commonClassDao; - } - - public DecisionPolicyDictionaryController(){} - - public UserInfo getUserInfo(String loginId){ - UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); - return name; - } - - @RequestMapping(value={"/get_SettingsDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getSettingsDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("settingsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(DecisionSettings.class, "xacmlId"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - - @RequestMapping(value={"/get_SettingsDictionaryData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getSettingsDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("settingsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/decision_dictionary/save_Settings"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - DecisionSettings decisionSettings; - String userId = null; - - if (fromAPI) { - decisionSettings = (DecisionSettings)mapper.readValue(root.get("dictionaryFields").toString(), DecisionSettings.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), "xacmlId", DecisionSettings.class); - int id = 0; - DecisionSettings data = (DecisionSettings) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - decisionSettings.setId(1); - } else { - decisionSettings.setId(id); - } - decisionSettings.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - decisionSettings = (DecisionSettings)mapper.readValue(root.get("settingsDictionaryData").toString(), DecisionSettings.class); - userId = root.get("userid").textValue(); - } - if(decisionSettings.getDatatypeBean().getShortName() != null){ - String datatype = decisionSettings.getDatatypeBean().getShortName(); - Datatype a = new Datatype(); - if(datatype.equalsIgnoreCase("string")){ - a.setId(26); - }else if(datatype.equalsIgnoreCase("integer")){ - a.setId(12); - }else if(datatype.equalsIgnoreCase("boolean")){ - a.setId(18); - }else if(datatype.equalsIgnoreCase("double")){ - a.setId(25); - }else if(datatype.equalsIgnoreCase("user")){ - a.setId(29); - } - decisionSettings.setDatatypeBean(a); - } - if(decisionSettings.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), "xacmlId", DecisionSettings.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - decisionSettings.setUserCreatedBy(this.getUserInfo(userId)); - decisionSettings.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(decisionSettings); - } - }else{ - if(!isFakeUpdate) { - decisionSettings.setUserModifiedBy(this.getUserInfo(userId)); - decisionSettings.setModifiedDate(new Date()); - commonClassDao.update(decisionSettings); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{settingsDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/settings_dictionary/remove_settings"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeSettingsDictionary(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()); - DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class); - commonClassDao.delete(decisionSettings); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)); - JSONObject j = new JSONObject("{settingsDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - - - @RequestMapping(value={"/get_RainyDayDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getRainyDayDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("rainyDayDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(RainyDayTreatments.class, "bbid"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - - @RequestMapping(value={"/get_RainyDayDictionaryData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getRainyDayDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("rainyDayDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/decision_dictionary/save_RainyDay"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - RainyDayTreatments decisionRainyDay; - TreatmentValues treatmentsData = null; - if (fromAPI) { - decisionRainyDay = (RainyDayTreatments)mapper.readValue(root.get("dictionaryFields").toString(), RainyDayTreatments.class); - treatmentsData = (TreatmentValues)mapper.readValue(root.get("dictionaryFields").toString(), TreatmentValues.class); - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(decisionRainyDay.getBbid()+":"+decisionRainyDay.getWorkstep(), "bbid:workstep", RainyDayTreatments.class); - int id = 0; - RainyDayTreatments data = (RainyDayTreatments) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - } else { - decisionRainyDay.setId(id); - } - } - } else { - decisionRainyDay = (RainyDayTreatments)mapper.readValue(root.get("rainyDayDictionaryData").toString(), RainyDayTreatments.class); - treatmentsData = (TreatmentValues)mapper.readValue(root.get("rainyDayDictionaryData").toString(), TreatmentValues.class); - } - - String userValue = ""; - int counter = 0; - if(treatmentsData.getUserDataTypeValues().size() > 0){ - for(Object treatment : treatmentsData.getUserDataTypeValues()){ - if(treatment instanceof LinkedHashMap){ - String key = ((LinkedHashMap) treatment).get("treatment").toString(); - if(counter>0){ - userValue = userValue + ","; - } - userValue = userValue + key ; - counter ++; - } - } - } - decisionRainyDay.setTreatments(userValue); - - if(decisionRainyDay.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(decisionRainyDay.getBbid()+":"+decisionRainyDay.getWorkstep(), "bbid:workstep", RainyDayTreatments.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(decisionRainyDay); - } - }else{ - if(!isFakeUpdate) { - commonClassDao.update(decisionRainyDay); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{rainyDayDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/decision_dictionary/remove_rainyDay"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeRainyDayDictionary(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()); - RainyDayTreatments decisionRainyDay = (RainyDayTreatments)mapper.readValue(root.get("data").toString(), RainyDayTreatments.class); - commonClassDao.delete(decisionRainyDay); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)); - JSONObject j = new JSONObject("{rainyDayDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - -} - -class TreatmentValues { - private ArrayList userDataTypeValues; - - public ArrayList getUserDataTypeValues() { - return userDataTypeValues; - } - - public void setUserDataTypeValues(ArrayList userDataTypeValues) { - this.userDataTypeValues = userDataTypeValues; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java deleted file mode 100644 index 0ea1da171..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java +++ /dev/null @@ -1,246 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.controller; - -import java.io.PrintWriter; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -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.pap.xacml.rest.adapters.GridData; -import org.openecomp.policy.pap.xacml.rest.util.JsonMessage; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.DescriptiveScope; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -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 -public class DescriptiveDictionaryController { - - private static final Logger LOGGER = FlexLogger.getLogger(DescriptiveDictionaryController.class); - - private static CommonClassDao commonClassDao; - - @Autowired - public DescriptiveDictionaryController(CommonClassDao commonClassDao){ - DescriptiveDictionaryController.commonClassDao = commonClassDao; - } - - public DescriptiveDictionaryController(){} - - public UserInfo getUserInfo(String loginId){ - UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); - return name; - } - - @RequestMapping(value={"/get_DescriptiveScopeByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getDescriptiveDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("descriptiveScopeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(DescriptiveScope.class, "descriptiveScopeName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_DescriptiveScope"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getDescriptiveDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("descriptiveScopeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/descriptive_dictionary/save_descriptive"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - DescriptiveScope descriptiveScope; - GridData data; - String userId = null; - if (fromAPI) { - descriptiveScope = (DescriptiveScope)mapper.readValue(root.get("dictionaryFields").toString(), DescriptiveScope.class); - data = (GridData)mapper.readValue(root.get("dictionaryFields").toString(), GridData.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), "descriptiveScopeName", DescriptiveScope.class); - int id = 0; - DescriptiveScope dbdata = (DescriptiveScope) duplicateData.get(0); - id = dbdata.getId(); - if(id==0){ - isFakeUpdate=true; - descriptiveScope.setId(1); - } else { - descriptiveScope.setId(id); - } - descriptiveScope.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - descriptiveScope = (DescriptiveScope)mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), DescriptiveScope.class); - data = (GridData)mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), GridData.class); - userId = root.get("userid").textValue(); - } - String header = ""; - int counter = 0; - if(data.getAttributes().size() > 0){ - for(Object attribute : data.getAttributes()){ - if(attribute instanceof LinkedHashMap){ - String key = ((LinkedHashMap) attribute).get("option").toString(); - String value = ((LinkedHashMap) attribute).get("number").toString(); - if(counter>0){ - header = header + "AND"; - } - header = header + key + ":"; - header = header + value; - counter ++; - } - } - } - descriptiveScope.setSearch(header); - if(descriptiveScope.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), "descriptiveScopeName", DescriptiveScope.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - descriptiveScope.setUserCreatedBy(this.getUserInfo(userId)); - descriptiveScope.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(descriptiveScope); - } - }else{ - if(!isFakeUpdate){ - descriptiveScope.setUserModifiedBy(this.getUserInfo(userId)); - descriptiveScope.setModifiedDate(new Date()); - commonClassDao.update(descriptiveScope); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/descriptive_dictionary/remove_descriptiveScope"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeDescriptiveDictionary(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()); - DescriptiveScope descriptiveScope = (DescriptiveScope)mapper.readValue(root.get("data").toString(), DescriptiveScope.class); - commonClassDao.delete(descriptiveScope); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)); - JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } -} - diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryController.java deleted file mode 100644 index b01f9b031..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryController.java +++ /dev/null @@ -1,447 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.controller; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.JSONObject; -import org.openecomp.policy.pap.xacml.rest.util.JsonMessage; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.Attribute; -import org.openecomp.policy.rest.jpa.Category; -import org.openecomp.policy.rest.jpa.Datatype; -import org.openecomp.policy.rest.jpa.EcompName; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -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 com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -public class DictionaryController { - - private static final Log LOGGER = LogFactory.getLog(DictionaryController.class); - - private static CommonClassDao commonClassDao; - - @Autowired - public DictionaryController(CommonClassDao commonClassDao){ - DictionaryController.commonClassDao = commonClassDao; - } - - public DictionaryController(){} - - public UserInfo getUserInfo(String loginId){ - UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); - return name; - } - - - public Category getCategory(){ - List list = commonClassDao.getData(Category.class); - for (int i = 0; i < list.size() ; i++) { - Category value = (Category) list.get(i); - if (value.getShortName().equals("resource")) { - return value; - } - } - return null; - } - - @RequestMapping(value={"/get_AttributeDatabyAttributeName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAttributeDictionaryEntityDatabyAttributeName(HttpServletRequest request, HttpServletResponse response){ - try{ - System.out.println(); - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("attributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(Attribute.class, "xacmlId"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - //Attribute Dictionary - @RequestMapping(value="/get_AttributeData", method= RequestMethod.GET , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAttributeDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - System.out.println(); - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("attributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(Attribute.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/attribute_dictionary/save_attribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - Attribute attributeData = null; - AttributeValues attributeValueData = null; - String userId = null; - if (fromAPI) { - //JsonNode json = root.get("dictionaryFields"); - attributeData = (Attribute)mapper.readValue(root.get("dictionaryFields").toString(), Attribute.class); - attributeValueData = (AttributeValues)mapper.readValue(root.get("dictionaryFields").toString(), AttributeValues.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), "xacmlId", Attribute.class); - int id = 0; - Attribute data = (Attribute) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - attributeData.setId(1); - } else { - attributeData.setId(id); - } - attributeData.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - attributeData = (Attribute)mapper.readValue(root.get("attributeDictionaryData").toString(), Attribute.class); - attributeValueData = (AttributeValues)mapper.readValue(root.get("attributeDictionaryData").toString(), AttributeValues.class); - userId = root.get("userid").textValue(); - } - String userValue = ""; - int counter = 0; - if(attributeValueData.getUserDataTypeValues().size() > 0){ - for(Object attribute : attributeValueData.getUserDataTypeValues()){ - if(attribute instanceof LinkedHashMap){ - String key = ((LinkedHashMap) attribute).get("attributeValues").toString(); - if(counter>0){ - userValue = userValue + ","; - } - userValue = userValue + key ; - counter ++; - } - } - } - attributeData.setAttributeValue(userValue); - if(attributeData.getDatatypeBean().getShortName() != null){ - String datatype = attributeData.getDatatypeBean().getShortName(); - Datatype a = new Datatype(); - if(datatype.equalsIgnoreCase("string")){ - a.setId(26); - }else if(datatype.equalsIgnoreCase("integer")){ - a.setId(12); - }else if(datatype.equalsIgnoreCase("boolean")){ - a.setId(18); - }else if(datatype.equalsIgnoreCase("double")){ - a.setId(25); - }else if(datatype.equalsIgnoreCase("user")){ - a.setId(29); - } - attributeData.setDatatypeBean(a); - } - if(attributeData.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), "xacmlId", Attribute.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - attributeData.setCategoryBean(this.getCategory()); - attributeData.setUserCreatedBy(this.getUserInfo(userId)); - attributeData.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(attributeData); - } - }else{ - if(!isFakeUpdate) { - attributeData.setUserModifiedBy(this.getUserInfo(userId)); - attributeData.setModifiedDate(new Date()); - commonClassDao.update(attributeData); - } - } - String responseString = null; - if(duplicateflag) { - responseString = "Duplicate"; - } else { - responseString = mapper.writeValueAsString(commonClassDao.getData(Attribute.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate) { - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{attributeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/attribute_dictionary/remove_attribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeAttributeDictionary(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()); - Attribute attributeData = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class); - commonClassDao.delete(attributeData); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(Attribute.class)); - JSONObject j = new JSONObject("{attributeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - //EcompName Dictionary - @RequestMapping(value={"/get_EcompNameDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getEcompNameDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - LOGGER.info("get_EcompNameDataByName is called"); - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("ecompNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(EcompName.class, "ecompName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_EcompNameData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getEcompNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("ecompNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(EcompName.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/ecomp_dictionary/save_ecompName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveEcompDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - EcompName ecompData; - String userId = null; - if (fromAPI) { - ecompData = (EcompName)mapper.readValue(root.get("dictionaryFields").toString(), EcompName.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(ecompData.getEcompName(), "ecompName", EcompName.class); - int id = 0; - EcompName data = (EcompName) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - ecompData.setId(1); - } else { - ecompData.setId(id); - } - ecompData.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - ecompData = (EcompName)mapper.readValue(root.get("ecompNameDictionaryData").toString(), EcompName.class); - userId = root.get("userid").textValue(); - } - if(ecompData.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(ecompData.getEcompName(), "ecompName", EcompName.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - ecompData.setUserCreatedBy(getUserInfo(userId)); - ecompData.setUserModifiedBy(getUserInfo(userId)); - commonClassDao.save(ecompData); - } - }else{ - if(!isFakeUpdate){ - ecompData.setUserModifiedBy(this.getUserInfo(userId)); - ecompData.setModifiedDate(new Date()); - commonClassDao.update(ecompData); - } - } - String responseString = null; - if(duplicateflag) { - responseString = "Duplicate"; - } else { - responseString = mapper.writeValueAsString(commonClassDao.getData(EcompName.class)); - } - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{ecompNameDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/ecomp_dictionary/remove_ecomp"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeEcompDictionary(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()); - EcompName ecompData = (EcompName)mapper.readValue(root.get("data").toString(), EcompName.class); - commonClassDao.delete(ecompData); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(EcompName.class)); - JSONObject j = new JSONObject("{ecompNameDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - -} - -class AttributeValues{ - private ArrayList userDataTypeValues; - - public ArrayList getUserDataTypeValues() { - return userDataTypeValues; - } - - public void setUserDataTypeValues(ArrayList userDataTypeValues) { - this.userDataTypeValues = userDataTypeValues; - } -} - diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryImportController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryImportController.java deleted file mode 100644 index 94f83674b..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryImportController.java +++ /dev/null @@ -1,539 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.controller; - /* - * - * - * */ -import java.io.File; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.OutputStream; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.compress.utils.IOUtils; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.ActionList; -import org.openecomp.policy.rest.jpa.ActionPolicyDict; -import org.openecomp.policy.rest.jpa.AddressGroup; -import org.openecomp.policy.rest.jpa.Attribute; -import org.openecomp.policy.rest.jpa.BRMSParamTemplate; -import org.openecomp.policy.rest.jpa.Category; -import org.openecomp.policy.rest.jpa.Datatype; -import org.openecomp.policy.rest.jpa.DecisionSettings; -import org.openecomp.policy.rest.jpa.DescriptiveScope; -import org.openecomp.policy.rest.jpa.EcompName; -import org.openecomp.policy.rest.jpa.GroupServiceList; -import org.openecomp.policy.rest.jpa.PEPOptions; -import org.openecomp.policy.rest.jpa.PrefixList; -import org.openecomp.policy.rest.jpa.ProtocolList; -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.rest.jpa.UserInfo; -import org.openecomp.policy.rest.jpa.VNFType; -import org.openecomp.policy.rest.jpa.VSCLAction; -import org.openecomp.policy.rest.jpa.VarbindDictionary; -import org.openecomp.policy.rest.jpa.Zone; -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.ObjectMapper; - -import au.com.bytecode.opencsv.CSVReader; - - -@Controller -public class DictionaryImportController { - private String newFile; - - private static CommonClassDao commonClassDao; - - @Autowired - public DictionaryImportController(CommonClassDao commonClassDao){ - DictionaryImportController.commonClassDao = commonClassDao; - } - - public DictionaryImportController(){} - - - @RequestMapping(value={"/dictionary/import_dictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public void ImportDictionaryData(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 userId = request.getParameter("userId"); - String dictionaryName = request.getParameter("dictionaryName"); - - File file = new File(dictionaryName); - OutputStream outputStream = new FileOutputStream(file); - IOUtils.copy(request.getInputStream(), outputStream); - outputStream.close(); - this.newFile = file.toString(); - CSVReader csvReader = new CSVReader(new FileReader(this.newFile)); - List dictSheet = csvReader.readAll(); - if(dictionaryName.startsWith("Attribute")){ - for(int i = 1; i< dictSheet.size(); i++){ - Attribute attribute = new Attribute(""); - UserInfo userinfo = new UserInfo(); - userinfo.setUserLoginId(userId); - attribute.setUserCreatedBy(userinfo); - attribute.setUserModifiedBy(userinfo); - String[] rows = dictSheet.get(i); - for (int j=0 ; j model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - List list = commonClassDao.getData(EnforcingType.class); - List dictList = new ArrayList<>(); - for(int i = 0; i < list.size(); i++){ - EnforcingType dict = (EnforcingType) list.get(i); - dictList.add(dict.getEnforcingType()); - } - model.put("enforcerDictionaryDatas", mapper.writeValueAsString(dictList)); - org.openecomp.policy.pap.xacml.rest.util.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={"/enforcer_dictionary/save_enforcerType"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveEnforcerDictionary(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()); - EnforcingType enforcingType = (EnforcingType)mapper.readValue(root.get("enforcerDictionaryData").toString(), EnforcingType.class); - if(enforcingType.getId() == 0){ - commonClassDao.save(enforcingType); - }else{ - commonClassDao.update(enforcingType); - } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(EnforcingType.class)); - JSONObject j = new JSONObject("{enforcerDictionaryDatas: " + 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; - } - - @RequestMapping(value={"/enforcer_dictionary/remove_enforcer"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeEnforcerDictionary(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()); - EnforcingType enforcingType = (EnforcingType)mapper.readValue(root.get("data").toString(), EnforcingType.class); - commonClassDao.delete(enforcingType); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(EnforcingType.class)); - JSONObject j = new JSONObject("{enforcerDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - System.out.println(e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/FirewallDictionaryController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/FirewallDictionaryController.java deleted file mode 100644 index 5172f451b..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/FirewallDictionaryController.java +++ /dev/null @@ -1,2279 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.controller; - -import java.io.PrintWriter; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.jboss.netty.handler.ipfilter.CIDR; -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.adapters.GridData; -import org.openecomp.policy.pap.xacml.rest.util.JsonMessage; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.ActionList; -import org.openecomp.policy.rest.jpa.AddressGroup; -import org.openecomp.policy.rest.jpa.FWTag; -import org.openecomp.policy.rest.jpa.FWTagPicker; -import org.openecomp.policy.rest.jpa.FirewallDictionaryList; -import org.openecomp.policy.rest.jpa.GroupServiceList; -import org.openecomp.policy.rest.jpa.PrefixList; -import org.openecomp.policy.rest.jpa.PortList; -import org.openecomp.policy.rest.jpa.ProtocolList; -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.rest.jpa.UserInfo; -import org.openecomp.policy.rest.jpa.Zone; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -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 -public class FirewallDictionaryController { - - private static final Logger LOGGER = FlexLogger.getLogger(FirewallDictionaryController.class); - - private static CommonClassDao commonClassDao; - - @Autowired - public FirewallDictionaryController(CommonClassDao commonClassDao){ - FirewallDictionaryController.commonClassDao = commonClassDao; - } - - public FirewallDictionaryController(){} - - public UserInfo getUserInfo(String loginId){ - UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); - return name; - } - - - @RequestMapping(value={"/get_PrefixListDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPrefixListDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("prefixListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PrefixList.class, "prefixListName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_PrefixListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPrefixListDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("prefixListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PrefixList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/fw_dictionary/save_prefixList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PrefixList prefixList; - if (fromAPI) { - prefixList = (PrefixList)mapper.readValue(root.get("dictionaryFields").toString(), PrefixList.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(prefixList.getPrefixListName(), "prefixListName", PrefixList.class); - int id = 0; - PrefixList data = (PrefixList) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - prefixList.setId(1); - } else { - prefixList.setId(id); - } - } - } else { - prefixList = (PrefixList)mapper.readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); - } - if(prefixList.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(prefixList.getPrefixListName(), "prefixListName", PrefixList.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(prefixList); - } - }else{ - if(!isFakeUpdate) { - commonClassDao.update(prefixList); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(PrefixList.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{prefixListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/fw_dictionary/remove_PrefixList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePrefixListDictionary(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()); - PrefixList prefixList = (PrefixList)mapper.readValue(root.get("data").toString(), PrefixList.class); - commonClassDao.delete(prefixList); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(PrefixList.class)); - JSONObject j = new JSONObject("{prefixListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/fw_dictionary/validate_prefixList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView validatePrefixListDictionary(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()); - PrefixList prefixList = (PrefixList)mapper.readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); - String responseValidation = "success"; - try{ - CIDR.newCIDR(prefixList.getPrefixListValue()); - }catch(UnknownHostException e){ - responseValidation = "error"; - } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{result: " + responseValidation + "}"); - out.write(j.toString()); - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/get_PortListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPortListDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("portListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PortList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/fw_dictionary/save_portName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView savePortListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PortList portList = (PortList)mapper.readValue(root.get("portListDictionaryData").toString(), PortList.class); - if(portList.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(portList.getPortName(), "portName", PortList.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(portList); - } - }else{ - commonClassDao.update(portList); - } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(PortList.class)); - } - JSONObject j = new JSONObject("{portListDictionaryDatas: " + responseString + "}"); - - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/fw_dictionary/remove_PortList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePortListDictionary(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()); - PortList portList = (PortList)mapper.readValue(root.get("data").toString(), PortList.class); - commonClassDao.delete(portList); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(PortList.class)); - JSONObject j = new JSONObject("{portListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/get_ProtocolListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getProtocolListDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap(); - ObjectMapper mapper = new ObjectMapper(); - model.put("protocolListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/get_ProtocolListDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getProtocolListDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap(); - ObjectMapper mapper = new ObjectMapper(); - model.put("protocolListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ProtocolList.class, "protocolName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/fw_dictionary/save_protocolList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - ProtocolList protocolList; - if (fromAPI) { - protocolList = (ProtocolList)mapper.readValue(root.get("dictionaryFields").toString(), ProtocolList.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(protocolList.getProtocolName(), "protocolName", ProtocolList.class); - int id = 0; - ProtocolList data = (ProtocolList) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - protocolList.setId(1); - } else { - protocolList.setId(id); - } - } - } else { - protocolList = (ProtocolList)mapper.readValue(root.get("protocolListDictionaryData").toString(), ProtocolList.class); - } - if(protocolList.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(protocolList.getProtocolName(), "protocolName", ProtocolList.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(protocolList); - } - }else{ - if(!isFakeUpdate){ - commonClassDao.update(protocolList); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{protocolListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/fw_dictionary/remove_protocol"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeProtocolListDictionary(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()); - ProtocolList protocolList = (ProtocolList)mapper.readValue(root.get("data").toString(), ProtocolList.class); - commonClassDao.delete(protocolList); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class)); - JSONObject j = new JSONObject("{protocolListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/get_AddressGroupDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAddressGroupDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("addressGroupDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(AddressGroup.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_AddressGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getAddressGroupDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("addressGroupDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/fw_dictionary/save_addressGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - AddressGroup addressGroup; - GridData gridData; - if (fromAPI) { - addressGroup = (AddressGroup)mapper.readValue(root.get("dictionaryFields").toString(), AddressGroup.class); - gridData = (GridData)mapper.readValue(root.get("dictionaryFields").toString(), GridData.class); - - if(!addressGroup.getGroupName().startsWith("Group_")){ - String groupName = "Group_"+addressGroup.getGroupName(); - addressGroup.setGroupName(groupName); - } - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class); - int id = 0; - AddressGroup data = (AddressGroup) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - addressGroup.setId(1); - } else { - addressGroup.setId(id); - } - } - } else { - addressGroup = (AddressGroup)mapper.readValue(root.get("addressGroupDictionaryData").toString(), AddressGroup.class); - gridData = (GridData)mapper.readValue(root.get("addressGroupDictionaryData").toString(), GridData.class); - if(!addressGroup.getGroupName().startsWith("Group_")){ - String groupName = "Group_"+addressGroup.getGroupName(); - addressGroup.setGroupName(groupName); - } - } - String userValue = ""; - int counter = 0; - if(gridData.getAttributes().size() > 0){ - for(Object attribute : gridData.getAttributes()){ - if(attribute instanceof LinkedHashMap){ - String key = ((LinkedHashMap) attribute).get("option").toString(); - if(counter>0){ - userValue = userValue + ","; - } - userValue = userValue + key ; - counter ++; - } - } - } - addressGroup.setServiceList(userValue); - if(addressGroup.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(addressGroup); - } - }else{ - if (!isFakeUpdate) { - commonClassDao.update(addressGroup); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class)); - } - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{addressGroupDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/fw_dictionary/remove_AddressGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeAddressGroupDictionary(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()); - AddressGroup addressGroup = (AddressGroup)mapper.readValue(root.get("data").toString(), AddressGroup.class); - commonClassDao.delete(addressGroup); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class)); - JSONObject j = new JSONObject("{addressGroupDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/get_ActionListDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getActionListDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - List list = commonClassDao.getData(ActionList.class); - List dictList = new ArrayList<>(); - for(int i = 0; i < list.size(); i++){ - ActionList dict = (ActionList) list.get(i); - dictList.add(dict.getActionName()); - } - model.put("actionListDictionaryDatas", mapper.writeValueAsString(dictList)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_ActionListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getActionListDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("actionListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ActionList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/fw_dictionary/save_ActionList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - ActionList actionList; - if (fromAPI) { - actionList = (ActionList)mapper.readValue(root.get("dictionaryFields").toString(), ActionList.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(actionList.getActionName(), "actionName", ActionList.class); - int id = 0; - ActionList data = (ActionList) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - actionList.setId(1); - } else { - actionList.setId(id); - } - } - } else { - actionList = (ActionList)mapper.readValue(root.get("actionListDictionaryData").toString(), ActionList.class); - } - if(actionList.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(actionList.getActionName(), "actionName", ActionList.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(actionList); - } - }else{ - if(!isFakeUpdate) { - commonClassDao.update(actionList); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(ActionList.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{actionListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/fw_dictionary/remove_ActionList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeActionListDictionary(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()); - ActionList actionList = (ActionList)mapper.readValue(root.get("data").toString(), ActionList.class); - commonClassDao.delete(actionList); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(ActionList.class)); - JSONObject j = new JSONObject("{actionListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/get_ServiceGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getServiceGroupDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("serviceGroupDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/get_ServiceGroupDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getServiceGroupDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("serviceGroupDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(GroupServiceList.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/fw_dictionary/save_serviceGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - GroupServiceList groupServiceList; - GridData gridData; - if (fromAPI) { - groupServiceList = (GroupServiceList)mapper.readValue(root.get("dictionaryFields").toString(), GroupServiceList.class); - gridData = (GridData)mapper.readValue(root.get("dictionaryFields").toString(), GridData.class); - - if(!groupServiceList.getGroupName().startsWith("Group_")){ - String groupName = "Group_"+groupServiceList.getGroupName(); - groupServiceList.setGroupName(groupName); - } - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(groupServiceList.getGroupName(), "name", GroupServiceList.class); - int id = 0; - GroupServiceList data = (GroupServiceList) duplicateData.get(0); - id = data.getId(); - - if(id==0){ - isFakeUpdate=true; - groupServiceList.setId(1); - } else { - groupServiceList.setId(id); - } - } - } else { - groupServiceList = (GroupServiceList)mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GroupServiceList.class); - gridData = (GridData)mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GridData.class); - } - if(!groupServiceList.getGroupName().startsWith("Group_")){ - String groupName = "Group_"+groupServiceList.getGroupName(); - groupServiceList.setGroupName(groupName); - } - String userValue = ""; - int counter = 0; - if(gridData.getAttributes().size() > 0){ - for(Object attribute : gridData.getAttributes()){ - if(attribute instanceof LinkedHashMap){ - String key = ((LinkedHashMap) attribute).get("option").toString(); - if(counter>0){ - userValue = userValue + ","; - } - userValue = userValue + key ; - counter ++; - } - } - } - groupServiceList.setServiceList(userValue); - if(groupServiceList.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(groupServiceList.getGroupName(), "name", GroupServiceList.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(groupServiceList); - } - }else{ - if(!isFakeUpdate) { - commonClassDao.update(groupServiceList); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{serviceGroupDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/fw_dictionary/remove_serviceGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeServiceGroupDictionary(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()); - GroupServiceList groupServiceList = (GroupServiceList)mapper.readValue(root.get("data").toString(), GroupServiceList.class); - commonClassDao.delete(groupServiceList); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class)); - JSONObject j = new JSONObject("{serviceGroupDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - System.out.println(e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/get_SecurityZoneDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getSecurityZoneDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("securityZoneDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(SecurityZone.class, "zoneName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_SecurityZoneData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getSecurityZoneDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("securityZoneDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/fw_dictionary/save_securityZone"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - SecurityZone securityZone; - if (fromAPI) { - securityZone = (SecurityZone)mapper.readValue(root.get("dictionaryFields").toString(), SecurityZone.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(securityZone.getZoneName(), "zoneName", SecurityZone.class); - int id = 0; - SecurityZone data = (SecurityZone) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - securityZone.setId(1); - } else { - securityZone.setId(id); - } - } - } else { - securityZone = (SecurityZone)mapper.readValue(root.get("securityZoneDictionaryData").toString(), SecurityZone.class); - } - if(securityZone.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(securityZone.getZoneName(), "zoneName", SecurityZone.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(securityZone); - } - }else{ - if(!isFakeUpdate) { - commonClassDao.update(securityZone); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{securityZoneDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/fw_dictionary/remove_securityZone"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeSecurityZoneDictionary(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()); - SecurityZone securityZone = (SecurityZone)mapper.readValue(root.get("data").toString(), SecurityZone.class); - commonClassDao.delete(securityZone); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class)); - JSONObject j = new JSONObject("{securityZoneDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - - @RequestMapping(value={"/get_ServiceListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getServiceListDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("serviceListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ServiceList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/get_ServiceListDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getServiceListDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("serviceListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ServiceList.class, "serviceName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/fw_dictionary/save_serviceList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - ServiceList serviceList; - GridData serviceListGridData; - if (fromAPI) { - serviceList = (ServiceList)mapper.readValue(root.get("dictionaryFields").toString(), ServiceList.class); - serviceListGridData = (GridData)mapper.readValue(root.get("dictionaryFields").toString(), GridData.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(serviceList.getServiceName(), "serviceName", ServiceList.class); - int id = 0; - ServiceList data = (ServiceList) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - serviceList.setId(1); - } else { - serviceList.setId(id); - } - } - }else{ - serviceList = (ServiceList)mapper.readValue(root.get("serviceListDictionaryData").toString(), ServiceList.class); - serviceListGridData = (GridData)mapper.readValue(root.get("serviceListDictionaryData").toString(), GridData.class); - } - String tcpValue = ""; - int counter = 0; - if(serviceListGridData.getTransportProtocols().size() > 0){ - for(Object attribute : serviceListGridData.getTransportProtocols()){ - if(attribute instanceof LinkedHashMap){ - String key = ((LinkedHashMap) attribute).get("option").toString(); - if(counter>0){ - tcpValue = tcpValue + ","; - } - tcpValue = tcpValue + key ; - counter ++; - } - } - } - serviceList.setServiceTransProtocol(tcpValue); - String appValue = ""; - int counter1 = 0; - if(serviceListGridData.getAppProtocols().size() > 0){ - for(Object attribute : serviceListGridData.getAppProtocols()){ - if(attribute instanceof LinkedHashMap){ - String key = ((LinkedHashMap) attribute).get("option").toString(); - if(counter1>0){ - appValue = appValue + ","; - } - appValue = appValue + key ; - counter1 ++; - } - } - } - serviceList.setServiceAppProtocol(appValue); - serviceList.setServiceType("SERVICE"); - if(serviceList.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(serviceList.getServiceName(), "serviceName", ServiceList.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(serviceList); - } - }else{ - if(!isFakeUpdate) { - commonClassDao.update(serviceList); - } - } - - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(ServiceList.class)); - } - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{serviceListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - - return null; - } - - @RequestMapping(value={"/fw_dictionary/remove_serviceList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeServiceListDictionary(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()); - ServiceList serviceList = (ServiceList)mapper.readValue(root.get("data").toString(), ServiceList.class); - commonClassDao.delete(serviceList); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(ServiceList.class)); - JSONObject j = new JSONObject("{serviceListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - System.out.println(e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/get_ZoneData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getZoneDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("zoneDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(Zone.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error("Exception Occured"+e); - } - } - - @RequestMapping(value={"/get_ZoneDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getZoneDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("zoneDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(Zone.class, "zoneName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/fw_dictionary/save_zoneName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - Zone zone; - if (fromAPI) { - zone = (Zone)mapper.readValue(root.get("dictionaryFields").toString(), Zone.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(zone.getZoneName(), "zoneName", Zone.class); - int id = 0; - Zone data = (Zone) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - zone.setId(1); - } else { - zone.setId(id); - } - } - } else { - zone = (Zone)mapper.readValue(root.get("zoneDictionaryData").toString(), Zone.class); - } - if(zone.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(zone.getZoneName(), "zoneName", Zone.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(zone); - } - }else{ - if(!isFakeUpdate) { - commonClassDao.update(zone); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(Zone.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{zoneDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/fw_dictionary/remove_zone"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeZoneDictionary(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()); - Zone zone = (Zone)mapper.readValue(root.get("data").toString(), Zone.class); - commonClassDao.delete(zone); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(Zone.class)); - JSONObject j = new JSONObject("{zoneDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/get_TermListDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTermListDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap(); - ObjectMapper mapper = new ObjectMapper(); - model.put("termListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(TermList.class, "termName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_TermListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTermListDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap(); - ObjectMapper mapper = new ObjectMapper(); - model.put("termListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(TermList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/fw_dictionary/save_termList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - TermList termList; - TermListData termListDatas; - String userId = null; - if (fromAPI) { - termList = (TermList)mapper.readValue(root.get("dictionaryFields").toString(), TermList.class); - termListDatas = (TermListData)mapper.readValue(root.get("dictionaryFields").toString(), TermListData.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(termList.getTermName(), "termName", TermList.class); - int id = 0; - TermList data = (TermList) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - termList.setId(1); - } else { - termList.setId(id); - } - termList.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - termList = (TermList)mapper.readValue(root.get("termListDictionaryData").toString(), TermList.class); - termListDatas = (TermListData)mapper.readValue(root.get("termListDictionaryData").toString(), TermListData.class); - userId = root.get("userid").textValue(); - } - String fromZoneValue = ""; - int counter = 0; - if(termListDatas.getFromZoneDatas().size() > 0){ - for(Object fromZone : termListDatas.getFromZoneDatas()){ - if(fromZone instanceof LinkedHashMap){ - String key = ((LinkedHashMap) fromZone).get("option").toString(); - if(counter>0){ - fromZoneValue = fromZoneValue + ","; - } - fromZoneValue = fromZoneValue + key ; - counter ++; - } - } - } - termList.setFromZones(fromZoneValue); - - String toZoneValue = ""; - int toZonecounter = 0; - if(termListDatas.getToZoneDatas().size() > 0){ - for(Object toZone : termListDatas.getToZoneDatas()){ - if(toZone instanceof LinkedHashMap){ - String key = ((LinkedHashMap) toZone).get("option").toString(); - if(toZonecounter>0){ - toZoneValue = toZoneValue + ","; - } - toZoneValue = toZoneValue + key ; - toZonecounter ++; - } - } - } - termList.setToZones(toZoneValue); - - String srcListValues = ""; - int srcListcounter = 0; - if(termListDatas.getSourceListDatas().size() > 0){ - for(Object srcList : termListDatas.getSourceListDatas()){ - if(srcList instanceof LinkedHashMap){ - String key = ((LinkedHashMap) srcList).get("option").toString(); - if(srcListcounter>0){ - srcListValues = srcListValues + ","; - } - srcListValues = srcListValues + key ; - srcListcounter ++; - } - } - } - termList.setSrcIPList(srcListValues); - - String desListValues = ""; - int destListcounter = 0; - if(termListDatas.getDestinationListDatas().size() > 0){ - for(Object desList : termListDatas.getDestinationListDatas()){ - if(desList instanceof LinkedHashMap){ - String key = ((LinkedHashMap) desList).get("option").toString(); - if(destListcounter>0){ - desListValues = desListValues + ","; - } - desListValues = desListValues + key ; - destListcounter ++; - } - } - } - termList.setDestIPList(desListValues); - - String srcSerValue = ""; - int srcSercounter = 0; - if(termListDatas.getSourceServiceDatas().size() > 0){ - for(Object srcSrc : termListDatas.getSourceServiceDatas()){ - if(srcSrc instanceof LinkedHashMap){ - String key = ((LinkedHashMap) srcSrc).get("option").toString(); - if(srcSercounter>0){ - srcSerValue = srcSerValue + ","; - } - srcSerValue = srcSerValue + key ; - srcSercounter ++; - } - } - } - termList.setSrcPortList(srcSerValue); - - String desSrcValue = ""; - int desSrccounter = 0; - if(termListDatas.getDestinationServiceDatas().size() > 0){ - for(Object desSrc : termListDatas.getDestinationServiceDatas()){ - if(desSrc instanceof LinkedHashMap){ - String key = ((LinkedHashMap) desSrc).get("option").toString(); - if(desSrccounter>0){ - desSrcValue = desSrcValue + ","; - } - desSrcValue = desSrcValue + key ; - desSrccounter ++; - } - } - } - termList.setDestPortList(desSrcValue); - - String actionValue = ""; - int actioncounter = 0; - if(termListDatas.getActionListDatas().size() > 0){ - for(Object actionList : termListDatas.getActionListDatas()){ - if(actionList instanceof LinkedHashMap){ - String key = ((LinkedHashMap) actionList).get("option").toString(); - if(actioncounter>0){ - actionValue = actionValue + ","; - } - actionValue = actionValue + key ; - actioncounter ++; - } - } - } - termList.setAction(actionValue); - - if(termList.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(termList.getTermName(), "termName", TermList.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - termList.setUserCreatedBy(this.getUserInfo(userId)); - termList.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(termList); - } - }else{ - if(!isFakeUpdate) { - termList.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.update(termList); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(TermList.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{termListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/fw_dictionary/remove_termList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeTermListDictionary(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()); - TermList termList = (TermList)mapper.readValue(root.get("data").toString(), TermList.class); - commonClassDao.delete(termList); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(TermList.class)); - JSONObject j = new JSONObject("{termListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - //ParentList Dictionary Data - @RequestMapping(value={"/get_FWDictionaryListDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getFWDictListDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("fwDictListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FirewallDictionaryList.class, "parentItemName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_FWDictionaryListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getFWDictionaryListEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("fwDictListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value={"/fw_dictionary/save_FWDictionaryList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveFWDictionaryList(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - FirewallDictionaryList fwDictList = (FirewallDictionaryList)mapper.readValue(root.get("fwDictListDictionaryData").toString(), FirewallDictionaryList.class); - GridData gridData = (GridData)mapper.readValue(root.get("fwDictListDictionaryData").toString(), GridData.class); - String userSLValue = ""; - int slcounter = 0; - if(gridData.getAttributes().size() > 0){ - for(Object attribute : gridData.getAttributes()){ - if(attribute instanceof LinkedHashMap){ - String key = ((LinkedHashMap) attribute).get("option").toString(); - if(slcounter>0){ - userSLValue = userSLValue + ","; - } - userSLValue = userSLValue + key ; - slcounter ++; - } - } - } - fwDictList.setServiceList(userSLValue); - String userALValue = ""; - int alcounter = 0; - if(gridData.getAlAttributes().size() > 0){ - for(Object attribute : gridData.getAlAttributes()){ - if(attribute instanceof LinkedHashMap){ - String key = ((LinkedHashMap) attribute).get("option").toString(); - if(alcounter>0){ - userALValue = userALValue + ","; - } - userALValue = userALValue + key ; - alcounter ++; - } - } - } - fwDictList.setAddressList(userALValue); - if(fwDictList.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(fwDictList.getParentItemName(), "parentItemName", FirewallDictionaryList.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(fwDictList); - } - }else{ - commonClassDao.update(fwDictList); - } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class)); - } - JSONObject j = new JSONObject("{fwDictListDictionaryDatas: " + responseString + "}"); - - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/fw_dictionary/remove_FWDictionaryList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeFWDictionaryListy(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()); - FirewallDictionaryList fwDictList = (FirewallDictionaryList)mapper.readValue(root.get("data").toString(), FirewallDictionaryList.class); - commonClassDao.delete(fwDictList); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class)); - JSONObject j = new JSONObject("{fwDictListDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - - @RequestMapping(value={"/get_TagPickerNameByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTagPickerNameEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap(); - ObjectMapper mapper = new ObjectMapper(); - model.put("fwTagPickerDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FWTagPicker.class, "tagPickerName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_TagPickerListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTagPickerDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap(); - ObjectMapper mapper = new ObjectMapper(); - model.put("fwTagPickerDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/fw_dictionary/save_fwTagPicker"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveFirewallTagPickerDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - - - FWTagPicker fwTagPicker; - TagGridValues data; - String userId = null; - if (fromAPI) { - fwTagPicker = (FWTagPicker)mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), FWTagPicker.class); - data = (TagGridValues)mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), TagGridValues.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(fwTagPicker.getTagPickerName(), "tagPickerName", FWTagPicker.class); - int id = 0; - FWTagPicker dbdata = (FWTagPicker) duplicateData.get(0); - id = dbdata.getId(); - fwTagPicker.setId(id); - fwTagPicker.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - - fwTagPicker = (FWTagPicker)mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), FWTagPicker.class); - data = (TagGridValues)mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), TagGridValues.class); - userId = root.get("userid").textValue(); - } - - String header = ""; - int counter = 0; - if(data.getTags().size() > 0){ - for(Object attribute : data.getTags()){ - if(attribute instanceof LinkedHashMap){ - String key = ((LinkedHashMap) attribute).get("option").toString(); - String value = ((LinkedHashMap) attribute).get("number").toString(); - if(counter>0){ - header = header + "#"; - } - header = header + key + ":"; - header = header + value; - counter ++; - } - } - } - fwTagPicker.setTagValues(header); - if(fwTagPicker.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(fwTagPicker.getTagPickerName(), "tagPickerName", FWTagPicker.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - fwTagPicker.setUserCreatedBy(this.getUserInfo(userId)); - fwTagPicker.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(fwTagPicker); - } - }else{ - fwTagPicker.setUserModifiedBy(this.getUserInfo(userId)); - fwTagPicker.setModifiedDate(new Date()); - commonClassDao.update(fwTagPicker); - } - - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - responseString = "Success"; - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{fwTagPickerDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/fw_dictionary/remove_tagPicker"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeFirewallTagPickerDictionary(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()); - FWTagPicker fwTagPicker = (FWTagPicker)mapper.readValue(root.get("data").toString(), FWTagPicker.class); - commonClassDao.delete(fwTagPicker); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - String responseString = mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class)); - JSONObject j = new JSONObject("{fwTagPickerDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - - @RequestMapping(value={"/get_TagNameByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTagNameEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("fwTagDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FWTag.class, "fwTagName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/get_TagListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getTagDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("fwTagDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(FWTag.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - } - - @RequestMapping(value={"/fw_dictionary/save_fwTag"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveFirewallTagDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - - - FWTag fwTag; - TagGridValues tagGridValues; - String userId = null; - if (fromAPI) { - fwTag = (FWTag)mapper.readValue(root.get("fwTagDictionaryDatas").toString(), FWTag.class); - tagGridValues = (TagGridValues)mapper.readValue(root.get("fwTagDictionaryDatas").toString(), TagGridValues.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), "tagName", FWTag.class); - int id = 0; - FWTag data = (FWTag) duplicateData.get(0); - id = data.getId(); - fwTag.setId(id); - fwTag.setUserCreatedBy(this.getUserInfo(userId)); - - } - } else { - fwTag = (FWTag)mapper.readValue(root.get("fwTagDictionaryData").toString(), FWTag.class); - tagGridValues = (TagGridValues)mapper.readValue(root.get("fwTagDictionaryData").toString(), TagGridValues.class); - userId = root.get("userid").textValue(); - } - - String userValue = ""; - int counter = 0; - if(tagGridValues.getTags().size() > 0){ - for(Object attribute : tagGridValues.getTags()){ - if(attribute instanceof LinkedHashMap){ - String key = ((LinkedHashMap) attribute).get("tags").toString(); - if(counter>0){ - userValue = userValue + ","; - } - userValue = userValue + key ; - counter ++; - } - } - } - fwTag.setTagValues(userValue); - if(fwTag.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), "fwTagName", FWTag.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - fwTag.setUserCreatedBy(this.getUserInfo(userId)); - fwTag.setUserModifiedBy(this.getUserInfo(userId)); - commonClassDao.save(fwTag); - } - }else{ - fwTag.setUserModifiedBy(this.getUserInfo(userId)); - fwTag.setModifiedDate(new Date()); - commonClassDao.update(fwTag); - } - - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(FWTag.class)); - } - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - responseString = "Success"; - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{fwTagDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - return null; - } - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/fw_dictionary/remove_tagList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeFirewallTagDictionary(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()); - FWTag fwTag = (FWTag)mapper.readValue(root.get("data").toString(), FWTag.class); - commonClassDao.delete(fwTag); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(FWTag.class)); - JSONObject j = new JSONObject("{fwTagDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } -} - -class TagGridValues{ - private ArrayList tags; - - public ArrayList getTags() { - return tags; - } - - public void setTags(ArrayList tags) { - this.tags = tags; - } -} - -class AGGridData{ - private ArrayList attributes; - - public ArrayList getAttributes() { - return attributes; - } - - public void setAttributes(ArrayList attributes) { - this.attributes = attributes; - } -} - -class TermListData{ - private ArrayList fromZoneDatas; - private ArrayList toZoneDatas; - private ArrayList sourceListDatas; - private ArrayList destinationListDatas; - private ArrayList sourceServiceDatas; - private ArrayList destinationServiceDatas; - private ArrayList actionListDatas; - public ArrayList getFromZoneDatas() { - return fromZoneDatas; - } - public void setFromZoneDatas(ArrayList fromZoneDatas) { - this.fromZoneDatas = fromZoneDatas; - } - public ArrayList getToZoneDatas() { - return toZoneDatas; - } - public void setToZoneDatas(ArrayList toZoneDatas) { - this.toZoneDatas = toZoneDatas; - } - public ArrayList getSourceListDatas() { - return sourceListDatas; - } - public void setSourceListDatas(ArrayList sourceListDatas) { - this.sourceListDatas = sourceListDatas; - } - public ArrayList getDestinationListDatas() { - return destinationListDatas; - } - public void setDestinationListDatas(ArrayList destinationListDatas) { - this.destinationListDatas = destinationListDatas; - } - public ArrayList getSourceServiceDatas() { - return sourceServiceDatas; - } - public void setSourceServiceDatas(ArrayList sourceServiceDatas) { - this.sourceServiceDatas = sourceServiceDatas; - } - public ArrayList getDestinationServiceDatas() { - return destinationServiceDatas; - } - public void setDestinationServiceDatas(ArrayList destinationServiceDatas) { - this.destinationServiceDatas = destinationServiceDatas; - } - public ArrayList getActionListDatas() { - return actionListDatas; - } - public void setActionListDatas(ArrayList actionListDatas) { - this.actionListDatas = actionListDatas; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java deleted file mode 100644 index b933a4f84..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java +++ /dev/null @@ -1,1051 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.controller; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringUtils; -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -import org.openecomp.policy.pap.xacml.rest.util.JsonMessage; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.DCAEuuid; -import org.openecomp.policy.rest.jpa.MicroServiceAttribute; -import org.openecomp.policy.rest.jpa.MicroServiceConfigName; -import org.openecomp.policy.rest.jpa.MicroServiceLocation; -import org.openecomp.policy.rest.jpa.MicroServiceModels; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.openecomp.policy.rest.util.MSAttributeObject; -import org.openecomp.policy.rest.util.MSModelUtils; -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; -import com.google.gson.Gson; - -@Controller -public class MicroServiceDictionaryController { - private static final Logger LOGGER = FlexLogger.getLogger(MicroServiceDictionaryController.class); - - private static CommonClassDao commonClassDao; - - public static void setCommonClassDao(CommonClassDao commonClassDao) { - MicroServiceDictionaryController.commonClassDao = commonClassDao; - } - - @Autowired - public MicroServiceDictionaryController(CommonClassDao commonClassDao){ - MicroServiceDictionaryController.commonClassDao = commonClassDao; - } - - public MicroServiceDictionaryController(){} - - public UserInfo getUserInfo(String loginId){ - UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); - return name; - } - - private static String SUCCESSKEY= "successMapKey"; - private static String SUCCESS = "success"; - private static String OPERATION = "operation"; - private static String GETDICTIONARY = "getDictionary"; - private static String ERROR = "error"; - private static String DICTIONARYDBQUERY = "dictionaryDBQuery"; - private HashMap classMap; - private List modelList = new ArrayList<>(); - - - - MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsEcompName(), XACMLPapServlet.getMsPolicyName()); - private MicroServiceModels newModel; - - - @RequestMapping(value={"/get_DCAEUUIDDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getDCAEUUIDDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("dcaeUUIDDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(DCAEuuid.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e); - } - } - - @RequestMapping(value={"/get_DCAEUUIDData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getDCAEUUIDDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("dcaeUUIDDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(DCAEuuid.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(SUCCESSKEY, SUCCESS); - response.addHeader(OPERATION, GETDICTIONARY); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(ERROR, DICTIONARYDBQUERY); - LOGGER.error(e.getMessage()); - } - } - - @RequestMapping(value={"/ms_dictionary/save_dcaeUUID"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - DCAEuuid dCAEuuid; - if (fromAPI) { - dCAEuuid = (DCAEuuid)mapper.readValue(root.get("dictionaryFields").toString(), DCAEuuid.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter(OPERATION).equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(dCAEuuid.getName(), "name", DCAEuuid.class); - int id = 0; - DCAEuuid data = (DCAEuuid) duplicateData.get(0); - id = data.getId(); - if(id==0){ - isFakeUpdate=true; - dCAEuuid.setId(1); - } else { - dCAEuuid.setId(id); - } - } - } else { - dCAEuuid = (DCAEuuid)mapper.readValue(root.get("dcaeUUIDDictionaryData").toString(), DCAEuuid.class); - } - if(dCAEuuid.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(dCAEuuid.getName(), "name", DCAEuuid.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(dCAEuuid); - } - }else{ - if(!isFakeUpdate) { - commonClassDao.update(dCAEuuid); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(DCAEuuid.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{dcaeUUIDDictionaryDatas: " + 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; - } - - @RequestMapping(value={"/ms_dictionary/remove_dcaeuuid"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeDCAEUUIDDictionary(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()); - DCAEuuid dCAEuuid = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class); - commonClassDao.delete(dCAEuuid); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(DCAEuuid.class)); - JSONObject j = new JSONObject("{dcaeUUIDDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - - @RequestMapping(value={"/get_MicroServiceConfigNameDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getMicroServiceConfigNameByNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("microServiceCongigNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(MicroServiceConfigName.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e); - } - } - - - - @RequestMapping(value={"/get_MicroServiceConfigNameData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getMicroServiceConfigNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("microServiceCongigNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(MicroServiceConfigName.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(SUCCESSKEY, SUCCESS); - response.addHeader(OPERATION, GETDICTIONARY); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(ERROR, DICTIONARYDBQUERY); - LOGGER.error(e.getMessage()); - } - } - - @RequestMapping(value={"/ms_dictionary/save_configName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - MicroServiceConfigName microServiceConfigName; - if (fromAPI) { - microServiceConfigName = (MicroServiceConfigName)mapper.readValue(root.get("dictionaryFields").toString(), MicroServiceConfigName.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter(OPERATION).equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(microServiceConfigName.getName(), "name", MicroServiceConfigName.class); - int id = 0; - MicroServiceConfigName data = (MicroServiceConfigName) duplicateData.get(0); - id = data.getId(); - - if(id==0){ - isFakeUpdate=true; - microServiceConfigName.setId(1); - } else { - microServiceConfigName.setId(id); - } - } - } else { - microServiceConfigName = (MicroServiceConfigName)mapper.readValue(root.get("microServiceCongigNameDictionaryData").toString(), MicroServiceConfigName.class); - } - if(microServiceConfigName.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(microServiceConfigName.getName(), "name", MicroServiceConfigName.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(microServiceConfigName); - } - }else{ - if(!isFakeUpdate) { - commonClassDao.update(microServiceConfigName); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceConfigName.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{microServiceCongigNameDictionaryDatas: " + 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; - } - - @RequestMapping(value={"/ms_dictionary/remove_msConfigName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeMicroServiceConfigNameDictionary(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()); - MicroServiceConfigName microServiceConfigName = (MicroServiceConfigName)mapper.readValue(root.get("data").toString(), MicroServiceConfigName.class); - commonClassDao.delete(microServiceConfigName); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceConfigName.class)); - JSONObject j = new JSONObject("{microServiceCongigNameDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/get_MicroServiceLocationDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getMicroServiceLocationByNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("microServiceLocationDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(MicroServiceLocation.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e); - } - } - - @RequestMapping(value={"/get_MicroServiceLocationData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getMicroServiceLocationDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("microServiceLocationDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(MicroServiceLocation.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(SUCCESSKEY, SUCCESS); - response.addHeader(OPERATION, GETDICTIONARY); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(ERROR, DICTIONARYDBQUERY); - LOGGER.error(e.getMessage()); - } - } - - @RequestMapping(value={"/ms_dictionary/save_location"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - MicroServiceLocation microServiceLocation; - if (fromAPI) { - microServiceLocation = (MicroServiceLocation)mapper.readValue(root.get("dictionaryFields").toString(), MicroServiceLocation.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter(OPERATION).equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(microServiceLocation.getName(), "name", MicroServiceLocation.class); - int id = 0; - MicroServiceLocation data = (MicroServiceLocation) duplicateData.get(0); - id = data.getId(); - - if(id==0){ - isFakeUpdate=true; - microServiceLocation.setId(1); - } else { - microServiceLocation.setId(id); - } - } - } else { - microServiceLocation = (MicroServiceLocation)mapper.readValue(root.get("microServiceLocationDictionaryData").toString(), MicroServiceLocation.class); - } - if(microServiceLocation.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(microServiceLocation.getName(), "name", MicroServiceLocation.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(microServiceLocation); - } - }else{ - if(!isFakeUpdate) { - commonClassDao.update(microServiceLocation); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceLocation.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{microServiceLocationDictionaryDatas: " + 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; - } - - @RequestMapping(value={"/ms_dictionary/remove_msLocation"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeMicroServiceLocationDictionary(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()); - MicroServiceLocation microServiceLocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class); - commonClassDao.delete(microServiceLocation); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceLocation.class)); - JSONObject j = new JSONObject("{microServiceLocationDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/get_MicroServiceAttributeDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getMicroServiceAttributeByNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("microServiceAttributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(MicroServiceAttribute.class, "name"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e.getMessage()); - } - } - - @RequestMapping(value={"/get_MicroServiceAttributeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getMicroServiceAttributeDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("microServiceAttributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(MicroServiceAttribute.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(SUCCESSKEY, SUCCESS); - response.addHeader(OPERATION, GETDICTIONARY); - response.getWriter().write(j.toString()); - - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(ERROR, DICTIONARYDBQUERY); - LOGGER.error(e.getMessage()); - } - } - - @RequestMapping(value={"/ms_dictionary/save_modelAttribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveMicroServiceAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - - MicroServiceAttribute microServiceAttribute; - if (fromAPI) { - microServiceAttribute = (MicroServiceAttribute)mapper.readValue(root.get("dictionaryFields").toString(), MicroServiceAttribute.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter(OPERATION).equals("update")) { - MicroServiceAttribute initialAttribute = (MicroServiceAttribute)mapper.readValue(root.get("initialFields").toString(), MicroServiceAttribute.class); - - String checkValue = initialAttribute.getName() + ":" + initialAttribute.getValue() + ":" + initialAttribute.getModelName(); - List duplicateData = commonClassDao.checkDuplicateEntry(checkValue, "name:value:modelName", MicroServiceAttribute.class); - int id=0; - for (int i= 0; i duplicateData = commonClassDao.checkDuplicateEntry(checkValue, "name:value:modelName", MicroServiceAttribute.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(microServiceAttribute); - } - }else{ - commonClassDao.update(microServiceAttribute); - } - - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceAttribute.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - responseString = "Success"; - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{microServiceAttributeDictionaryDatas: " + 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; - } - - @RequestMapping(value={"/ms_dictionary/remove_modelAttribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeMicroServiceAttributeDictionary(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()); - MicroServiceAttribute microServiceAttribute = (MicroServiceAttribute)mapper.readValue(root.get("data").toString(), MicroServiceAttribute.class); - commonClassDao.delete(microServiceAttribute); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(MicroServiceDictionaryController.commonClassDao.getData(MicroServiceAttribute.class)); - JSONObject j = new JSONObject("{microServiceAttributeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(e.getMessage()); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - - @RequestMapping(value={"/get_MicroServiceModelsDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getMicroServiceModelsDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("microServiceModelsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(MicroServiceModels.class, "modelName"))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e.getMessage()); - } - } - - @RequestMapping(value={"/get_MicroServiceModelsDataByVersion"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getMicroServiceModelsDictionaryByVersionEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - JsonNode root = mapper.readTree(request.getReader()); - String modelName = null; - if (root.get("microServiceModelsDictionaryData").has("modelName")){ - modelName = root.get("microServiceModelsDictionaryData").get("modelName").asText().replace("\"", ""); - } - if (modelName!=null){ - model.put("microServiceModelsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataById(MicroServiceModels.class, "modelName", modelName))); - } else{ - model.put(ERROR, "No model name given"); - } - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - LOGGER.error(e.getMessage()); - } - } - - @RequestMapping(value={"/get_MicroServiceModelsData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getMicroServiceModelsDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("microServiceModelsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(MicroServiceModels.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(SUCCESSKEY, SUCCESS); - response.addHeader(OPERATION, GETDICTIONARY); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(ERROR, DICTIONARYDBQUERY); - LOGGER.error(e.getMessage()); - } - } - - @RequestMapping(value={"/get_MicroServiceModelsDataServiceVersion"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getMicroServiceModelsDictionaryEntityDataServiceVersion(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - List data = new ArrayList<>(); - List datas = commonClassDao.getData(MicroServiceModels.class); - for(int i = 0; i < datas.size(); i++){ - MicroServiceModels msmodel = (MicroServiceModels) datas.get(i); - if (!data.contains(msmodel.getModelName())){ - data.add(msmodel.getModelName() + "-v" + msmodel.getVersion()); - } - } - model.put("microServiceModelsDictionaryDatas", mapper.writeValueAsString(data)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - LOGGER.error(e); - } - } - - @RequestMapping(value={"/get_MicroServiceModelsDataByClass"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getMicroServiceModelsDictionaryClassEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("microServiceModelsDictionaryClassDatas", mapper.writeValueAsString(modelList)); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(SUCCESSKEY, SUCCESS); - response.addHeader(OPERATION, GETDICTIONARY); - response.getWriter().write(j.toString()); - - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader(ERROR, DICTIONARYDBQUERY); - LOGGER.error(e.getMessage()); - } - } - - @RequestMapping(value={"/ms_dictionary/save_model"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView saveMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean fromAPI = false; - this.newModel = new MicroServiceModels(); - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - MicroServiceModels microServiceModels = new MicroServiceModels(); - String userId = null; - - if(root.has("modelType")){ - JsonNode dataType = root.get("modelType"); - String modelType= dataType.toString(); - if(modelType.contains("yml")){ - if (root.has("microServiceModelsDictionaryData")){ - if (root.get("microServiceModelsDictionaryData").has("description")){ - microServiceModels.setDescription(root.get("microServiceModelsDictionaryData").get("description").asText().replace("\"", "")); - } - if (root.get("microServiceModelsDictionaryData").has("modelName")){ - microServiceModels.setModelName(root.get("microServiceModelsDictionaryData").get("modelName").asText().replace("\"", "")); - this.newModel.setModelName(microServiceModels.getModelName()); - } - if (root.get("microServiceModelsDictionaryData").has("version")){ - microServiceModels.setVersion(root.get("microServiceModelsDictionaryData").get("version").asText().replace("\"", "")); - this.newModel.setVersion(microServiceModels.getVersion()); - } - } - - MSAttributeObject mainClass = null; - classMap = new HashMap<>(); - JsonNode data = root.get("classMap"); - ObjectMapper mapper1 = new ObjectMapper(); - String data1 = data.toString().substring(1, data.toString().length()-1); - data1 = data1.replace("\\", ""); - data1=data1.replace("\"{","{"); - data1=data1.replace("}\"","}"); - JSONObject jsonObject = new JSONObject(data1); - Set keys = jsonObject.keySet(); - for(String key : keys){ - String value = jsonObject.get(key).toString(); - MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class); - classMap.put(key, msAttributeObject); - } - - userId = root.get("userid").textValue(); - mainClass = classMap.get(this.newModel.getModelName()); - this.newModel.setDependency("[]"); - String value = new Gson().toJson(mainClass.getSubClass()); - this.newModel.setSub_attributes(value); - String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", ""); - int equalsIndexForAttributes= attributes.indexOf("="); - String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1); - this.newModel.setAttributes(atttributesAfterFirstEquals); - String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); - int equalsIndex= refAttributes.indexOf("="); - String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1); - this.newModel.setRef_attributes(refAttributesAfterFirstEquals); - this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); - this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); - - }else{ - if (fromAPI) { - microServiceModels = (MicroServiceModels)mapper.readValue(root.get("dictionaryFields").toString(), MicroServiceModels.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter(OPERATION).equals("update")) { - String checkName = microServiceModels.getModelName() + ":" + microServiceModels.getVersion(); - List duplicateData = commonClassDao.checkDuplicateEntry(checkName, "modelName:version", MicroServiceModels.class); - int id = 0; - for (int i=0; i< duplicateData.size(); i++){ - MicroServiceModels data = (MicroServiceModels) duplicateData.get(0); - id = data.getId(); - } - microServiceModels.setId(id); - microServiceModels.setUserCreatedBy(this.getUserInfo(userId)); - - } - } else { - if (root.has("microServiceModelsDictionaryData")){ - if (root.get("microServiceModelsDictionaryData").has("description")){ - microServiceModels.setDescription(root.get("microServiceModelsDictionaryData").get("description").asText().replace("\"", "")); - } - if (root.get("microServiceModelsDictionaryData").has("modelName")){ - microServiceModels.setModelName(root.get("microServiceModelsDictionaryData").get("modelName").asText().replace("\"", "")); - this.newModel.setModelName(microServiceModels.getModelName()); - } - if (root.get("microServiceModelsDictionaryData").has("version")){ - microServiceModels.setVersion(root.get("microServiceModelsDictionaryData").get("version").asText().replace("\"", "")); - this.newModel.setVersion(microServiceModels.getVersion()); - } - } - if(root.has("classMap")){ - classMap = new HashMap<>(); - JsonNode data = root.get("classMap"); - ObjectMapper mapper1 = new ObjectMapper(); - String data1 = data.toString().substring(1, data.toString().length()-1); - data1 = data1.replace("\\", ""); - JSONObject jsonObject = new JSONObject(data1); - Set keys = jsonObject.keySet(); - for(String key : keys){ - String value = jsonObject.get(key).toString(); - MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class); - classMap.put(key, msAttributeObject); - } - } - userId = root.get("userid").textValue(); - addValuesToNewModel(classMap); - } - } - - } - microServiceModels.setAttributes(this.newModel.getAttributes()); - microServiceModels.setRef_attributes(this.newModel.getRef_attributes()); - microServiceModels.setDependency(this.newModel.getDependency()); - microServiceModels.setModelName(this.newModel.getModelName()); - microServiceModels.setSub_attributes(this.newModel.getSub_attributes()); - microServiceModels.setVersion(this.newModel.getVersion()); - microServiceModels.setEnumValues(this.newModel.getEnumValues()); - microServiceModels.setAnnotation(this.newModel.getAnnotation()); - - if(microServiceModels.getId() == 0){ - String checkName = microServiceModels.getModelName() + ":" + microServiceModels.getVersion(); - List duplicateData = commonClassDao.checkDuplicateEntry(checkName, "modelName:version", MicroServiceModels.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - microServiceModels.setUserCreatedBy(this.getUserInfo(userId)); - commonClassDao.save(microServiceModels); - } - }else{ - commonClassDao.update(microServiceModels); - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceModels.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - responseString = "Success"; - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{microServiceModelsDictionaryDatas: " + 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; - } - - @RequestMapping(value={"/ms_dictionary/remove_msModel"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removeMicroServiceModelsDictionary(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()); - MicroServiceModels microServiceModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class); - commonClassDao.delete(microServiceModels); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceModels.class)); - JSONObject j = new JSONObject("{microServiceModelsDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - LOGGER.error(e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - private void addValuesToNewModel(HashMap classMap) { - new MicroServiceModels(); - //Loop through the classmap and pull out the required info for the new file. - MSAttributeObject mainClass = null; - ArrayList dependency = null; - String subAttribute = null; - - mainClass = classMap.get(this.newModel.getModelName()); - - if (mainClass !=null){ - String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""}); - dependency = new ArrayList(Arrays.asList(dependTemp.split(","))); - dependency = getFullDependencyList(dependency); - for (String element : dependency){ - MSAttributeObject temp = new MSAttributeObject(); - temp = classMap.get(element); - if (temp!=null){ - mainClass.addAllRefAttribute(temp.getRefAttribute()); - mainClass.addAllAttribute(temp.getAttribute()); - } - } - subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName()); - }else{ - subAttribute = "{}"; - this.newModel.setDependency(""); - } - - if (mainClass != null && mainClass.getDependency()==null){ - mainClass.setDependency(""); - } - if(mainClass != null){ - this.newModel.setDependency(mainClass.getDependency()); - this.newModel.setSub_attributes(subAttribute); - this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", "")); - this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", "")); - this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); - this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); - } - } - - private ArrayList getFullDependencyList(ArrayList dependency) { - ArrayList returnList = new ArrayList<>(); - ArrayList workingList = new ArrayList<>(); - returnList.addAll(dependency); - for (String element : dependency ){ - if (classMap.containsKey(element)){ - MSAttributeObject value = classMap.get(element); - String rawValue = StringUtils.replaceEach(value.getDependency(), new String[]{"[", "]"}, new String[]{"", ""}); - workingList = new ArrayList(Arrays.asList(rawValue.split(","))); - for(String depend : workingList){ - if (!returnList.contains(depend) && !depend.isEmpty()){ - returnList.add(depend.trim()); - //getFullDepedency(workingList) - } - } - } - } - - return returnList; - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java deleted file mode 100644 index 08635c157..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java +++ /dev/null @@ -1,927 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.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.apache.commons.lang.StringUtils; -import org.json.JSONObject; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.util.JsonMessage; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.GroupPolicyScopeList; -import org.openecomp.policy.rest.jpa.PolicyScopeClosedLoop; -import org.openecomp.policy.rest.jpa.PolicyScopeResource; -import org.openecomp.policy.rest.jpa.PolicyScopeService; -import org.openecomp.policy.rest.jpa.PolicyScopeType; -import org.openecomp.policy.rest.jpa.UserInfo; -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 -public class PolicyScopeDictionaryController { - - private static final Logger LOGGER = FlexLogger.getLogger(PolicyScopeDictionaryController.class); - - private static CommonClassDao commonClassDao; - - @Autowired - public PolicyScopeDictionaryController(CommonClassDao commonClassDao){ - PolicyScopeDictionaryController.commonClassDao = commonClassDao; - } - - public PolicyScopeDictionaryController(){} - - private static String SUCCESSMAPKEY = "successMapKey"; - - public UserInfo getUserInfo(String loginId){ - UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); - return name; - } - - @RequestMapping(value={"/get_GroupPolicyScopeDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getGroupPolicyScopeEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("groupPolicyScopeListDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(GroupPolicyScopeList.class, "name"))); - 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={"/get_GroupPolicyScopeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getGroupPolicyScopeEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("groupPolicyScopeListDatas", mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(SUCCESSMAPKEY, "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - LOGGER.error(e); - } - } - - @RequestMapping(value={"/ps_dictionary/save_psGroupPolicyScope"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean duplicateGroupFlag = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - //GroupPolicyScopeList gpdata = (GroupPolicyScopeList)mapper.readValue(root.get("groupPolicyScopeListData").toString(), GroupPolicyScopeList.class); - GroupPolicyScopeList gpdata = null; - GroupPolicyScope groupData = null; - if (fromAPI) { - gpdata = (GroupPolicyScopeList)mapper.readValue(root.get("dictionaryFields").toString(), GroupPolicyScopeList.class); - try{ - groupData = (GroupPolicyScope)mapper.readValue(root.get("groupPolicyScopeListData1").toString(), GroupPolicyScope.class); - }catch(Exception e){ - groupData = new GroupPolicyScope(); - groupData.setResource(root.get("dictionaryFields").get("resource").toString().replace("\"", "")); - groupData.setClosedloop(root.get("dictionaryFields").get("closedloop").toString().replace("\"", "")); - groupData.setService(root.get("dictionaryFields").get("service").toString().replace("\"", "")); - groupData.setType(root.get("dictionaryFields").get("type").toString().replace("\"", "")); - } - - if(!gpdata.getGroupName().startsWith("PolicyScope")){ - String name = "PolicyScope_" + gpdata.getGroupName(); - gpdata.setGroupName(name); - } - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - - List duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupName(), "name", GroupPolicyScopeList.class); - int id = 0; - for (int i =0; i< duplicateData.size(); i++){ - GroupPolicyScopeList data = (GroupPolicyScopeList) duplicateData.get(0); - id = data.getId(); - } - - if(id==0){ - isFakeUpdate=true; - gpdata.setId(1); - } else { - gpdata.setId(id); - } - - } - } else { - gpdata = (GroupPolicyScopeList)mapper.readValue(root.get("groupPolicyScopeListData").toString(), GroupPolicyScopeList.class); - - try{ - groupData = (GroupPolicyScope)mapper.readValue(root.get("groupPolicyScopeListData1").toString(), GroupPolicyScope.class); - }catch(Exception e){ - groupData = new GroupPolicyScope(); - groupData.setResource(root.get("groupPolicyScopeListData1").get("resource").toString().replace("\"", "")); - groupData.setClosedloop(root.get("groupPolicyScopeListData1").get("closedloop").toString().replace("\"", "")); - groupData.setService(root.get("groupPolicyScopeListData1").get("service").toString().replace("\"", "")); - groupData.setType(root.get("groupPolicyScopeListData1").get("type").toString().replace("\"", "")); - } - if(!gpdata.getGroupName().startsWith("PolicyScope")){ - String name = "PolicyScope_" + gpdata.getGroupName(); - gpdata.setGroupName(name); - } - - } - ArrayList valueList = new ArrayList<>(); - String list = null; - String resourceValue = groupData.getResource(); - String typeValue = groupData.getType(); - String serviceValue = groupData.getService(); - String closedLoopValue = groupData.getClosedloop(); - valueList.add("resource=" + resourceValue); - valueList.add("service=" + serviceValue); - valueList.add("type=" + typeValue); - valueList.add("closedLoopControlName=" + closedLoopValue); - list = StringUtils.replaceEach(valueList.toString(), new String[]{"[", "]", " "}, new String[]{"", "", ""}); - gpdata.setGroupList(list); - if(!gpdata.getGroupName().startsWith("PolicyScope")){ - String name = "PolicyScope_" + gpdata.getGroupName(); - gpdata.setGroupName(name); - } - if(gpdata.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupName(), "name", GroupPolicyScopeList.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupList(), "groupList", GroupPolicyScopeList.class); - if(!duplicateData.isEmpty()){ - duplicateGroupFlag = true; - }else{ - commonClassDao.save(gpdata); - } - } - }else{ - if(!isFakeUpdate) { - List duplicateGroupList = commonClassDao.checkExistingGroupListforUpdate(gpdata.getGroupList(), gpdata.getGroupName()); - if(!duplicateGroupList.isEmpty()) { - duplicateGroupFlag = true; - } else { - commonClassDao.update(gpdata); - } - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else if(duplicateGroupFlag){ - responseString = "DuplicateGroup"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate") && !responseString.equals("DuplicateGroup")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{groupPolicyScopeListDatas: " + 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; - } - - @RequestMapping(value={"/ps_dictionary/remove_GroupPolicyScope"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePSGroupScopeDictionary(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()); - GroupPolicyScopeList ecompData = (GroupPolicyScopeList)mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class); - commonClassDao.delete(ecompData); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class)); - JSONObject j = new JSONObject("{groupPolicyScopeListDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - System.out.println(e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/get_PSClosedLoopDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSClosedLoopEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psClosedLoopDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PolicyScopeClosedLoop.class, "name"))); - 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={"/get_PSClosedLoopData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSClosedLoopEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psClosedLoopDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(SUCCESSMAPKEY, "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - LOGGER.error(e); - } - } - - @RequestMapping(value={"/ps_dictionary/save_psClosedLoop"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView savePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyScopeClosedLoop ecompData; - if (fromAPI) { - ecompData = (PolicyScopeClosedLoop)mapper.readValue(root.get("dictionaryFields").toString(), PolicyScopeClosedLoop.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(ecompData.getName(), "name", PolicyScopeClosedLoop.class); - int id = 0; - for (int i =0; i< duplicateData.size(); i++){ - PolicyScopeClosedLoop data = (PolicyScopeClosedLoop) duplicateData.get(0); - id = data.getId(); - } - - if(id==0){ - isFakeUpdate=true; - ecompData.setId(1); - } else { - ecompData.setId(id); - } - - } - } else { - ecompData = (PolicyScopeClosedLoop)mapper.readValue(root.get("psClosedLoopDictionaryData").toString(), PolicyScopeClosedLoop.class); - } - if(ecompData.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(ecompData.getName(), "name", PolicyScopeClosedLoop.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(ecompData); - } - }else{ - if(!isFakeUpdate) { - commonClassDao.update(ecompData); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{psClosedLoopDictionaryDatas: " + 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; - } - - @RequestMapping(value={"/ps_dictionary/remove_PSClosedLoop"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePSClosedLoopDictionary(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()); - PolicyScopeClosedLoop ecompData = (PolicyScopeClosedLoop)mapper.readValue(root.get("data").toString(), PolicyScopeClosedLoop.class); - commonClassDao.delete(ecompData); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class)); - JSONObject j = new JSONObject("{psClosedLoopDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - System.out.println(e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/get_PSServiceDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSServiceEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psServiceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PolicyScopeService.class, "name"))); - 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={"/get_PSServiceData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSServiceEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psServiceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(SUCCESSMAPKEY, "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - LOGGER.error(e); - } - } - - @RequestMapping(value={"/ps_dictionary/save_psService"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyScopeService ecompData; - if (fromAPI) { - ecompData = (PolicyScopeService)mapper.readValue(root.get("dictionaryFields").toString(), PolicyScopeService.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(ecompData.getName(), "name", PolicyScopeService.class); - int id = 0; - for (int i =0; i< duplicateData.size(); i++){ - PolicyScopeService data = (PolicyScopeService) duplicateData.get(0); - id = data.getId(); - } - if(id==0){ - isFakeUpdate=true; - ecompData.setId(1); - } else { - ecompData.setId(id); - } - } - } else { - ecompData = (PolicyScopeService)mapper.readValue(root.get("psServiceDictionaryData").toString(), PolicyScopeService.class); - } - if(ecompData.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(ecompData.getName(), "name", PolicyScopeService.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(ecompData); - } - }else{ - if(!isFakeUpdate) { - commonClassDao.update(ecompData); - } - } - - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{psServiceDictionaryDatas: " + 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; - } - - @RequestMapping(value={"/ps_dictionary/remove_PSService"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePSServiceDictionary(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()); - PolicyScopeService ecompData = (PolicyScopeService)mapper.readValue(root.get("data").toString(), PolicyScopeService.class); - commonClassDao.delete(ecompData); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class)); - JSONObject j = new JSONObject("{psServiceDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - System.out.println(e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/get_PSTypeDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSTypeEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PolicyScopeType.class, "name"))); - 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={"/get_PSTypeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSTypeEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader(SUCCESSMAPKEY, "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - LOGGER.error(e); - } - } - - @RequestMapping(value={"/ps_dictionary/save_psType"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyScopeType ecompData; - if (fromAPI) { - ecompData = (PolicyScopeType)mapper.readValue(root.get("dictionaryFields").toString(), PolicyScopeType.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(ecompData.getName(), "name", PolicyScopeType.class); - int id = 0; - for (int i =0; i< duplicateData.size(); i++){ - PolicyScopeType data = (PolicyScopeType) duplicateData.get(0); - id = data.getId(); - } - - if(id==0){ - isFakeUpdate=true; - ecompData.setId(1); - } else { - ecompData.setId(id); - } - - } - } else { - ecompData = (PolicyScopeType)mapper.readValue(root.get("psTypeDictionaryData").toString(), PolicyScopeType.class); - } - if(ecompData.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(ecompData.getName(), "name", PolicyScopeType.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(ecompData); - } - }else{ - if(!isFakeUpdate) { - commonClassDao.update(ecompData); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - - } else { - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{psTypeDictionaryDatas: " + 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; - } - - @RequestMapping(value={"/ps_dictionary/remove_PSType"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePSTypeDictionary(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()); - PolicyScopeType ecompData = (PolicyScopeType)mapper.readValue(root.get("data").toString(), PolicyScopeType.class); - commonClassDao.delete(ecompData); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class)); - JSONObject j = new JSONObject("{psTypeDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - System.out.println(e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - @RequestMapping(value={"/get_PSResourceDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSResourceEntityDataByName(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psResourceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PolicyScopeResource.class, "name"))); - 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={"/get_PSResourceData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getPSResourceEntityData(HttpServletRequest request, HttpServletResponse response){ - try{ - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("psResourceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } - catch (Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - LOGGER.error(e); - } - } - - @RequestMapping(value={"/ps_dictionary/save_psResource"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - PolicyScopeResource ecompData; - if (fromAPI) { - ecompData = (PolicyScopeResource)mapper.readValue(root.get("dictionaryFields").toString(), PolicyScopeResource.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(ecompData.getName(), "name", PolicyScopeResource.class); - int id = 0; - PolicyScopeResource data = (PolicyScopeResource) duplicateData.get(0); - id = data.getId(); - - if(id==0){ - isFakeUpdate=true; - ecompData.setId(1); - } else { - ecompData.setId(id); - } - } - } else { - ecompData = (PolicyScopeResource)mapper.readValue(root.get("psResourceDictionaryData").toString(), PolicyScopeResource.class); - } - if(ecompData.getId() == 0){ - List duplicateData = commonClassDao.checkDuplicateEntry(ecompData.getName(), "name", PolicyScopeResource.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(ecompData); - } - }else{ - if(!isFakeUpdate) { - commonClassDao.update(ecompData); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = "Duplicate"; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals("Duplicate")) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - - } else { - - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{psResourceDictionaryDatas: " + 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; - } - - @RequestMapping(value={"/ps_dictionary/remove_PSResource"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView removePSResourceDictionary(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()); - PolicyScopeResource ecompData = (PolicyScopeResource)mapper.readValue(root.get("data").toString(), PolicyScopeResource.class); - commonClassDao.delete(ecompData); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class)); - JSONObject j = new JSONObject("{psResourceDictionaryDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } - catch (Exception e){ - System.out.println(e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } -} - -class GroupPolicyScope{ - String resource; - String type; - String service; - String closedloop; - public String getResource() { - return resource; - } - public void setResource(String resource) { - this.resource = resource; - } - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - public String getService() { - return service; - } - public void setService(String service) { - this.service = service; - } - public String getClosedloop() { - return closedloop; - } - public void setClosedloop(String closedloop) { - this.closedloop = closedloop; - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PushPolicyController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PushPolicyController.java deleted file mode 100644 index 3f86378ab..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/PushPolicyController.java +++ /dev/null @@ -1,229 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.controller; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.net.URI; -import java.util.List; -import java.util.UUID; - -import javax.persistence.EntityManager; -import javax.persistence.Query; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -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.std.pap.StdPDPGroup; -import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import com.att.research.xacml.api.pap.PAPException; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -@Controller -public class PushPolicyController { - private static final Logger LOGGER = FlexLogger.getLogger(PushPolicyController.class); - - private static CommonClassDao commonClassDao; - - @Autowired - public PushPolicyController(CommonClassDao commonClassDao){ - PushPolicyController.commonClassDao = commonClassDao; - } - - public PushPolicyController(){} - - @RequestMapping(value="/pushPolicy", method=RequestMethod.POST) - public void pushPolicy(HttpServletRequest request, HttpServletResponse response){ - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - try { - JsonNode root = mapper.readTree(request.getInputStream()); - String policyScope = root.get("policyScope").asText(); - String filePrefix = root.get("filePrefix").asText(); - String policyName = root.get("policyName").asText(); - String pdpGroup = root.get("pdpGroup").asText(); - String requestID = request.getHeader("X-ECOMP-RequestID"); - if(requestID==null){ - requestID = UUID.randomUUID().toString(); - LOGGER.info("No request ID provided, sending generated ID: " + requestID.toString()); - } - LOGGER.info("Push policy Request : " + root.asText()); - String policyVersionName = policyScope.replace(".", File.separator) + File.separator - + filePrefix + policyName; - List policyVersionObject = commonClassDao.getDataById(PolicyVersion.class, "policyName", policyVersionName); - if(policyVersionObject!=null){ - PolicyVersion policyVersion = (PolicyVersion) policyVersionObject.get(0); - String policyID = policyVersionName.replace(File.separator, "."); // This is before adding version. - policyVersionName += "." + policyVersion.getActiveVersion() + ".xml"; - addPolicyToGroup(policyScope, policyID, policyVersionName.replace(File.separator, "."), pdpGroup, response); - }else{ - String message = "Unknown Policy '" + policyName + "'"; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); - response.addHeader("error", "unknownPolicy"); - response.addHeader("operation", "push"); - response.addHeader("message", message); - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - return; - } - //safetyChecker(policyName); - } catch (NullPointerException | IOException e) { - LOGGER.error(e); - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - response.addHeader("error", "unknown"); - response.addHeader("operation", "push"); - return; - } - } - - private void addPolicyToGroup(String policyScope, String policyID, String policyName, String pdpGroup, HttpServletResponse response) { - StdPDPGroup selectedPDPGroup = null; - StdPDPPolicy selectedPolicy = null; - //Get the current policies from the Group and Add the new one - //Set currentPoliciesInGroup = null; - try { - selectedPDPGroup = (StdPDPGroup) XACMLPapServlet.getPAPEngine().getGroup(pdpGroup); - } catch (PAPException e1) { - PolicyLogger.error(e1); - } - if(selectedPDPGroup==null){ - String message = "Unknown groupId '" + selectedPDPGroup + "'"; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); - response.addHeader("error", "unknownGroupId"); - response.addHeader("operation", "push"); - response.addHeader("message", message); - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - return; - } - //Get PolicyEntity from DB; - EntityManager em = XACMLPapServlet.getEmf().createEntityManager(); - Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName"); - createPolicyQuery.setParameter("scope", policyScope); - createPolicyQuery.setParameter("policyName", policyName.substring(policyScope.length()+1)); - List createPolicyQueryList = createPolicyQuery.getResultList(); - PolicyEntity policyEntity = null; - if(createPolicyQueryList.size()>0){ - policyEntity = (PolicyEntity)createPolicyQueryList.get(0); - }else{ - PolicyLogger.error("Somehow, more than one policy with the same scope, name, and deleted status were found in the database"); - String message = "Unknown Policy '" + policyName + "'"; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); - response.addHeader("error", "unknownPolicy"); - response.addHeader("operation", "push"); - response.addHeader("message", message); - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - return; - } - File temp = new File(policyName); - try { - BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); - bw.write(policyEntity.getPolicyData()); - bw.close(); - URI selectedURI = temp.toURI(); - // Create the policy Object - selectedPolicy = new StdPDPPolicy(policyName, true, policyID, selectedURI); - } catch (IOException e) { - LOGGER.error("Unable to create policy '" + policyName + "': "+ e.getMessage()); - } - try { - new ObjectOutputStream(response.getOutputStream()).writeObject(selectedPolicy); - } catch (IOException e) { - LOGGER.error(e); - response.addHeader("error", "policyCopyError"); - response.addHeader("message", e.getMessage()); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - } - response.addHeader("Content-Type","application/json"); - response.setStatus(HttpServletResponse.SC_ACCEPTED); - response.addHeader("operation", "push"); - response.addHeader("policyId", policyName); - return; - // TODO : Check point to push policies within PAP. - /*PolicyDBDaoTransaction addPolicyToGroupTransaction = XACMLPapServlet.getDbDaoTransaction(); - try{ - if (selectedPolicy != null) { - // Add Current policies from container - currentPoliciesInGroup = selectedPDPGroup.getPolicies(); - // copy policy to PAP - addPolicyToGroupTransaction.addPolicyToGroup(selectedPDPGroup.getId(), policyName,"XACMLPapServlet.pushPolicyController"); - ((StdPDPGroup) selectedPDPGroup).copyPolicyToFile(policyName, policyID, new FileInputStream(temp)); - addPolicyToGroupTransaction.commitTransaction(); - } - }catch (Exception e) { - addPolicyToGroupTransaction.rollbackTransaction(); - String message = "Policy '" + policyName + "' not copied to group '" + pdpGroup +"': " + e; - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.addHeader("error", "policyCopyError"); - response.addHeader("message", message); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - } - //If the selected policy is in the group we must remove it because the name is default - for (PDPPolicy existingPolicy : currentPoliciesInGroup) { - if (existingPolicy.getId().equals(selectedPolicy.getId())) { - selectedPDPGroup.removePolicyFromGroup(existingPolicy); - LOGGER.debug("Removing existing policy: " + existingPolicy); - break; - } - } - //Update the PDP Group after removing old version of policy - //Set updatedPoliciesInGroup = selectedPDPGroup.getPolicies(); - //need to remove the policy with default name from group - for (PDPPolicy updatedPolicy : currentPoliciesInGroup) { - if (updatedPolicy.getName().equalsIgnoreCase("default")) { - selectedPDPGroup.removePolicyFromGroup(updatedPolicy); - } - } - Set policies = selectedPDPGroup.getPolicies(); - policies.add(selectedPolicy); - selectedPDPGroup.setPolicies(policies); - // Update now. - try { - XACMLPapServlet.getPAPEngine().updateGroup(selectedPDPGroup); - } catch (PAPException e) { - // TODO Auto-generated catch block - logger.error("Exception Occured"+e); - } - // policy file copied ok and the Group was updated on the PDP - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - response.addHeader("operation", "push"); - response.addHeader("policyId", policyName); - response.addHeader("groupId", pdpGroup); - return;*/ - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/SafePolicyController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/SafePolicyController.java deleted file mode 100644 index 8c88e68be..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/SafePolicyController.java +++ /dev/null @@ -1,385 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.controller; - -import java.io.PrintWriter; -import java.util.Date; -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.pap.xacml.rest.util.JsonMessage; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.RiskType; -import org.openecomp.policy.rest.jpa.SafePolicyWarning; -import org.openecomp.policy.rest.jpa.UserInfo; -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 -public class SafePolicyController { - - private static final Logger LOGGER = FlexLogger.getLogger(SafePolicyController.class); - - private static CommonClassDao commonClassDao; - - @Autowired - public SafePolicyController(CommonClassDao commonClassDao){ - SafePolicyController.commonClassDao = commonClassDao; - } - - public SafePolicyController(){} - - public UserInfo getUserInfo(String loginId){ - UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); - return name; - } - - private static String DUPLICATE = "Duplicate"; - - @RequestMapping(value = { "/get_RiskTypeDataByName" }, method = { - org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) - public void getRiskTypeDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response) { - try { - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("riskTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(RiskType.class, "name"))); - 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 = { "/get_RiskTypeData" }, method = { - org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) - public void getEcompNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response) { - try { - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("riskTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(RiskType.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } catch (Exception e) { - LOGGER.error(e.getMessage()); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - } - } - - @RequestMapping(value = { "/sp_dictionary/save_riskType" }, method = { - org.springframework.web.bind.annotation.RequestMethod.POST }) - public ModelAndView saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) - throws Exception { - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - RiskType riskTypeData; - String userId = null; - if (fromAPI) { - riskTypeData = (RiskType) mapper.readValue(root.get("dictionaryFields").toString(), - RiskType.class); - userId = "API"; - - //check if update operation or create, get id for data to be updated and update attributeData - if ("update".equalsIgnoreCase(request.getParameter("operation"))){ - List duplicateData = commonClassDao.checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class); - int id = 0; - RiskType data = (RiskType) duplicateData.get(0); - id = data.getId(); - - if(id==0){ - isFakeUpdate=true; - riskTypeData.setId(1); - } else { - riskTypeData.setId(id); - } - - riskTypeData.setUserCreatedBy(this.getUserInfo(userId)); - } - } else { - riskTypeData = (RiskType) mapper.readValue(root.get("riskTypeDictionaryData").toString(), RiskType.class); - userId = root.get("userid").textValue(); - } - - if (riskTypeData.getId() == 0) { - List duplicateData = commonClassDao.checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - riskTypeData.setUserCreatedBy(getUserInfo(userId)); - riskTypeData.setUserModifiedBy(getUserInfo(userId)); - commonClassDao.save(riskTypeData); - } - } else { - if (!isFakeUpdate) { - riskTypeData.setUserModifiedBy(this.getUserInfo(userId)); - riskTypeData.setModifiedDate(new Date()); - commonClassDao.update(riskTypeData); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = DUPLICATE; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(RiskType.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals(DUPLICATE)) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{riskTypeDictionaryDatas: " + 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; - } - - @RequestMapping(value = { "/sp_dictionary/remove_riskType" }, method = { - org.springframework.web.bind.annotation.RequestMethod.POST }) - public ModelAndView removeEcompDictionary(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()); - RiskType ecompData = (RiskType) mapper.readValue(root.get("data").toString(), RiskType.class); - commonClassDao.delete(ecompData); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(RiskType.class)); - JSONObject j = new JSONObject("{riskTypeDictionaryDatas: " + 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; - } - - @RequestMapping(value = { "/get_SafePolicyWarningDataByName" }, method = { - org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) - public void getSafePolicyWarningEntityDataByName(HttpServletRequest request, HttpServletResponse response) { - try { - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("safePolicyWarningDatas", - mapper.writeValueAsString(commonClassDao.getDataByColumn(SafePolicyWarning.class, "name"))); - 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 = { "/get_SafePolicyWarningData" }, method = { - org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) - public void getSafePolicyWarningeEntityData(HttpServletRequest request, HttpServletResponse response) { - try { - Map model = new HashMap<>(); - ObjectMapper mapper = new ObjectMapper(); - model.put("safePolicyWarningDatas", - mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class))); - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); - JSONObject j = new JSONObject(msg); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getDictionary"); - response.getWriter().write(j.toString()); - } catch (Exception e) { - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - LOGGER.error(e.getMessage()); - } - } - - @RequestMapping(value = { "/sp_dictionary/save_safePolicyWarning" }, method = { - org.springframework.web.bind.annotation.RequestMethod.POST }) - public ModelAndView saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) - throws Exception { - try { - boolean duplicateflag = false; - boolean isFakeUpdate = false; - boolean fromAPI = false; - if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { - fromAPI = true; - } - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - SafePolicyWarning safePolicyWarning; - if (fromAPI) { - safePolicyWarning = (SafePolicyWarning) mapper - .readValue(root.get("dictionaryFields").toString(), SafePolicyWarning.class); - - //check if update operation or create, get id for data to be updated and update attributeData - if (request.getParameter("operation").equals("update")) { - List duplicateData = commonClassDao.checkDuplicateEntry(safePolicyWarning.getName(), "name", SafePolicyWarning.class); - int id = 0; - SafePolicyWarning data = (SafePolicyWarning) duplicateData.get(0); - id = data.getId(); - - if(id==0){ - isFakeUpdate=true; - safePolicyWarning.setId(1); - } else { - safePolicyWarning.setId(id); - } - } - } else { - safePolicyWarning = (SafePolicyWarning) mapper.readValue(root.get("safePolicyWarningData").toString(), SafePolicyWarning.class); - } - - if (safePolicyWarning.getId() == 0) { - List duplicateData = commonClassDao.checkDuplicateEntry(safePolicyWarning.getName(), "name", SafePolicyWarning.class); - if(!duplicateData.isEmpty()){ - duplicateflag = true; - }else{ - commonClassDao.save(safePolicyWarning); - } - } else { - if(!isFakeUpdate) { - commonClassDao.update(safePolicyWarning); - } - } - String responseString = ""; - if(duplicateflag){ - responseString = DUPLICATE; - }else{ - responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)); - } - - if (fromAPI) { - if (responseString!=null && !responseString.equals(DUPLICATE)) { - if(isFakeUpdate){ - responseString = "Exists"; - } else { - responseString = "Success"; - } - } - ModelAndView result = new ModelAndView(); - result.setViewName(responseString); - return result; - } else { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - JSONObject j = new JSONObject("{safePolicyWarningDatas: " + 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; - } - - @RequestMapping(value = { "/sp_dictionary/remove_SafePolicyWarning" }, method = { - org.springframework.web.bind.annotation.RequestMethod.POST }) - public ModelAndView removeSafePolicyWarningDictionary(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()); - SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) mapper.readValue(root.get("data").toString(), - SafePolicyWarning.class); - commonClassDao.delete(safePolicyWarningData); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); - - PrintWriter out = response.getWriter(); - - String responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)); - JSONObject j = new JSONObject("{groupPolicyScopeListDatas: " + responseString + "}"); - out.write(j.toString()); - - return null; - } catch (Exception e) { - System.out.println(e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/package-info.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/package-info.java deleted file mode 100644 index 049f3c72c..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/controller/package-info.java +++ /dev/null @@ -1,22 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.controller; diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java deleted file mode 100644 index c624012f1..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java +++ /dev/null @@ -1,443 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.daoimpl; - -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -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.Criterion; -import org.hibernate.criterion.Disjunction; -import org.hibernate.criterion.Projections; -import org.hibernate.criterion.Restrictions; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.ClosedLoops; -import org.openecomp.policy.rest.jpa.GroupPolicyScopeList; -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 Log LOGGER = LogFactory.getLog(CommonClassDaoImpl.class); - - - private static SessionFactory sessionFactory; - - @Autowired - private CommonClassDaoImpl(SessionFactory sessionFactory){ - CommonClassDaoImpl.sessionFactory = sessionFactory; - } - - public CommonClassDaoImpl(){ - //Default Constructor - } - - @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; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @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; - } - - @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 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; - } - - - @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") - @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; - } - - - @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; - } - - - @SuppressWarnings("unchecked") - @Override - public void updateClAlarms(String clName, String alarms) { - Session session = sessionFactory.openSession(); - List closedloopsdata = null; - Transaction tx = session.beginTransaction(); - try { - Criteria cr = session.createCriteria(ClosedLoops.class); - cr.add(Restrictions.eq("closedLoopControlName",clName)); - closedloopsdata = cr.list(); - ClosedLoops closedloop = closedloopsdata.get(0); - closedloop.setAlarmConditions(alarms); - session.update(closedloop); - tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e); - }finally{ - session.close(); - } - } - - - @SuppressWarnings("unchecked") - @Override - public void updateClYaml(String clName, String yaml) { - Session session = sessionFactory.openSession(); - List closedloopsdata = null; - Transaction tx = session.beginTransaction(); - try { - Criteria cr = session.createCriteria(ClosedLoops.class); - cr.add(Restrictions.eq("closedLoopControlName",clName)); - closedloopsdata = cr.list(); - ClosedLoops closedloop = closedloopsdata.get(0); - closedloop.setYaml(yaml); - session.update(closedloop); - tx.commit(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e); - }finally{ - session.close(); - } - } - - - @SuppressWarnings("unchecked") - @Override - public void deleteAll() { - Session session = sessionFactory.openSession(); - Transaction tx = session.beginTransaction(); - List closedloopsdata = null; - try { - Criteria cr = session.createCriteria(ClosedLoops.class); - closedloopsdata = cr.list(); - - if(closedloopsdata!=null && !closedloopsdata.isEmpty()) { - LOGGER.info("ClosedLoops exist in the database, we need to delete them in our first step to buildCache()."); - for(int i=0; i < closedloopsdata.size(); i++) { - ClosedLoops cl = closedloopsdata.get(i); - session.delete(cl); - } - } else { - LOGGER.info("No ClosedLoops exist in the database, no need to delete."); - } - - tx.commit(); - }catch(Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while deleting ClosedLoops from the table"+e); - }finally{ - session.close(); - } - } - - @SuppressWarnings({ "unchecked"}) - @Override - public List checkExistingGroupListforUpdate(String groupListValue, String groupNameValue) { - Session session = sessionFactory.openSession(); - Transaction tx = session.beginTransaction(); - List data = null; - try { - Criteria cr = session.createCriteria(GroupPolicyScopeList.class); - cr.add(Restrictions.eq("groupList",groupListValue)); - Criterion expression = Restrictions.eq("name", groupNameValue); - cr.add(Restrictions.not(expression)); - data = cr.list(); - tx.commit(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for GroupPolicyScopeList 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 List getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, String columnName, List data) { - return null; - } - -} \ No newline at end of file diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java deleted file mode 100644 index facc6e06f..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java +++ /dev/null @@ -1,311 +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.pap.xacml.rest.elk.client; - -import java.io.FileInputStream; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Iterator; -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 com.google.gson.Gson; - -import io.searchbox.client.JestClientFactory; -import io.searchbox.client.config.HttpClientConfig; -import io.searchbox.client.http.JestHttpClient; -import io.searchbox.core.Bulk; -import io.searchbox.core.Bulk.Builder; -import io.searchbox.core.BulkResult; -import io.searchbox.core.Index; -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; - - - -/** - * This code will deals with parsing the XACML content on reading from - * database(PolicyEntity, ConfigurationDataEntity and ActionBodyEntity tables) - * and convert the data into json to do bulk operation on putting to elastic search database. - * Which is used to support Elastic Search in Policy Application GUI to search policies. - * - * - * - * properties should be configured in policyelk.properties - * - */ -public class ElasticSearchPolicyUpdate { - - private static final Logger LOGGER = FlexLogger.getLogger(ElasticSearchPolicyUpdate.class); - protected final static JestClientFactory jestFactory = new JestClientFactory(); - - public static void main(String[] args) { - - String elkURL = null; - String databseUrl = null; - String userName = null; - String password = null; - String databaseDriver = null; - - String propertyFile = System.getProperty("PROPERTY_FILE"); - Properties config = new Properties(); - Path file = Paths.get(propertyFile); - if(Files.notExists(file)){ - LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString()); - }else{ - if(file.toString().endsWith(".properties")){ - try { - InputStream in = new FileInputStream(file.toFile()); - config.load(in); - elkURL = config.getProperty("policy.elk.url"); - databseUrl = config.getProperty("policy.database.url"); - userName = config.getProperty("policy.database.username"); - password = config.getProperty("policy.database.password"); - databaseDriver = config.getProperty("policy.database.driver"); - if(elkURL == null || databseUrl == null || userName == null || password == null || databaseDriver == null){ - LOGGER.error("One of the Property is null in policyelk.properties = elkurl:databaseurl:username:password:databasedriver " - + elkURL + ":"+ databseUrl + ":"+ userName + ":"+ password + ":"+ databaseDriver + ":"); - } - } catch (Exception e) { - LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString()); - } - } - } - - Builder bulk = null; - - HttpClientConfig httpClientConfig = new HttpClientConfig.Builder(elkURL).multiThreaded(true).build(); - jestFactory.setHttpClientConfig(httpClientConfig); - JestHttpClient client = (JestHttpClient) jestFactory.getObject(); - - Connection conn = null; - Statement stmt = null; - - List listIndex = new ArrayList(); - - try { - Class.forName(databaseDriver); - conn = DriverManager.getConnection(databseUrl, userName, password); - stmt = conn.createStatement(); - - String policyEntityQuery = "Select * from PolicyEntity"; - ResultSet result = stmt.executeQuery(policyEntityQuery); - - while(result.next()){ - StringBuilder policyDataString = new StringBuilder("{"); - String scope = result.getString("scope"); - String policyName = result.getString("policyName"); - if(policyName != null){ - policyDataString.append("\"policyName\":\""+scope+"."+policyName+"\","); - } - String description = result.getString("description"); - if(description != null){ - policyDataString.append("\"policyDescription\":\""+description+"\","); - } - Object policyData = result.getString("policydata"); - - if(scope != null){ - policyDataString.append("\"scope\":\""+scope+"\","); - } - String actionbodyid = result.getString("actionbodyid"); - String configurationdataid = result.getString("configurationdataid"); - - - String policyWithScopeName = scope + "." + policyName; - String _type = null; - - if(policyWithScopeName.contains(".Config_")){ - policyDataString.append("\"policyType\":\"Config\","); - if(policyWithScopeName.contains(".Config_Fault_")){ - _type = "closedloop"; - policyDataString.append("\"configPolicyType\":\"ClosedLoop_Fault\","); - }else if(policyWithScopeName.contains(".Config_PM_")){ - _type = "closedloop"; - policyDataString.append("\"configPolicyType\":\"ClosedLoop_PM\","); - }else{ - _type = "config"; - policyDataString.append("\"configPolicyType\":\"Base\","); - } - }else if(policyWithScopeName.contains(".Action_")){ - _type = "action"; - policyDataString.append("\"policyType\":\"Action\","); - }else if(policyWithScopeName.contains(".Decision_")){ - _type = "decision"; - policyDataString.append("\"policyType\":\"Decision\","); - } - - if(!"decision".equals(_type)){ - if(configurationdataid != null){ - String configEntityQuery = "Select * from ConfigurationDataEntity where configurationDataId = "+configurationdataid+""; - Statement configstmt = conn.createStatement(); - ResultSet configResult = configstmt.executeQuery(configEntityQuery); - while(configResult.next()){ - String configBody = configResult.getString("configbody"); - String configType = configResult.getString("configtype"); - if("JSON".equalsIgnoreCase(configType)){ - policyDataString.append("\"jsonBodyData\":"+configBody+",\"configType\":\""+configType+"\","); - }else if("OTHER".equalsIgnoreCase(configType)){ - if(configBody!=null){ - configBody= configBody.replaceAll("\"", ""); - policyDataString.append("\"jsonBodyData\":\""+configBody+"\",\"configType\":\""+configType+"\","); - } - } - } - configResult.close(); - } - - if(actionbodyid != null){ - String actionEntityQuery = "Select * from ActionBodyEntity where actionBodyId = "+actionbodyid+""; - Statement actionstmt = conn.createStatement(); - ResultSet actionResult = actionstmt.executeQuery(actionEntityQuery); - while(actionResult.next()){ - String actionBody = actionResult.getString("actionbody"); - policyDataString.append("\"jsonBodyData\":"+actionBody+","); - } - actionResult.close(); - } - } - - String _id = policyWithScopeName; - - policyDataString.append(constructPolicyData(policyData, policyDataString)); - - String dataString = policyDataString.toString(); - dataString = dataString.substring(0, dataString.length()-1); - dataString = dataString.trim().replace(System.getProperty("line.separator"), "") + "}"; - dataString = dataString.replace("null", "\"\""); - dataString = dataString.replaceAll(" ", "").replaceAll("\n", ""); - - try{ - Gson gson = new Gson(); - gson.fromJson(dataString, Object.class); - }catch(Exception e){ - continue; - } - - if("config".equals(_type)){ - listIndex.add(new Index.Builder(dataString).index("policy").type("config").id(_id).build()); - }else if("closedloop".equals(_type)){ - listIndex.add(new Index.Builder(dataString).index("policy").type("closedloop").id(_id).build()); - }else if("action".equals(_type)){ - listIndex.add(new Index.Builder(dataString).index("policy").type("action").id(_id).build()); - }else if("decision".equals(_type)){ - listIndex.add(new Index.Builder(dataString).index("policy").type("decision").id(_id).build()); - } - } - - result.close(); - bulk = new Bulk.Builder(); - for(int i =0; i < listIndex.size(); i++){ - bulk.addAction(listIndex.get(i)); - } - BulkResult searchResult = client.execute(bulk.build()); - if(searchResult.isSucceeded()){ - LOGGER.debug("Success"); - }else{ - LOGGER.error("Failure"); - } - } catch (Exception e) { - LOGGER.error("Exception Occured while performing database Operation for Elastic Search Policy Upgrade"+e); - }finally{ - if(conn != null){ - try { - conn.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the connection"+e); - } - } - } - } - - private static String constructPolicyData(Object policyData, StringBuilder policyDataString){ - if(policyData instanceof PolicyType){ - PolicyType policy = (PolicyType) policyData; - 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 ("ECOMPName".equals(attributeId)) { - policyDataString.append("\"ecompName\":\""+value+"\","); - } - if ("RiskType".equals(attributeId)){ - policyDataString.append("\"riskType\":\""+value+"\","); - } - if ("RiskLevel".equals(attributeId)){ - policyDataString.append("\"riskLevel\":\""+value+"\","); - } - if ("guard".equals(attributeId)){ - policyDataString.append("\"guard\":\""+value+"\","); - } - if ("ConfigName".equals(attributeId)){ - policyDataString.append("\"configName\":\""+value+"\","); - } - } - } - } - } - } - } - } - } - return policyDataString.toString(); - } - -} \ No newline at end of file diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnector.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnector.java deleted file mode 100644 index 2b94e44c7..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnector.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.elk.client; - - -import java.util.Map; - -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; - -import io.searchbox.client.JestResult; - -public interface ElkConnector { - - public static final String ELK_URL = "http://localhost:9200"; - public static final String ELK_INDEX_POLICY = "policy"; - - public enum PolicyIndexType { - config, - action, - decision, - closedloop, - all, - } - - public enum PolicyType { - Config, - Action, - Decision, - Config_Fault, - Config_PM, - Config_FW, - Config_MS, - none, - } - - public enum PolicyBodyType { - json, - xml, - properties, - txt, - none, - } - - public boolean delete(PolicyRestAdapter policyData) - throws IllegalStateException; - - public JestResult search(PolicyIndexType type, String text) - throws IllegalStateException, IllegalArgumentException; - - public JestResult search(PolicyIndexType type, String text, - Map searchKeyValue) - throws IllegalStateException, IllegalArgumentException; - - public boolean update(PolicyRestAdapter policyData) throws IllegalStateException; - - public ElkConnector singleton = new ElkConnectorImpl(); - - public static PolicyIndexType toPolicyIndexType(String policyName) - throws IllegalArgumentException { - if (policyName == null) - throw new IllegalArgumentException("Unsupported NULL policy name conversion"); - - if (policyName.startsWith("Config_Fault")) { - return PolicyIndexType.closedloop; - } else if (policyName.startsWith("Config_PM")) { - return PolicyIndexType.closedloop; - } else if (policyName.startsWith("Config_FW")) { - return PolicyIndexType.config; - } else if (policyName.startsWith("Config_MS")) { - return PolicyIndexType.config; - }else if (policyName.startsWith("Action")) { - return PolicyIndexType.action; - } else if (policyName.startsWith("Decision")) { - return PolicyIndexType.decision; - } else if (policyName.startsWith("Config")) { - return PolicyIndexType.config; - } else { - throw new IllegalArgumentException - ("Unsupported policy name conversion to index: " + - policyName); - } - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java deleted file mode 100644 index a6315f89d..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java +++ /dev/null @@ -1,418 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.elk.client; - -import java.io.IOException; -import java.util.Map; -import java.util.Map.Entry; - -import org.elasticsearch.index.query.QueryBuilders; -import org.elasticsearch.index.query.QueryStringQueryBuilder; -import org.elasticsearch.search.builder.SearchSourceBuilder; -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.xacml.api.XACMLErrorConstants; - -import io.searchbox.action.Action; -import io.searchbox.client.JestClient; -import io.searchbox.client.JestClientFactory; -import io.searchbox.client.JestResult; -import io.searchbox.client.config.HttpClientConfig; -import io.searchbox.core.Delete; -import io.searchbox.core.Index; -import io.searchbox.core.Search; -import io.searchbox.core.Search.Builder; -import io.searchbox.indices.IndicesExists; -import io.searchbox.indices.type.TypeExist; -import io.searchbox.params.Parameters; - -public class ElkConnectorImpl implements ElkConnector{ - - private static final Logger LOGGER = FlexLogger.getLogger(ElkConnector.class); - - protected final JestClientFactory jestFactory = new JestClientFactory(); - protected final JestClient jestClient; - protected static int QUERY_MAXRECORDS = 1000; - - public ElkConnectorImpl() { - if (LOGGER.isDebugEnabled()){ - LOGGER.debug("ENTER: -"); - } - HttpClientConfig jestClientConfig = new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build(); - jestFactory.setHttpClientConfig(jestClientConfig); - jestClient = jestFactory.getObject(); - } - - protected boolean isType(PolicyIndexType type) throws IOException { - if (LOGGER.isDebugEnabled()){ - LOGGER.debug("ENTER: -"); - } - - try { - Action typeQuery = new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build(); - JestResult result = jestClient.execute(typeQuery); - - if (LOGGER.isInfoEnabled()) { - LOGGER.info("JSON:" + result.getJsonString()); - LOGGER.info("ERROR:" + result.getErrorMessage()); - LOGGER.info("PATH:" + result.getPathToResult()); - LOGGER.info(result.getJsonObject()); - } - return result.isSucceeded(); - } catch (IOException e) { - LOGGER.warn("Error checking type existance of " + type.toString() + ": " + e.getMessage(), e); - throw e; - } - } - - protected boolean isIndex() throws IOException { - try { - Action indexQuery = new IndicesExists.Builder(ELK_INDEX_POLICY).build(); - - JestResult result = jestClient.execute(indexQuery); - if (LOGGER.isInfoEnabled()) { - LOGGER.info("JSON:" + result.getJsonString()); - LOGGER.info("ERROR:" + result.getErrorMessage()); - LOGGER.info("PATH:" + result.getPathToResult()); - LOGGER.info(result.getJsonObject()); - } - return result.isSucceeded(); - } catch (IOException e) { - LOGGER.warn("Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), e); - throw e; - } - } - - @Override - public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException { - if (LOGGER.isTraceEnabled()){ - LOGGER.trace("ENTER: " + text); - } - - if (text == null || text.isEmpty()) { - throw new IllegalArgumentException("No search string provided"); - } - - QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery("*"+text+"*"); - SearchSourceBuilder searchSourceBuilder = - new SearchSourceBuilder().query(mQ); - - Builder searchBuilder = new Search.Builder(searchSourceBuilder.toString()). - addIndex(ELK_INDEX_POLICY). - setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS); - - if (type == null || type == PolicyIndexType.all) { - for (PolicyIndexType pT: PolicyIndexType.values()) { - if (pT != PolicyIndexType.all) { - searchBuilder.addType(pT.toString()); - } - } - } else { - searchBuilder.addType(type.toString()); - } - - Search search = searchBuilder.build(); - JestResult result; - try { - result = jestClient.execute(search); - } catch (IOException ioe) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + - search + ": " + ioe.getMessage(), ioe); - throw new IllegalStateException(ioe); - } - - if (result.isSucceeded()) { - if (LOGGER.isInfoEnabled()){ - LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + - result.getPathToResult() + ":" + System.lineSeparator() + - result.getJsonString()); - } - } else { - /* Unsuccessful search */ - if (LOGGER.isWarnEnabled()){ - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + - result.getResponseCode() + ": " + - search.getURI() + ":" + - result.getPathToResult() + ":" + - result.getJsonString() + ":" + - result.getErrorMessage()); - } - - String errorMessage = result.getErrorMessage(); - if (errorMessage != null && !errorMessage.isEmpty()) { - String xMessage = errorMessage; - if (errorMessage.contains("TokenMgrError")) { - int indexError = errorMessage.lastIndexOf("TokenMgrError"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("QueryParsingException")) { - int indexError = errorMessage.lastIndexOf("QueryParsingException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("JsonParseException")) { - int indexError = errorMessage.lastIndexOf("JsonParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("Parse Failure")) { - int indexError = errorMessage.lastIndexOf("Parse Failure"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("SearchParseException")) { - int indexError = errorMessage.lastIndexOf("SearchParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else { - xMessage = result.getErrorMessage(); - } - throw new IllegalStateException(xMessage); - } - } - - return result; - } - - - @Override - public JestResult search(PolicyIndexType type, String text, - Map filter_s) - throws IllegalStateException, IllegalArgumentException { - if (LOGGER.isTraceEnabled()){ - LOGGER.trace("ENTER: " + text); - } - - if (filter_s == null || filter_s.size() == 0) { - return search(type, text); - } - - String matches_s = ""; - matches_s = "{\n" + - " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + - " \"query\": {\n" + - " \"bool\" : {\n" + - " \"must\" : ["; - - String match_params = ""; - boolean first = true; - for(Entry entry : filter_s.entrySet()){ - String key = entry.getKey(); - String value = entry.getValue(); - if(first){ - match_params = "\"match\" : {\""+key+"\" : \""+value+"\" }},"; - first = false; - }else{ - match_params = match_params + "{\"match\" : { \""+key+"\" : \""+value+"\" } },"; - } - } - if(match_params.endsWith(",")){ - match_params = match_params.substring(0, match_params.length()-2); - } - - matches_s = matches_s + "{\n" + match_params + "\n}" ; - - boolean query = false; - String query_String = ""; - if(text != null){ - query = true; - query_String = "{\n \"query_string\" : {\n \"query\" : \"*"+text+"*\"\n} \n}"; - } - - if(query){ - matches_s = matches_s + "," + query_String + "]\n}\n}\n}"; - }else{ - matches_s = matches_s + "]\n}\n}\n}"; - } - - Builder searchBuilder = new Search.Builder(matches_s).addIndex(ELK_INDEX_POLICY); - - if (type == null || type == PolicyIndexType.all) { - for (PolicyIndexType pT: PolicyIndexType.values()) { - if (pT != PolicyIndexType.all) { - searchBuilder.addType(pT.toString()); - } - } - } else { - searchBuilder.addType(type.toString()); - } - - Search search = searchBuilder.build(); - - JestResult result; - try { - result = jestClient.execute(search); - } catch (IOException ioe) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + - search + ": " + ioe.getMessage(), ioe); - throw new IllegalStateException(ioe); - } - - if (result.isSucceeded()) { - if (LOGGER.isInfoEnabled()){ - LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + - result.getPathToResult() + ":" + System.lineSeparator() + - result.getJsonString()); - } - } else { - /* Unsuccessful search */ - if (LOGGER.isWarnEnabled()){ - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + - result.getResponseCode() + ": " + - search.getURI() + ":" + - result.getPathToResult() + ":" + - result.getJsonString() + ":" + - result.getErrorMessage()); - } - - String errorMessage = result.getErrorMessage(); - if (errorMessage != null && !errorMessage.isEmpty()) { - String xMessage = errorMessage; - if (errorMessage.contains("TokenMgrError")) { - int indexError = errorMessage.lastIndexOf("TokenMgrError"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("QueryParsingException")) { - int indexError = errorMessage.lastIndexOf("QueryParsingException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("JsonParseException")) { - int indexError = errorMessage.lastIndexOf("JsonParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("Parse Failure")) { - int indexError = errorMessage.lastIndexOf("Parse Failure"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else if (errorMessage.contains("SearchParseException")) { - int indexError = errorMessage.lastIndexOf("SearchParseException"); - xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); - } else { - xMessage = result.getErrorMessage(); - } - throw new IllegalStateException(xMessage); - } - } - - return result; - } - - public boolean put(PolicyRestAdapter policyData) - throws IOException, IllegalStateException { - if (LOGGER.isTraceEnabled()) LOGGER.trace("ENTER"); - - PolicyIndexType indexType; - try { - String policyName = policyData.getNewFileName(); - if(policyName.contains("Config_")){ - policyName = policyName.replace(".Config_", ":Config_"); - }else if(policyName.contains("Action_")){ - policyName = policyName.replace(".Action_", ":Action_"); - }else if(policyName.contains("Decision_")){ - policyName = policyName.replace(".Decision_", ":Decision_"); - } - - String[] splitPolicyName = policyName.split(":"); - indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]); - } catch (IllegalArgumentException e) { - throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + e.getMessage()); - } - PolicyElasticData elasticData = new PolicyElasticData(policyData); - JSONObject jsonObj = new JSONObject(elasticData); - Index elkPut = new Index.Builder(jsonObj.toString()). - index(ELK_INDEX_POLICY). - type(indexType.name()). - id(elasticData.getPolicyName()). - refresh(true). - build(); - - JestResult result = jestClient.execute(elkPut); - - if (result.isSucceeded()) { - if (LOGGER.isInfoEnabled()) - LOGGER.info("OK: PUT operation of " + "->" + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); - } else { - if (LOGGER.isWarnEnabled()) - LOGGER.warn("FAILURE: PUT operation of "+ "->" + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); - - } - - return result.isSucceeded(); - } - - @Override - public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException { - PolicyIndexType indexType = null; - JestResult result; - try { - String policyName = policyData.getNewFileName(); - if(policyName.contains("Config_")){ - policyName = policyName.replace(".Config_", ":Config_"); - }else if(policyName.contains("Action_")){ - policyName = policyName.replace(".Action_", ":Action_"); - }else if(policyName.contains("Decision_")){ - policyName = policyName.replace(".Decision_", ":Decision_"); - } - - String[] splitPolicyName = policyName.split(":"); - indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]); - if (!isType(indexType)) { - throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + - " Type: " + indexType + - " is not configured"); - } - PolicyElasticData elasticData = new PolicyElasticData(policyData); - Delete deleteRequest = new Delete.Builder(elasticData.getPolicyName()).index(ELK_INDEX_POLICY). - type(indexType.name()).build(); - result = jestClient.execute(deleteRequest); - } catch (IllegalArgumentException | IOException e) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ": delete:" + - indexType + ": null" + ":" + policyData.getNewFileName() + ": " + - e.getMessage(), e); - throw new IllegalStateException(e); - } - - if (result.isSucceeded()) { - if (LOGGER.isInfoEnabled()) - LOGGER.info("OK: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); - } else { - if (LOGGER.isWarnEnabled()) - LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + - "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + - result.getPathToResult() + "]" + System.lineSeparator() + - result.getJsonString()); - } - - return result.isSucceeded(); - } - - @Override - public boolean update(PolicyRestAdapter policyData) throws IllegalStateException { - if (LOGGER.isDebugEnabled()){ - LOGGER.debug("ENTER"); - } - try { - boolean success = put(policyData); - return success; - } catch (Exception e) { - LOGGER.warn(XACMLErrorConstants.ERROR_UNKNOWN + ":" + "cannot test and update", e); - throw new IllegalStateException(e); - } - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/Pair.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/Pair.java deleted file mode 100644 index cf4cecbb4..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/Pair.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.elk.client; - -public class Pair { - private L left; - private R right; - public Pair(L l, R r){ - this.left = l; - this.right = r; - } - public L left(){ return left; } - public R right(){ return right; } - public void left(L l){ this.left = l; } - public void right(R r){ this.right = r; } -} \ No newline at end of file diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticData.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticData.java deleted file mode 100644 index 15eae89ec..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticData.java +++ /dev/null @@ -1,623 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.elk.client; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.adapter.YAMLParams; - -public class PolicyElasticData { - - private String scope; - private String policyType; - private String configPolicyType; - private String configBodyData; - private String policyName; - private String policyDescription; - private String ecompName; - private String configName; - private String configType; - private String jsonBody; - private Object jsonBodyData; - - private LinkedHashMap serviceTypePolicyName; - private LinkedHashMap verticaMetrics; - private LinkedHashMap description; - private LinkedHashMap attributeFields; - - //Safe Policy - private String policyScope; - private String providerComboBox; - private String riskType; - private String riskLevel; - private String guard; - private String ttlDate; - private Map matching; - - private ArrayList triggerSignatures; - private ArrayList symptomSignatures; - private String logicalConnector; - private String policyStatus; - public String gocServerScope; - private String supressionType; - - //MicroSerice - private String serviceType; - private String uuid; - private String location; - private String priority; - private String msLocation; - - //BRMS Policies - private String ruleName; - private Map brmsParamBody; - private String brmsController; - private ArrayList brmsDependency; - private LinkedHashMap ruleData; - private LinkedHashMap ruleListData; - private Map drlRuleAndUIParams; - - //ClosedLoop - private String clearTimeOut; - private String trapMaxAge; - private String verificationclearTimeOut; - public Map dynamicLayoutMap; - - //FireWall - private String fwPolicyType; - private ArrayList fwattributes; - private String parentForChild; - private String securityZone; - - //Action & Decision - private String ruleCombiningAlgId; - private Map dynamicFieldConfigAttributes; - private Map dynamicSettingsMap; - private Map dropDownMap; - private String actionPerformer; - private String actionAttribute; - private List dynamicRuleAlgorithmLabels; - private List dynamicRuleAlgorithmCombo; - private List dynamicRuleAlgorithmField1; - private List dynamicRuleAlgorithmField2; - private List dynamicVariableList; - private List dataTypeList; - private String actionAttributeValue; - private String ruleProvider; - private String actionBody; - private String actionDictHeader; - private String actionDictType; - private String actionDictUrl; - private String actionDictMethod; - private YAMLParams yamlparams; - - public PolicyElasticData(PolicyRestAdapter policyData) { - this.scope = policyData.getDomain(); - this.policyType = policyData.getPolicyType(); - this.configPolicyType = policyData.getConfigPolicyType(); - this.configBodyData = policyData.getConfigBodyData(); - this.policyName = policyData.getNewFileName(); - this.policyDescription = policyData.getPolicyDescription(); - this.ecompName = policyData.getEcompName(); - this.configName = policyData.getConfigName(); - this.configType = policyData.getConfigType(); - this.jsonBody = policyData.getJsonBody(); - if(configPolicyType.startsWith("ClosedLoop")){ - this.jsonBodyData = jsonBody; - }else{ - this.jsonBodyData = policyData.getJsonBodyData(); - } - - this.serviceTypePolicyName = policyData.getServiceTypePolicyName(); - this.verticaMetrics = policyData.getVerticaMetrics(); - this.description = policyData.getDescription(); - this.attributeFields = policyData.getAttributeFields(); - - //Safe Policy - this.policyScope = policyData.getPolicyScope(); - this.providerComboBox = policyData.getProviderComboBox(); - this.riskType = policyData.getRiskType(); - this.riskLevel = policyData.getRiskLevel(); - this.guard = policyData.getGuard(); - this.ttlDate = policyData.getTtlDate(); - this.matching = policyData.getMatching(); - - this.triggerSignatures = policyData.getTriggerSignatures(); - this.symptomSignatures = policyData.getSymptomSignatures(); - this.logicalConnector = policyData.getLogicalConnector(); - this.policyStatus = policyData.getPolicyStatus(); - this.gocServerScope = policyData.getGocServerScope(); - this.supressionType = policyData.getSupressionType(); - - //MicroSerice - this.serviceType = policyData.getServiceType(); - this.uuid = policyData.getUuid(); - this.location = policyData.getLocation(); - this.priority = policyData.getPriority(); - this.msLocation = policyData.getMsLocation(); - - //BRMS Policies - this.ruleName = policyData.getRuleName(); - this.brmsParamBody = policyData.getBrmsParamBody(); - this.brmsController = policyData.getBrmsController(); - this.brmsDependency = policyData.getBrmsDependency(); - this.ruleData = policyData.getRuleData(); - this.ruleListData = policyData.getRuleListData(); - this.drlRuleAndUIParams = policyData.getDrlRuleAndUIParams(); - - //ClosedLoop - this.clearTimeOut = policyData.getClearTimeOut(); - this.trapMaxAge = policyData.getTrapMaxAge(); - this.verificationclearTimeOut = policyData.getVerificationclearTimeOut(); - this.dynamicLayoutMap = policyData.getDynamicLayoutMap(); - - //FireWall - this.fwPolicyType = policyData.getFwPolicyType(); - this.fwattributes = policyData.getFwattributes(); - this.parentForChild = policyData.getParentForChild(); - this.securityZone = policyData.getSecurityZone(); - - //Action & Decision - this.ruleCombiningAlgId = policyData.getRuleCombiningAlgId(); - this.dynamicFieldConfigAttributes = policyData.getDynamicFieldConfigAttributes(); - this.dynamicSettingsMap = policyData.getDynamicSettingsMap(); - this.dropDownMap = policyData.getDropDownMap(); - this.actionPerformer = policyData.getActionPerformer(); - this.actionAttribute = policyData.getActionAttribute(); - this.dynamicRuleAlgorithmLabels = policyData.getDynamicRuleAlgorithmLabels(); - this.dynamicRuleAlgorithmCombo = policyData.getDynamicRuleAlgorithmCombo(); - this.dynamicRuleAlgorithmField1 = policyData.getDynamicRuleAlgorithmField1(); - this.dynamicRuleAlgorithmField2 = policyData.getDynamicRuleAlgorithmField2(); - this.dynamicVariableList = policyData.getDynamicVariableList(); - this.dataTypeList = policyData.getDataTypeList(); - this.actionAttributeValue = policyData.getActionAttributeValue(); - this.ruleProvider = policyData.getRuleProvider(); - this.actionBody = policyData.getActionBody(); - this.actionDictHeader = policyData.getActionDictHeader(); - this.actionDictType = policyData.getActionDictType(); - this.actionDictUrl = policyData.getActionDictUrl(); - this.actionDictMethod = policyData.getActionDictMethod(); - this.yamlparams = policyData.getYamlparams(); - } - - public String getScope() { - return scope; - } - public void setScope(String scope) { - this.scope = scope; - } - public String getPolicyType() { - return policyType; - } - public void setPolicyType(String policyType) { - this.policyType = policyType; - } - public String getConfigPolicyType() { - return configPolicyType; - } - public void setConfigPolicyType(String configPolicyType) { - this.configPolicyType = configPolicyType; - } - public String getConfigBodyData() { - return configBodyData; - } - - public void setConfigBodyData(String configBodyData) { - this.configBodyData = configBodyData; - } - public String getPolicyName() { - return policyName; - } - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - public String getPolicyDescription() { - return policyDescription; - } - public void setPolicyDescription(String policyDescription) { - this.policyDescription = policyDescription; - } - public String getEcompName() { - return ecompName; - } - public void setEcompName(String ecompName) { - this.ecompName = ecompName; - } - public String getConfigName() { - return configName; - } - public void setConfigName(String configName) { - this.configName = configName; - } - public String getConfigType() { - return configType; - } - public void setConfigType(String configType) { - this.configType = configType; - } - public String getJsonBody() { - return jsonBody; - } - public void setJsonBody(String jsonBody) { - this.jsonBody = jsonBody; - } - public LinkedHashMap getServiceTypePolicyName() { - return serviceTypePolicyName; - } - - public void setServiceTypePolicyName(LinkedHashMap serviceTypePolicyName) { - this.serviceTypePolicyName = serviceTypePolicyName; - } - - public LinkedHashMap getVerticaMetrics() { - return verticaMetrics; - } - - public void setVerticaMetrics(LinkedHashMap verticaMetrics) { - this.verticaMetrics = verticaMetrics; - } - - public LinkedHashMap getDescription() { - return description; - } - - public void setDescription(LinkedHashMap description) { - this.description = description; - } - - public LinkedHashMap getAttributeFields() { - return attributeFields; - } - - public void setAttributeFields(LinkedHashMap attributeFields) { - this.attributeFields = attributeFields; - } - public String getPolicyScope() { - return policyScope; - } - public void setPolicyScope(String policyScope) { - this.policyScope = policyScope; - } - public String getProviderComboBox() { - return providerComboBox; - } - public void setProviderComboBox(String providerComboBox) { - this.providerComboBox = providerComboBox; - } - 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 getGuard() { - return guard; - } - public void setGuard(String guard) { - this.guard = guard; - } - public String getTtlDate() { - return ttlDate; - } - public void setTtlDate(String ttlDate) { - this.ttlDate = ttlDate; - } - public Map getMatching() { - return matching; - } - public void setMatching(Map matching) { - this.matching = matching; - } - public ArrayList getTriggerSignatures() { - return triggerSignatures; - } - public void setTriggerSignatures(ArrayList triggerSignatures) { - this.triggerSignatures = triggerSignatures; - } - public ArrayList getSymptomSignatures() { - return symptomSignatures; - } - public void setSymptomSignatures(ArrayList symptomSignatures) { - this.symptomSignatures = symptomSignatures; - } - public String getLogicalConnector() { - return logicalConnector; - } - public void setLogicalConnector(String logicalConnector) { - this.logicalConnector = logicalConnector; - } - public String getPolicyStatus() { - return policyStatus; - } - public void setPolicyStatus(String policyStatus) { - this.policyStatus = policyStatus; - } - public String getGocServerScope() { - return gocServerScope; - } - public void setGocServerScope(String gocServerScope) { - this.gocServerScope = gocServerScope; - } - public String getSupressionType() { - return supressionType; - } - public void setSupressionType(String supressionType) { - this.supressionType = supressionType; - } - public String getServiceType() { - return serviceType; - } - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - public String getUuid() { - return uuid; - } - public void setUuid(String uuid) { - this.uuid = uuid; - } - public String getLocation() { - return location; - } - public void setLocation(String location) { - this.location = location; - } - public String getPriority() { - return priority; - } - public void setPriority(String priority) { - this.priority = priority; - } - public String getMsLocation() { - return msLocation; - } - public void setMsLocation(String msLocation) { - this.msLocation = msLocation; - } - public String getRuleName() { - return ruleName; - } - public void setRuleName(String ruleName) { - this.ruleName = ruleName; - } - public Map getBrmsParamBody() { - return brmsParamBody; - } - public void setBrmsParamBody(Map brmsParamBody) { - this.brmsParamBody = brmsParamBody; - } - public String getBrmsController() { - return brmsController; - } - public void setBrmsController(String brmsController) { - this.brmsController = brmsController; - } - public ArrayList getBrmsDependency() { - return brmsDependency; - } - public void setBrmsDependency(ArrayList brmsDependency) { - this.brmsDependency = brmsDependency; - } - public LinkedHashMap getRuleData() { - return ruleData; - } - public void setRuleData(LinkedHashMap ruleData) { - this.ruleData = ruleData; - } - public LinkedHashMap getRuleListData() { - return ruleListData; - } - public void setRuleListData(LinkedHashMap ruleListData) { - this.ruleListData = ruleListData; - } - public Map getDrlRuleAndUIParams() { - return drlRuleAndUIParams; - } - public void setDrlRuleAndUIParams(Map drlRuleAndUIParams) { - this.drlRuleAndUIParams = drlRuleAndUIParams; - } - 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 Map getDynamicLayoutMap() { - return dynamicLayoutMap; - } - public void setDynamicLayoutMap(Map dynamicLayoutMap) { - this.dynamicLayoutMap = dynamicLayoutMap; - } - public String getFwPolicyType() { - return fwPolicyType; - } - public void setFwPolicyType(String fwPolicyType) { - this.fwPolicyType = fwPolicyType; - } - public ArrayList getFwattributes() { - return fwattributes; - } - public void setFwattributes(ArrayList fwattributes) { - this.fwattributes = fwattributes; - } - public String getParentForChild() { - return parentForChild; - } - public void setParentForChild(String parentForChild) { - this.parentForChild = parentForChild; - } - public String getSecurityZone() { - return securityZone; - } - public void setSecurityZone(String securityZone) { - this.securityZone = securityZone; - } - public String getRuleCombiningAlgId() { - return ruleCombiningAlgId; - } - public void setRuleCombiningAlgId(String ruleCombiningAlgId) { - this.ruleCombiningAlgId = ruleCombiningAlgId; - } - public Map getDynamicFieldConfigAttributes() { - return dynamicFieldConfigAttributes; - } - public void setDynamicFieldConfigAttributes(Map dynamicFieldConfigAttributes) { - this.dynamicFieldConfigAttributes = dynamicFieldConfigAttributes; - } - public Map getDynamicSettingsMap() { - return dynamicSettingsMap; - } - public void setDynamicSettingsMap(Map dynamicSettingsMap) { - this.dynamicSettingsMap = dynamicSettingsMap; - } - public Map getDropDownMap() { - return dropDownMap; - } - public void setDropDownMap(Map dropDownMap) { - this.dropDownMap = dropDownMap; - } - public String getActionPerformer() { - return actionPerformer; - } - public void setActionPerformer(String actionPerformer) { - this.actionPerformer = actionPerformer; - } - public String getActionAttribute() { - return actionAttribute; - } - public void setActionAttribute(String actionAttribute) { - this.actionAttribute = actionAttribute; - } - public List getDynamicRuleAlgorithmLabels() { - return dynamicRuleAlgorithmLabels; - } - public void setDynamicRuleAlgorithmLabels(List dynamicRuleAlgorithmLabels) { - this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; - } - public List getDynamicRuleAlgorithmCombo() { - return dynamicRuleAlgorithmCombo; - } - public void setDynamicRuleAlgorithmCombo(List dynamicRuleAlgorithmCombo) { - this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; - } - public List getDynamicRuleAlgorithmField1() { - return dynamicRuleAlgorithmField1; - } - public void setDynamicRuleAlgorithmField1(List dynamicRuleAlgorithmField1) { - this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; - } - public List getDynamicRuleAlgorithmField2() { - return dynamicRuleAlgorithmField2; - } - public void setDynamicRuleAlgorithmField2(List dynamicRuleAlgorithmField2) { - this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; - } - public List getDynamicVariableList() { - return dynamicVariableList; - } - public void setDynamicVariableList(List dynamicVariableList) { - this.dynamicVariableList = dynamicVariableList; - } - public List getDataTypeList() { - return dataTypeList; - } - public void setDataTypeList(List dataTypeList) { - this.dataTypeList = dataTypeList; - } - public String getActionAttributeValue() { - return actionAttributeValue; - } - public void setActionAttributeValue(String actionAttributeValue) { - this.actionAttributeValue = actionAttributeValue; - } - public String getRuleProvider() { - return ruleProvider; - } - public void setRuleProvider(String ruleProvider) { - this.ruleProvider = ruleProvider; - } - public String getActionBody() { - return actionBody; - } - public void setActionBody(String actionBody) { - this.actionBody = actionBody; - } - public String getActionDictHeader() { - return actionDictHeader; - } - public void setActionDictHeader(String actionDictHeader) { - this.actionDictHeader = actionDictHeader; - } - public String getActionDictType() { - return actionDictType; - } - public void setActionDictType(String actionDictType) { - this.actionDictType = actionDictType; - } - public String getActionDictUrl() { - return actionDictUrl; - } - public void setActionDictUrl(String actionDictUrl) { - this.actionDictUrl = actionDictUrl; - } - public String getActionDictMethod() { - return actionDictMethod; - } - public void setActionDictMethod(String actionDictMethod) { - this.actionDictMethod = actionDictMethod; - } - public YAMLParams getYamlparams() { - return yamlparams; - } - - public void setYamlparams(YAMLParams yamlparams) { - this.yamlparams = yamlparams; - } - - public Object getJsonBodyData() { - return jsonBodyData; - } - - public void setJsonBodyData(Object jsonBodyData) { - this.jsonBodyData = jsonBodyData; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java deleted file mode 100644 index e5250d6b6..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java +++ /dev/null @@ -1,563 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.elk.client; - - -import java.io.PrintWriter; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.TrustManager; -import javax.net.ssl.X509TrustManager; -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.pap.xacml.rest.elk.client.ElkConnector.PolicyIndexType; -import org.openecomp.policy.pap.xacml.rest.util.JsonMessage; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.ActionPolicyDict; -import org.openecomp.policy.rest.jpa.Attribute; -import org.openecomp.policy.rest.jpa.BRMSParamTemplate; -import org.openecomp.policy.rest.jpa.ClosedLoopD2Services; -import org.openecomp.policy.rest.jpa.ClosedLoopSite; -import org.openecomp.policy.rest.jpa.DCAEuuid; -import org.openecomp.policy.rest.jpa.DecisionSettings; -import org.openecomp.policy.rest.jpa.DescriptiveScope; -import org.openecomp.policy.rest.jpa.EcompName; -import org.openecomp.policy.rest.jpa.GroupPolicyScopeList; -import org.openecomp.policy.rest.jpa.MicroServiceLocation; -import org.openecomp.policy.rest.jpa.MicroServiceModels; -import org.openecomp.policy.rest.jpa.PEPOptions; -import org.openecomp.policy.rest.jpa.RiskType; -import org.openecomp.policy.rest.jpa.SafePolicyWarning; -import org.openecomp.policy.rest.jpa.TermList; -import org.openecomp.policy.rest.jpa.VNFType; -import org.openecomp.policy.rest.jpa.VSCLAction; -import org.openecomp.policy.rest.jpa.VarbindDictionary; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.beans.factory.annotation.Autowired; -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 com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.JsonArray; - -import io.searchbox.client.JestResult; - -@Controller -@RequestMapping({"/"}) -public class PolicyElasticSearchController{ - - private static final Logger LOGGER = FlexLogger.getLogger(PolicyElasticSearchController.class); - - enum Mode{ - attribute, ecompName, actionPolicy, brmsParam, pepOptions, - clSite, clService, clVarbind, clVnf, clVSCL, decision, - fwTerm, msDCAEUUID, msConfigName, msLocation, msModels, - psGroupPolicy, safeRisk, safePolicyWarning - } - - public static final HashMap name2jsonPath = new HashMap() { - private static final long serialVersionUID = 1L; - }; - - public static CommonClassDao commonClassDao; - - @Autowired - public PolicyElasticSearchController(CommonClassDao commonClassDao) { - PolicyElasticSearchController.commonClassDao = commonClassDao; - } - - public PolicyElasticSearchController() {} - - public static void TurnOffCertsCheck() { - // Create a trust manager that does not validate certificate chains - TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; - } - public void checkClientTrusted(X509Certificate[] certs, - String authType) { - } - public void checkServerTrusted(X509Certificate[] certs, - String authType) { - } - } }; - - // Install all-trusting trust manager - SSLContext ctx; - try { - ctx = SSLContext.getInstance("SSL"); - ctx.init(null, trustAllCerts, new java.security.SecureRandom()); - HttpsURLConnection.setDefaultSSLSocketFactory(ctx - .getSocketFactory()); - } catch (NoSuchAlgorithmException | KeyManagementException e) { - LOGGER.error("SSL Security Error: " + e); - } - - // Create all-trusting host name verifier - HostnameVerifier allHostsValid = new HostnameVerifier() { - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - - // Install the all-trusting host verifier - HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); - } - - - - - public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException { - if (type == null || type.isEmpty()){ - return PolicyIndexType.all; - } - return PolicyIndexType.valueOf(type); - } - - public boolean updateElk(PolicyRestAdapter policyData) { - boolean success = true; - try { - success = ElkConnector.singleton.update(policyData); - if (!success) { - if (LOGGER.isWarnEnabled()) { - LOGGER.warn("FAILURE to create ELK record created for " + policyData.getNewFileName()); - } - } else { - if (LOGGER.isInfoEnabled()) { - LOGGER.warn("SUCCESS creating ELK record created for " + policyData.getNewFileName()); - } - } - } catch (Exception e) { - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e); - success = false; - } - return success; - } - - public boolean deleteElk(PolicyRestAdapter policyData) { - boolean success = true; - try { - success = ElkConnector.singleton.delete(policyData); - if (!success) { - if (LOGGER.isWarnEnabled()) { - LOGGER.warn("FAILURE to delete ELK record created for " + policyData.getNewFileName()); - } - } else { - if (LOGGER.isInfoEnabled()) { - LOGGER.warn("SUCCESS deleting ELK record created for " + policyData.getNewFileName()); - } - } - } catch (Exception e) { - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e); - success = false; - } - return success; - } - - - @RequestMapping(value="/searchPolicy", method= RequestMethod.POST) - public void searchPolicy(HttpServletRequest request, HttpServletResponse response) { - try{ - boolean result = false; - boolean policyResult = false; - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - PolicyRestAdapter policyData = new PolicyRestAdapter(); - PolicyElasticSearchController controller = new PolicyElasticSearchController(); - Map searchKeyValue = new HashMap<>(); - List policyList = new ArrayList<>(); - if(request.getParameter("policyName") != null){ - String policyName = request.getParameter("policyName"); - policyData.setNewFileName(policyName); - if("delete".equalsIgnoreCase(request.getParameter("action"))){ - result = controller.deleteElk(policyData); - }else{ - result = controller.updateElk(policyData); - } - } - if("search".equalsIgnoreCase(request.getParameter("action"))){ - try { - JsonNode root = mapper.readTree(request.getReader()); - SearchData searchData = (SearchData)mapper.readValue(root.get("searchdata").toString(), SearchData.class); - - String policyType = searchData.getPolicyType(); - - String searchText = searchData.getQuery(); - String descriptivevalue = searchData.getDescriptiveScope(); - if(descriptivevalue != null){ - DescriptiveScope dsSearch = (DescriptiveScope) commonClassDao.getEntityItem(DescriptiveScope.class, "descriptiveScopeName", descriptivevalue); - if(dsSearch != null){ - String[] descriptiveList = dsSearch.getSearch().split("AND"); - for(String keyValue : descriptiveList){ - String[] entry = keyValue.split(":"); - if(searchData.getPolicyType() != null && "closedLoop".equals(searchData.getPolicyType())){ - searchKeyValue.put("jsonBodyData", "*" +entry[1] +"*"); - }else{ - searchKeyValue.put(entry[0], entry[1]); - } - } - } - } - - if(searchData.getClosedLooppolicyType() != null){ - String closedLoopType; - if("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())){ - closedLoopType = "ClosedLoop_Fault"; - }else{ - closedLoopType = "ClosedLoop_PM"; - } - searchKeyValue.put("configPolicyType", closedLoopType); - } - if(searchData.getEcompName() != null){ - searchKeyValue.put("ecompName", searchData.getEcompName()); - } - if(searchData.getD2Service() != null){ - String d2Service = searchData.getD2Service().trim(); - if(d2Service.equalsIgnoreCase("Hosted Voice (Trinity)")){ - d2Service = "trinity"; - }else if(d2Service.equalsIgnoreCase("vUSP")){ - d2Service = "vUSP"; - }else if(d2Service.equalsIgnoreCase("MCR")){ - d2Service = "mcr"; - }else if(d2Service.equalsIgnoreCase("Gamma")){ - d2Service = "gamma"; - }else if(d2Service.equalsIgnoreCase("vDNS")){ - d2Service = "vDNS"; - } - searchKeyValue.put("jsonBodyData."+d2Service+"", "true"); - } - if(searchData.getVnfType() != null){ - searchKeyValue.put("jsonBodyData", "*" +searchData.getVnfType() +"*"); - } - if(searchData.getPolicyStatus() != null){ - searchKeyValue.put("jsonBodyData", "*" +searchData.getPolicyStatus()+"*"); - } - if(searchData.getVproAction() != null){ - searchKeyValue.put("jsonBodyData", "*" +searchData.getVproAction()+"*"); - } - if(searchData.getServiceType() != null){ - searchKeyValue.put("serviceType", searchData.getServiceType()); - } - if(searchData.getBindTextSearch() != null){ - searchKeyValue.put(searchData.getBindTextSearch(), searchText); - searchText = null; - } - PolicyIndexType type = null; - if(policyType != null){ - if(policyType.equalsIgnoreCase("action")){ - type = ElkConnector.PolicyIndexType.action; - }else if(policyType.equalsIgnoreCase("decision")){ - type = ElkConnector.PolicyIndexType.decision; - }else if(policyType.equalsIgnoreCase("config")){ - type = ElkConnector.PolicyIndexType.config; - }else { - type = ElkConnector.PolicyIndexType.closedloop; - } - }else{ - type = ElkConnector.PolicyIndexType.all; - } - JestResult policyResultList = controller.search(type, searchText, searchKeyValue); - if(policyResultList.isSucceeded()){ - result = true; - policyResult = true; - JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); - for(int i =0; i < resultObject.size(); i++){ - String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString(); - policyList.add(policyName); - } - }else{ - LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs"); - } - }catch(Exception e){ - LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server" + e); - } - } - String message=""; - if(result){ - message = "Elastic Server Transaction is success"; - }else{ - message = "Elastic Server Transaction is failed, please check the logs"; - } - JsonMessage msg = new JsonMessage(mapper.writeValueAsString(message)); - JSONObject j = new JSONObject(msg); - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("success", "success"); - if(policyResult){ - JSONObject k = new JSONObject("{policyresult: " + policyList + "}"); - response.getWriter().write(k.toString()); - }else{ - response.getWriter().write(j.toString()); - } - }catch(Exception e){ - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "Exception Occured While Performing Elastic Transaction"); - LOGGER.error("Exception Occured While Performing Elastic Transaction"+e.getMessage()); - } - } - - @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - try{ - PolicyIndexType config = PolicyIndexType.config; - PolicyIndexType closedloop = PolicyIndexType.closedloop; - PolicyIndexType action = PolicyIndexType.action; - PolicyIndexType decision = PolicyIndexType.decision; - PolicyIndexType all = PolicyIndexType.all; - - ObjectMapper mapper = new ObjectMapper(); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - JsonNode root = mapper.readTree(request.getReader()); - String dictionaryType = root.get("type").textValue(); - Mode mode = Mode.valueOf(dictionaryType); - String value; - List policyList = new ArrayList<>(); - switch (mode){ - case attribute : - Attribute attributedata = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class); - value = attributedata.getXacmlId(); - policyList = searchElkDatabase(all, "pholder",value); - break; - case ecompName : - EcompName ecompName = (EcompName)mapper.readValue(root.get("data").toString(), EcompName.class); - value = ecompName.getEcompName(); - policyList = searchElkDatabase(all, "ecompName",value); - break; - case actionPolicy : - ActionPolicyDict actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("data").toString(), ActionPolicyDict.class); - value = actionPolicyDict.getAttributeName(); - policyList = searchElkDatabase(action, "actionAttributeValue",value); - break; - case brmsParam : - BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate)mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class); - value = bRMSParamTemplate.getRuleName(); - policyList = searchElkDatabase(config, "ruleName",value); - break; - case pepOptions : - PEPOptions pEPOptions = (PEPOptions)mapper.readValue(root.get("data").toString(), PEPOptions.class); - value = pEPOptions.getPepName(); - policyList = searchElkDatabase(closedloop,"jsonBodyData.pepName",value); - break; - case clSite : - ClosedLoopSite closedLoopSite = (ClosedLoopSite)mapper.readValue(root.get("data").toString(), ClosedLoopSite.class); - value = closedLoopSite.getSiteName(); - policyList = searchElkDatabase(closedloop,"siteNames",value); - break; - case clService : - ClosedLoopD2Services closedLoopD2Services = (ClosedLoopD2Services)mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class); - value = closedLoopD2Services.getServiceName(); - policyList = searchElkDatabase(closedloop, "pholder",value); - break; - case clVarbind : - VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class); - value = varbindDictionary.getVarbindName(); - policyList = searchElkDatabase(closedloop, "jsonBodyData.triggerSignaturesUsedForUI.signatures",value); - break; - case clVnf : - VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class); - value = vNFType.getVnftype(); - policyList = searchElkDatabase(closedloop, "jsonBodyData.vnfType",value); - break; - case clVSCL : - VSCLAction vsclAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class); - value = vsclAction.getVsclaction(); - policyList = searchElkDatabase(closedloop, "jsonBodyData.actions",value); - break; - case decision : - DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class); - value = decisionSettings.getXacmlId(); - policyList = searchElkDatabase(decision,"pholder",value); - break; - case fwTerm : - TermList term = (TermList)mapper.readValue(root.get("data").toString(), TermList.class); - value = term.getTermName(); - policyList = searchElkDatabase(config, "pholder",value); - break; - case msDCAEUUID : - DCAEuuid dcaeUUID = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class); - value = dcaeUUID.getName(); - policyList = searchElkDatabase(config, "uuid",value); - break; - case msLocation : - MicroServiceLocation mslocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class); - value = mslocation.getName(); - policyList = searchElkDatabase(config, "location",value); - break; - case msModels : - MicroServiceModels msModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class); - value = msModels.getModelName(); - policyList = searchElkDatabase(config, "serviceType",value); - break; - case psGroupPolicy : - GroupPolicyScopeList groupPoilicy = (GroupPolicyScopeList)mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class); - value = groupPoilicy.getGroupName(); - policyList = searchElkDatabase(config, "pholder",value); - break; - case safeRisk : - RiskType riskType= (RiskType)mapper.readValue(root.get("data").toString(), RiskType.class); - value = riskType.getRiskName(); - policyList = searchElkDatabase(config, "riskType",value); - break; - case safePolicyWarning : - SafePolicyWarning safePolicy = (SafePolicyWarning)mapper.readValue(root.get("data").toString(), SafePolicyWarning.class); - value = safePolicy.getName(); - policyList = searchElkDatabase(config, "pholder",value); - break; - default: - } - - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("success", "success"); - JSONObject k = new JSONObject("{policyresult: " + policyList + "}"); - response.getWriter().write(k.toString()); - }catch(Exception e){ - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(e.getMessage()); - } - return null; - } - - //Search the Elk database - public List searchElkDatabase(PolicyIndexType type, String key, String value){ - PolicyElasticSearchController controller = new PolicyElasticSearchController(); - Map searchKeyValue = new HashMap<>(); - if(!"pholder".equals(key)){ - searchKeyValue.put(key, value); - } - - List policyList = new ArrayList<>(); - JestResult policyResultList = controller.search(type, value, searchKeyValue); - if(policyResultList.isSucceeded()){ - JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); - for(int i =0; i < resultObject.size(); i++){ - String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString(); - policyList.add(policyName); - } - }else{ - LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs"); - } - return policyList; - } - - public JestResult search(PolicyIndexType type, String text, Map searchKeyValue) { - return ElkConnector.singleton.search(type, text, searchKeyValue); - } - -} - -class SearchData{ - private String query; - private String policyType; - private String descriptiveScope; - private String closedLooppolicyType; - private String ecompName; - private String d2Service; - private String vnfType; - private String policyStatus; - private String vproAction; - private String serviceType; - private String bindTextSearch; - public String getQuery() { - return query; - } - public void setQuery(String query) { - this.query = query; - } - public String getPolicyType() { - return policyType; - } - public void setPolicyType(String policyType) { - this.policyType = policyType; - } - public String getDescriptiveScope() { - return descriptiveScope; - } - public void setDescriptiveScope(String descriptiveScope) { - this.descriptiveScope = descriptiveScope; - } - public String getClosedLooppolicyType() { - return closedLooppolicyType; - } - public void setClosedLooppolicyType(String closedLooppolicyType) { - this.closedLooppolicyType = closedLooppolicyType; - } - public String getEcompName() { - return ecompName; - } - public void setEcompName(String ecompName) { - this.ecompName = ecompName; - } - public String getD2Service() { - return d2Service; - } - public void setD2Service(String d2Service) { - this.d2Service = d2Service; - } - public String getVnfType() { - return vnfType; - } - public void setVnfType(String vnfType) { - this.vnfType = vnfType; - } - public String getPolicyStatus() { - return policyStatus; - } - public void setPolicyStatus(String policyStatus) { - this.policyStatus = policyStatus; - } - public String getVproAction() { - return vproAction; - } - public void setVproAction(String vproAction) { - this.vproAction = vproAction; - } - public String getServiceType() { - return serviceType; - } - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - public String getBindTextSearch() { - return bindTextSearch; - } - public void setBindTextSearch(String bindTextSearch) { - this.bindTextSearch = bindTextSearch; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyLocator.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyLocator.java deleted file mode 100644 index f246c9b15..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/elk/client/PolicyLocator.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.elk.client; - -public class PolicyLocator { - public final String policyType; - public final String policyName; - public final String owner; - public final String scope; - public final String policyId; - public final String version; - - public PolicyLocator(String policyType, String policyName, - String owner, String scope, String policyId, - String version) { - this.policyType = policyType; - this.policyName= policyName; - this.owner = owner; - this.scope = scope; - this.policyId = policyId; - this.version = version; - } - - public String toString() { - return "[" + - this.owner + "|" + - this.scope + "|" + - this.policyType + "|" + - this.policyName + "|" + - this.policyId + "|" + - "v" + this.version + "|" + "]"; - - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/APIRequestHandler.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/APIRequestHandler.java deleted file mode 100644 index c1de11548..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/APIRequestHandler.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.handler; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.policy.common.logging.ECOMPLoggingContext; -import org.openecomp.policy.pap.xacml.rest.service.ImportService; -import org.openecomp.policy.pap.xacml.rest.service.MetricService; -import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; - -public class APIRequestHandler { - - private EcompPDPGroup newGroup; - - public void doGet(HttpServletRequest request, HttpServletResponse response, String apiflag) throws IOException{ - // Request from the API to get Dictionary Items - if ("api".equalsIgnoreCase(apiflag)) { - DictionaryHandler dictionaryHandler = DictionaryHandler.getInstance(); - dictionaryHandler.doDictionaryAPIGet(request, response); - return; - } - // Request from the API to get the ActiveVersion from the PolicyVersion table - if ("version".equalsIgnoreCase(apiflag)){ - PushPolicyHandler pushHandler = new PushPolicyHandler(); - pushHandler.getActiveVersion(request, response); - return; - } - // Request from the API to get the URI from the gitpath - if ("uri".equalsIgnoreCase(apiflag)){ - PushPolicyHandler pushHandler = new PushPolicyHandler(); - pushHandler.getSelectedURI(request, response); - return; - } - if ("getMetrics".equalsIgnoreCase(apiflag)){ - MetricService.doGetPolicyMetrics(request, response); - return; - } - } - - public void doPut(HttpServletRequest request, HttpServletResponse response, String service) throws IOException { - if ("MICROSERVICE".equalsIgnoreCase(service) || "BRMSPARAM".equalsIgnoreCase(service)){ - ImportService importService = new ImportService(); - importService.doImportMicroServicePut(request, response); - return; - } - if ("dictionaryItem".equalsIgnoreCase(service)) { - DictionaryHandler dictionaryHandler = DictionaryHandler.getInstance(); - dictionaryHandler.doDictionaryAPIPut(request, response); - return; - } else { - SavePolicyHandler savePolicy = SavePolicyHandler.getInstance(); - savePolicy.doPolicyAPIPut(request, response); - } - } - - public void doDelete(HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext, String apiflag) throws Exception { - DeleteHandler deleteHandler = DeleteHandler.getInstance(); - if ("deletePapApi".equalsIgnoreCase(apiflag)) { - deleteHandler.doAPIDeleteFromPAP(request, response, loggingContext); - return; - } else if ("deletePdpApi".equalsIgnoreCase(apiflag)) { - deleteHandler.doAPIDeleteFromPDP(request, response, loggingContext); - setNewGroup(deleteHandler.getDeletedGroup()); - return; - } - } - - private void setNewGroup(EcompPDPGroup newGroup) { - this.newGroup = newGroup; - } - - public EcompPDPGroup getNewGroup() { - return newGroup; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java deleted file mode 100644 index 693196517..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DeleteHandler.java +++ /dev/null @@ -1,477 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.handler; - -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.Query; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.policy.common.logging.ECOMPLoggingContext; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; -import org.openecomp.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController; -import org.openecomp.policy.pap.xacml.rest.model.RemoveGroupPolicy; -import org.openecomp.policy.pap.xacml.rest.util.JPAUtils; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.jpa.PolicyEntity; -import org.openecomp.policy.rest.jpa.PolicyVersion; -import org.openecomp.policy.utils.PolicyUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; -import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; -import org.openecomp.policy.xacml.std.pap.StdPDPGroup; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.att.research.xacml.util.XACMLProperties; - -public class DeleteHandler { - - private EcompPDPGroup newgroup; - - private static String papDbDriver = null; - private static String papDbUrl = null; - private static String papDbUser = null; - private static String papDbPassword = null; - - public void doAPIDeleteFromPAP(HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws Exception { - // get the request content into a String - String json = null; - java.util.Scanner scanner = new java.util.Scanner(request.getInputStream()); - scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - PolicyLogger.info("JSON request from API: " + json); - // convert Object sent as JSON into local object - StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class); - String policyName = policy.getPolicyName(); - Boolean policyVersionDeleted = false; - String removeXMLExtension; - int currentVersion; - String removeVersionExtension; - String splitPolicyName = null; - String[] split = null; - String status = "error"; - PolicyEntity policyEntity = null; - JPAUtils jpaUtils = null; - - papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER); - papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); - papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER); - papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD); - Connection con = null; - - try { - jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf()); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Could not create JPAUtils instance on the PAP"); - response.addHeader("error", "jpautils"); - response.addHeader("operation", "delete"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - } - if (jpaUtils.dbLockdownIgnoreErrors()) { - PolicyLogger.warn("Policies are locked down"); - response.addHeader("operation", "delete"); - response.addHeader("lockdown", "true"); - response.setStatus(HttpServletResponse.SC_ACCEPTED); - return; - } - EntityManager em = (EntityManager) XACMLPapServlet.getEmf().createEntityManager(); - Query policyEntityQuery = null; - try{ - if(policyName.endsWith(".xml")){ - removeXMLExtension = policyName.replace(".xml", ""); - currentVersion = Integer.parseInt(removeXMLExtension.substring(removeXMLExtension.lastIndexOf(".")+1)); - removeVersionExtension = removeXMLExtension.substring(0, removeXMLExtension.lastIndexOf(".")); - boolean queryCheck = true; - if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){ - if(policyName.contains("Config_")){ - splitPolicyName = removeVersionExtension.replace(".Config_", ":Config_"); - }else if(policyName.contains("Action_")){ - splitPolicyName = removeVersionExtension.replace(".Action_", ":Action_"); - }else if(policyName.contains("Decision_")){ - splitPolicyName = removeVersionExtension.replace(".Decision_", ":Decision_"); - } - if(splitPolicyName != null){ - split = splitPolicyName.split(":"); - }else{ - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy. Please, provide the valid policyname."); - response.addHeader("error", "unknown"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); - return; - } - policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName LIKE :pName and p.scope=:pScope"); - }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")) { - if(policyName.contains("Config_")){ - splitPolicyName = policyName.replace(".Config_", ":Config_"); - }else if(policyName.contains("Action_")){ - splitPolicyName = policyName.replace(".Action_", ":Action_"); - }else if(policyName.contains("Decision_")){ - splitPolicyName = policyName.replace(".Decision_", ":Decision_"); - } - split = splitPolicyName.split(":"); - queryCheck = false; - policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:pName and p.scope=:pScope"); - } - - if(queryCheck){ - policyEntityQuery.setParameter("pName", "%"+split[1]+"%"); - }else{ - policyEntityQuery.setParameter("pName", split[1]); - } - - policyEntityQuery.setParameter("pScope", split[0]); - List peResult = policyEntityQuery.getResultList(); - if(!peResult.isEmpty()){ - Query getPolicyVersion = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname"); - getPolicyVersion.setParameter("pname", removeVersionExtension.replace(".", File.separator)); - List pvResult = getPolicyVersion.getResultList(); - PolicyVersion pVersion = (PolicyVersion) pvResult.get(0); - int newVersion = 0; - em.getTransaction().begin(); - Class.forName(papDbDriver); - con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword); - - if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){ - boolean groupCheck = checkPolicyGroupEntity(em, con, peResult); - if(!groupCheck){ - for(Object peData : peResult){ - policyEntity = (PolicyEntity) peData; - status = deletePolicyEntityData(em, policyEntity); - } - }else{ - status = "PolicyInPDP"; - } - if(status.equals("error")){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database."); - response.addHeader("error", "unknown"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); - return; - }else if(status.equals("PolicyInPDP")){ - PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups."); - response.addHeader("error", "PolicyInPDP"); - response.setStatus(HttpServletResponse.SC_CONFLICT); - return; - }else{ - try{ - policyVersionDeleted = true; - em.remove(pVersion); - }catch(Exception e){ - policyVersionDeleted = false; - } - } - }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")){ - boolean groupCheck = checkPolicyGroupEntity(em, con, peResult); - if(!groupCheck){ - policyEntity = (PolicyEntity) peResult.get(0); - status = deletePolicyEntityData(em, policyEntity); - }else{ - status = "PolicyInPDP"; - } - - if(status.equals("error")){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database."); - response.addHeader("error", "unknown"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); - return; - }else if(status.equals("PolicyInPDP")){ - PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups."); - response.addHeader("error", "unknown"); - response.setStatus(HttpServletResponse.SC_CONFLICT); - return; - }else{ - if(currentVersion > 1){ - if(!peResult.isEmpty()){ - for(Object object : peResult){ - policyEntity = (PolicyEntity) object; - String policyEntityName = policyEntity.getPolicyName().replace(".xml", ""); - int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1)); - if(policyEntityVersion > newVersion){ - newVersion = policyEntityVersion-1; - } - } - } - pVersion.setActiveVersion(newVersion); - pVersion.setHigherVersion(newVersion); - try{ - policyVersionDeleted = true; - em.persist(pVersion); - }catch(Exception e){ - policyVersionDeleted = false; - } - }else{ - try{ - policyVersionDeleted = true; - em.remove(pVersion); - }catch(Exception e){ - policyVersionDeleted = false; - } - } - } - } - }else{ - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."); - response.addHeader("error", "unknown"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); - return; - } - } - em.getTransaction().commit(); - }catch(Exception e){ - em.getTransaction().rollback(); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR"); - response.addHeader("error", "deleteDB"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - } finally { - em.close(); - if(con != null){ - con.close(); - } - } - - if (policyVersionDeleted) { - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "delete"); - return; - } else { - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."); - response.addHeader("error", "unknown"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); - return; - } - } - - public String deletePolicyEntityData(EntityManager em, PolicyEntity policyEntity) throws SQLException{ - PolicyElasticSearchController controller = new PolicyElasticSearchController(); - PolicyRestAdapter policyData = new PolicyRestAdapter(); - String policyName = policyEntity.getPolicyName(); - try{ - if(policyName.contains("Config_")){ - em.remove(policyEntity.getConfigurationData()); - }else if(policyName.contains("Action_")){ - em.remove(policyEntity.getActionBodyEntity()); - } - String searchPolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); - policyData.setNewFileName(searchPolicyName); - controller.deleteElk(policyData); - em.remove(policyEntity); - }catch(Exception e){ - return "error"; - } - return "success"; - } - - public boolean checkPolicyGroupEntity(EntityManager em, Connection con, List peResult) throws SQLException{ - for(Object peData : peResult){ - PolicyEntity policyEntity = (PolicyEntity) peData; - Statement st = null; - ResultSet rs = null; - try{ - st = con.createStatement(); - rs = st.executeQuery("Select * from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"); - boolean gEntityList = rs.next(); - rs.close(); - if(gEntityList){ - return true; - } - }finally{ - if(st != null){ - st.close(); - } - } - } - return false; - } - - public void doAPIDeleteFromPDP(HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws IOException { - String policyName = request.getParameter("policyName"); - String groupId = request.getParameter("groupId"); - String responseString = null; - // for PUT operations the group may or may not need to exist before the operation can be done - EcompPDPGroup group = null; - try { - group = XACMLPapServlet.getPAPEngine().getGroup(groupId); - } catch (PAPException e) { - PolicyLogger.error("Exception occured While PUT operation is performing for PDP Group"+e); - } - if (group == null) { - String message = "Unknown groupId '" + groupId + "'"; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.addHeader("error", "UnknownGroup"); - response.sendError(HttpServletResponse.SC_NOT_FOUND, message); - return; - } else { - loggingContext.setServiceName("API:PAP.deletPolicyFromPDPGroup"); - if (policyName.contains("xml")) { - PolicyLogger.debug("The full file name including the extension was provided for policyName.. continue."); - } else { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... " - + "policyName must be the full name of the file to be deleted including version and extension"; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Invalid policyName... " - + "policyName must be the full name of the file to be deleted including version and extension"); - response.addHeader("error", message); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; - } - RemoveGroupPolicy removePolicy = new RemoveGroupPolicy((StdPDPGroup) group); - PDPPolicy policy = group.getPolicy(policyName); - if (policy != null) { - - if ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param"))) { - if (preSafetyCheck(policy)) { - PolicyLogger.debug("Precheck Successful."); - } - } - - removePolicy.prepareToRemove(policy); - EcompPDPGroup updatedGroup = removePolicy.getUpdatedObject(); - responseString = deletePolicyFromPDPGroup(updatedGroup, loggingContext); - } else { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP."; - PolicyLogger.error(message); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Policy does not exist on the PDP."); - response.addHeader("error", message); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - return; - } - } - if (responseString.equals("success")) { - PolicyLogger.info("Policy successfully deleted!"); - PolicyLogger.audit("Policy successfully deleted!"); - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "delete"); - return; - } else if (responseString.equals("No Group")) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Group update had bad input."; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input."); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "groupUpdate"); - response.addHeader("message", message); - return; - } else if (responseString.equals("DB Error")) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "deleteDB"); - return; - } else { - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + " Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."); - response.addHeader("error", "unknown"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); - return; - } - } - - private String deletePolicyFromPDPGroup (EcompPDPGroup group, ECOMPLoggingContext loggingContext){ - PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction(); - String response = null; - loggingContext.setServiceName("API:PAP.DeleteHandler"); - EcompPDPGroup existingGroup = null; - try { - existingGroup = XACMLPapServlet.getPAPEngine().getGroup(group.getId()); - } catch (PAPException e1) { - PolicyLogger.error("Exception occured While Deleting Policy From PDP Group"+e1); - } - if (group == null || ! (group instanceof StdPDPGroup) || existingGroup == null || ! (group.getId().equals(existingGroup.getId()))) { - String existingID = null; - if(existingGroup != null){ - existingID = existingGroup.getId(); - } - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + existingID + " objectFromJSON="+group); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response = "No Group"; - return response; - } - // The Path on the PAP side is not carried on the RESTful interface with the AC - // (because it is local to the PAP) - // so we need to fill that in before submitting the group for update - ((StdPDPGroup)group).setDirectory(((StdPDPGroup)existingGroup).getDirectory()); - try{ - acPutTransaction.updateGroup(group, "XACMLPapServlet.doAPIDelete"); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: " - +"group="+existingGroup.getId()); - response = "DB Error"; - return response; - } - try { - XACMLPapServlet.getPAPEngine().updateGroup(group); - } catch (PAPException e) { - PolicyLogger.error("Exception occured While Updating PDP Groups"+e); - response = "error in updateGroup method"; - } - PolicyLogger.debug("Group '" + group.getId() + "' updated"); - acPutTransaction.commitTransaction(); - // Group changed, which might include changing the policies - try { - newgroup = existingGroup; - } catch (Exception e) { - PolicyLogger.error("Exception occured in Group Change Method"+e); - response = "error in groupChanged method"; - } - if (response==null){ - response = "success"; - PolicyLogger.audit("Policy successfully deleted!"); - PolicyLogger.audit("Transaction Ended Successfully"); - } - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended"); - return response; - } - - public EcompPDPGroup getDeletedGroup(){ - return newgroup; - } - - public boolean preSafetyCheck(PDPPolicy policy) { - return true; - } - - public static DeleteHandler getInstance() { - try { - Class deleteHandler = Class.forName(XACMLProperties.getProperty("deletePolicy.impl.className", DeleteHandler.class.getName())); - DeleteHandler instance = (DeleteHandler) deleteHandler.newInstance(); - return instance; - } catch (Exception e) { - PolicyLogger.error(e.getMessage()); - } - return null; - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandler.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandler.java deleted file mode 100644 index 43342dd65..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandler.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.handler; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - -import com.att.research.xacml.util.XACMLProperties; - -public interface DictionaryHandler { - String DICTIONARY_DEFAULT_CLASS = DictionaryHandlerImpl.class.getName(); - - /* - * Get Instance - */ - public static DictionaryHandler getInstance(){ - try { - Class dictionaryHandler = Class.forName(XACMLProperties.getProperty("dictionary.impl.className", DICTIONARY_DEFAULT_CLASS)); - DictionaryHandler instance = (DictionaryHandler) dictionaryHandler.newInstance(); - return instance; - } catch (Exception e) { - PolicyLogger.error(e.getMessage()); - } - return null; - } - - /* - * Get Equivalent for Dictionary Services. - */ - public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response); - /* - * Put Equivalent for Dictionary Services. - */ - public void doDictionaryAPIPut(HttpServletRequest request, HttpServletResponse response); - - /** - * Can be used to extend the services. - * - * getflag=true indicates Get Request. - * getflag=false indicates Put Request. - * @return - */ - public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag); -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java deleted file mode 100644 index 8b462bad2..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java +++ /dev/null @@ -1,323 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.handler; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.pap.xacml.rest.service.DictionaryService; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; - -public class DictionaryHandlerImpl implements DictionaryHandler{ - /* - * Get Equivalent for Dictionary Services. - */ - public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response) { - String dictionaryType = request.getParameter("dictionaryType"); - try { - DictionaryService dictionary = new DictionaryService(); - switch (dictionaryType) { - case "EcompName": - dictionary.getEcompDictionary(request, response); - break; - case "Attribute": - dictionary.getAttributeDictionary(request, response); - break; - case "Action": - dictionary.getActionPolicyDictionary(request, response); - break; - case "BRMSParamTemplate": - dictionary.getBRMSParamDictionary(request, response); - break; - case "VSCLAction": - dictionary.getVSCLAction(request, response); - break; - case "VNFType": - dictionary.getVnfType(request, response); - break; - case "PEPOptions": - dictionary.getPEPOptions(request, response); - break; - case "Varbind": - dictionary.getVarbind(request, response); - break; - case "Service": - dictionary.getServiceType(request, response); - break; - case "Site": - dictionary.getSiteType(request, response); - break; - case "Settings": - dictionary.getSettingsDictionary(request, response); - break; - case "DescriptiveScope": - dictionary.getDescriptiveDictionary(request, response); - break; - case "Enforcer": - dictionary.getEnforcerDictionary(request, response); - break; - case "ActionList": - dictionary.getActionListDictionary(request, response); - break; - case "ProtocolList": - dictionary.getProtocolListDictionary(request, response); - break; - case "Zone": - dictionary.getZoneDictionary(request, response); - break; - case "SecurityZone": - dictionary.getSecurityZoneDictionary(request, response); - break; - case "PrefixList": - dictionary.getPrefixListDictionary(request, response); - break; - case "AddressGroup": - dictionary.getAddressGroupDictionary(request, response); - break; - case "ServiceGroup": - dictionary.getServiceGroupDictionary(request, response); - break; - case "ServiceList": - dictionary.getServiceListDictionary(request, response); - break; - case "TermList": - case "RuleList": - case "FirewallRuleList": - case "Term": - dictionary.getTermListDictionary(request, response); - break; - case "MicroServiceLocation": - dictionary.getMicroServiceLocationDictionary(request, response); - break; - case "MicroServiceConfigName": - dictionary.getMicroServiceConfigNameDictionary(request, response); - break; - case "DCAEUUID": - dictionary.getDCAEUUIDDictionary(request, response); - break; - case "MicroServiceModels": - dictionary.getMicroServiceModelsDictionary(request, response); - break; - case "PolicyScopeService": - dictionary.getPSServiceDictionary(request, response); - break; - case "PolicyScopeResource": - dictionary.getPSResourceDictionary(request, response); - break; - case "PolicyScopeType": - dictionary.getPSTypeDictionary(request, response); - break; - case "PolicyScopeClosedLoop": - dictionary.getPSClosedLoopDictionary(request, response); - break; - case "GroupPolicyScopeList": - dictionary.getPSGroupScopeDictionary(request, response); - break; - case "RiskType": - dictionary.getRiskTypeDictionary(request, response); - break; - case "SafePolicyWarning": - dictionary.getSafePolicyWarningDictionary(request, response); - break; - case "MicroServiceDictionary": - dictionary.getMicroServiceDictionary(request, response); - break; - default: - extendedOptions(dictionaryType, request, response, true); - return; - } - } catch (Exception e) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Querying the Database: " + e.getMessage(); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DictionaryHandler", " Error Querying the Database."); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "dictionaryDBQuery"); - response.addHeader("error", message); - return; - } - } - - /** - * Can be used to extend the services. - * - * getflag=true indicates Get Request. - * getflag=false indicates Put Request. - * @return - */ - public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag) { - // Default code - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Invalid Dictionary in Request."; - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "DictionaryHandler", " Invalid Dictionary in Request."); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.setHeader("error", "dictionary"); - response.addHeader("error", message); - return null; - } - - public void doDictionaryAPIPut(HttpServletRequest request, HttpServletResponse response) { - String result = null; - String dictionaryType = request.getParameter("dictionaryType"); - String operation = request.getParameter("operation"); - try { - DictionaryService dictionary = new DictionaryService(); - switch (dictionaryType) { - case "EcompName": - result = dictionary.saveEcompDictionary(request, response); - break; - case "Attribute": - result = dictionary.saveAttributeDictionary(request, response); - break; - case "Action": - result = dictionary.saveActionPolicyDictionary(request, response); - break; - case "BRMSParamTemplate": - result = dictionary.saveBRMSParamDictionary(request, response); - break; - case "VSCLAction": - result = dictionary.saveVSCLAction(request, response); - break; - case "VNFType": - result = dictionary.saveVnfType(request, response); - break; - case "PEPOptions": - result = dictionary.savePEPOptions(request, response); - break; - case "Varbind": - result = dictionary.saveVarbind(request, response); - break; - case "Service": - result = dictionary.saveServiceType(request, response); - break; - case "Site": - result = dictionary.saveSiteType(request, response); - break; - case "Settings": - result = dictionary.saveSettingsDictionary(request, response); - break; - case "DescriptiveScope": - result = dictionary.saveDescriptiveDictionary(request, response); - break; - case "Enforcer": - result = dictionary.saveEnforcerDictionary(request, response); - break; - case "ActionList": - result = dictionary.saveActionListDictionary(request, response); - break; - case "ProtocolList": - result = dictionary.saveProtocolListDictionary(request, response); - break; - case "Zone": - result = dictionary.saveZoneDictionary(request, response); - break; - case "SecurityZone": - result = dictionary.saveSecurityZoneDictionary(request, response); - break; - case "PrefixList": - result = dictionary.savePrefixListDictionary(request, response); - break; - case "AddressGroup": - result = dictionary.saveAddressGroupDictionary(request, response); - break; - case "ServiceGroup": - result = dictionary.saveServiceGroupDictionary(request, response); - break; - case "ServiceList": - result = dictionary.saveServiceListDictionary(request, response); - break; - case "TermList": - case "RuleList": - case "FirewallRuleList": - case "Term": - result = dictionary.saveTermListDictionary(request, response); - break; - case "MicroServiceLocation": - result = dictionary.saveMicroServiceLocationDictionary(request, response); - break; - case "MicroServiceConfigName": - result = dictionary.saveMicroServiceConfigNameDictionary(request, response); - break; - case "DCAEUUID": - result = dictionary.saveDCAEUUIDDictionary(request, response); - break; - case "MicroServiceModels": - result = dictionary.saveMicroServiceModelsDictionary(request, response); - break; - case "PolicyScopeService": - result = dictionary.savePSServiceDictionary(request, response); - break; - case "PolicyScopeResource": - result = dictionary.savePSResourceDictionary(request, response); - break; - case "PolicyScopeType": - result = dictionary.savePSTypeDictionary(request, response); - break; - case "PolicyScopeClosedLoop": - result = dictionary.savePSClosedLoopDictionary(request, response); - break; - case "GroupPolicyScopeList": - result = dictionary.savePSGroupScopeDictionary(request, response); - break; - case "RiskType": - result = dictionary.saveRiskTypeDictionary(request, response); - break; - case "SafePolicyWarning": - result = dictionary.saveSafePolicyWarningDictionary(request, response); - break; - case "MicroServiceDictionary": - result = dictionary.saveMicroServiceDictionary(request, response); - break; - default: - result = extendedOptions(dictionaryType, request, response, false); - if(result==null){ - return; - }else{ - break; - } - } - } catch (Exception e) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Updating the Database: " + e.getMessage(); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error Updating the Database."); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); - return; - } - if (result.equalsIgnoreCase("Success")) { - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("successMapKey", "success"); - if (operation.equalsIgnoreCase("update")) { - response.addHeader("operation", "updateDictionary"); - } else { - response.addHeader("operation", "createDictionary"); - } - } else if (result.equalsIgnoreCase("Duplicate")) { - response.setStatus(HttpServletResponse.SC_CONFLICT); - response.addHeader("error", "dictionaryItemExists"); - } else if (result.equalsIgnoreCase("DuplicateGroup")) { - response.setStatus(HttpServletResponse.SC_CONFLICT); - response.addHeader("error", "duplicateGroup"); - } else { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Updating the Database."; - PolicyLogger.error(message); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); - } - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/PushPolicyHandler.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/PushPolicyHandler.java deleted file mode 100644 index 009a2d601..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/PushPolicyHandler.java +++ /dev/null @@ -1,123 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.handler; - -import java.io.File; -import java.net.URI; -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.Query; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -import org.openecomp.policy.rest.jpa.PolicyVersion; -import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; -import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; - -import com.att.research.xacml.util.XACMLProperties; - -public class PushPolicyHandler { - - /* - * Get Active Version. - */ - public void getActiveVersion(HttpServletRequest request, HttpServletResponse response) { - EntityManager em = null; - if(XACMLPapServlet.getEmf()!=null){ - em = (EntityManager) XACMLPapServlet.getEmf().createEntityManager(); - } - if (em==null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + XACMLPapServlet.getPersistenceUnit()); - return; - } - String policyScope = request.getParameter("policyScope"); - String filePrefix = request.getParameter("filePrefix"); - String policyName = request.getParameter("policyName"); - - String pvName = policyScope + File.separator + filePrefix + policyName; - int activeVersion = 0; - - //Get the Active Version to use in the ID - em.getTransaction().begin(); - Query query = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname"); - query.setParameter("pname", pvName); - - @SuppressWarnings("rawtypes") - List result = query.getResultList(); - PolicyVersion versionEntity = null; - if (!result.isEmpty()) { - versionEntity = (PolicyVersion) result.get(0); - em.persist(versionEntity); - activeVersion = versionEntity.getActiveVersion(); - em.getTransaction().commit(); - } else { - PolicyLogger.debug("No PolicyVersion using policyName found"); - } - - //clean up connection - em.close(); - if (String.valueOf(activeVersion)!=null || !String.valueOf(activeVersion).equalsIgnoreCase("")) { - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("version", String.valueOf(activeVersion)); - } else { - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - } - } - - /* - * Get Selected URI path. - */ - public void getSelectedURI(HttpServletRequest request, HttpServletResponse response) { - String gitPath = request.getParameter("gitPath"); - File file = new File(gitPath); - PolicyLogger.debug("The fileItem is : " + file.toString()); - URI selectedURI = file.toURI(); - String uri = selectedURI.toString(); - if (!uri.equalsIgnoreCase("")) { - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("selectedURI", uri); - } else { - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - } - } - - public boolean preSafetyCheck(StdPDPPolicy policy, String configHome){ - return true; - } - - public boolean preSafetyCheck(EcompPDPGroup policy, String configHome){ - return true; - } - - public static PushPolicyHandler getInstance() { - try { - Class pushPolicyHandler = Class.forName(XACMLProperties.getProperty("pushPolicy.impl.className", PushPolicyHandler.class.getName())); - PushPolicyHandler instance = (PushPolicyHandler) pushPolicyHandler.newInstance(); - return instance; - } catch (Exception e) { - PolicyLogger.error(e.getMessage()); - } - return null; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/SavePolicyHandler.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/SavePolicyHandler.java deleted file mode 100644 index 4624f74aa..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/handler/SavePolicyHandler.java +++ /dev/null @@ -1,157 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.handler; - -import java.io.IOException; -import java.util.HashMap; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.parsers.ParserConfigurationException; - -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -import org.openecomp.policy.pap.xacml.rest.policycontroller.PolicyCreation; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.utils.PolicyUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; -import org.xml.sax.SAXException; - -import com.att.research.xacml.util.XACMLProperties; - -public class SavePolicyHandler { - private HashMap ErrorHeaders = null; - - public void doPolicyAPIPut(HttpServletRequest request, HttpServletResponse response) throws IOException { - String operation = request.getParameter("operation"); - String policyType = request.getParameter("policyType"); - String apiflag = request.getParameter("apiflag"); - PolicyCreation creation = new PolicyCreation(); - if ( policyType != null ) { - PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); - if("update".equalsIgnoreCase(operation)){ - policyAdapter.setEditPolicy(true); - }else{ - policyAdapter.setEditPolicy(false); - } - - // get the request 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(request.getInputStream()); - scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - PolicyLogger.info("JSON request from API: " + json); - // convert Object sent as JSON into local object - StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class); - //Set policyAdapter values including parentPath (Common to all policy types) - try { - policyAdapter = setDataToPolicyAdapter(policy, policyType, apiflag); - - if(!extendedPolicyOptions(policyAdapter, response)){ - creation.savePolicy(policyAdapter, response); - } - if ("update".equalsIgnoreCase(operation)) { - response.addHeader("operation", "update"); - } else { - response.addHeader("operation", "create"); - } - } catch (Exception e1) { - PolicyLogger.error(XACMLErrorConstants.ERROR_UNKNOWN + - "Could not set data to policy adapter "+ e1.getMessage()); - } - } - } - - private PolicyRestAdapter setDataToPolicyAdapter(StdPAPPolicy policy, String policyType, String apiflag) throws ParserConfigurationException, ServletException, SAXException, IOException{ - PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); - policyAdapter.setApiflag(apiflag); - /* - * set policy adapter values for Building JSON object containing policy data - */ - //Common among policy types - policyAdapter.setPolicyName(policy.getPolicyName()); - policyAdapter.setPolicyDescription(policy.getPolicyDescription()); - policyAdapter.setEcompName(policy.getEcompName()); //Config Base and Decision Policies - policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"); - - policyAdapter.setPolicyType(policyType); - policyAdapter.setDynamicFieldConfigAttributes(policy.getDynamicFieldConfigAttributes()); - policyAdapter.setEditPolicy(policy.isEditPolicy()); - policyAdapter.setEntityManagerFactory(XACMLPapServlet.getEmf()); - //Config Specific - policyAdapter.setConfigName(policy.getConfigName()); //Base and Firewall - policyAdapter.setConfigBodyData(policy.getConfigBodyData()); //Base - policyAdapter.setConfigType((policy.getConfigType()!=null) ? policy.getConfigType().toUpperCase(): null); //Base - policyAdapter.setJsonBody(policy.getJsonBody()); //Firewall, ClosedLoop - policyAdapter.setConfigPolicyType(policy.getConfigPolicyType()); - policyAdapter.setDraft(policy.isDraft()); //ClosedLoop_Fault - policyAdapter.setServiceType(policy.getServiceType()); //ClosedLoop_PM - policyAdapter.setUuid(policy.getUuid()); //Micro Service - policyAdapter.setLocation(policy.getMsLocation()); //Micro Service - policyAdapter.setPriority(policy.getPriority()); //Micro Service - policyAdapter.setPolicyScope(policy.getDomainDir()); - policyAdapter.setRiskType(policy.getRiskType()); //Safe Policy Attributes - policyAdapter.setRiskLevel(policy.getRiskLevel());//Safe Policy Attributes - policyAdapter.setGuard(policy.getGuard());//Safe Policy Attributes - policyAdapter.setTtlDate(policy.getTTLDate());//Safe Policy Attributes - policyAdapter.setBrmsParamBody(policy.getDrlRuleAndUIParams()); - policyAdapter.setBrmsDependency(policy.getBrmsDependency()); // BRMS Policies. - policyAdapter.setBrmsController(policy.getBrmsController()); // BRMS Policies. - //Action Policy Specific - policyAdapter.setActionAttribute(policy.getActionAttribute()); //comboDictValue - policyAdapter.setActionPerformer(policy.getActionPerformer()); - policyAdapter.setDynamicRuleAlgorithmLabels(policy.getDynamicRuleAlgorithmLabels()); - policyAdapter.setDynamicRuleAlgorithmCombo(policy.getDynamicRuleAlgorithmCombo()); - policyAdapter.setDynamicRuleAlgorithmField1(policy.getDynamicRuleAlgorithmField1()); - policyAdapter.setDynamicRuleAlgorithmField2(policy.getDynamicRuleAlgorithmField2()); - //Decision Policy Specific - policyAdapter.setDynamicSettingsMap(policy.getDynamicSettingsMap()); - policyAdapter.setRuleProvider(policy.getProviderComboBox()); - policyAdapter.setDomainDir(policyAdapter.getPolicyScope()); - policyAdapter.setDomain(policyAdapter.getPolicyScope()); - return policyAdapter; - } - - public boolean extendedPolicyOptions(PolicyRestAdapter policyAdapter, HttpServletResponse response){ - return false; - } - - public void addErrorHeader(String key, String value){ - if(ErrorHeaders==null){ - ErrorHeaders= new HashMap<>(); - } - ErrorHeaders.put(key, value); - } - - public static SavePolicyHandler getInstance() { - try { - Class savePolicyHandler = Class.forName(XACMLProperties.getProperty("savePolicy.impl.className", SavePolicyHandler.class.getName())); - SavePolicyHandler instance = (SavePolicyHandler) savePolicyHandler.newInstance(); - return instance; - } catch (Exception e) { - PolicyLogger.error(e.getMessage()); - } - return null; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/model/PDPPolicyContainer.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/model/PDPPolicyContainer.java deleted file mode 100644 index 13a1801bd..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/model/PDPPolicyContainer.java +++ /dev/null @@ -1,348 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.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.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.util.PolicyContainer; -import org.openecomp.policy.pap.xacml.rest.util.PolicyItemSetChangeNotifier; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; - -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.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. - */ - public static String PROPERTY_ID = "Id"; - - /** - * String identifier of a file's "name" property. - */ - public static String PROPERTY_NAME = "Name"; - - /** - * String identifier of a file's "name" property. - */ - public static String PROPERTY_VERSION = "Version"; - - /** - * String identifier of a file's "Description" property. - */ - public static String PROPERTY_DESCRIPTION = "Description"; - - /** - * String identifier of a file's "IsRoot" property. - */ - public static String PROPERTY_ISROOT = "Root"; - - /** - * List of the string identifiers for the available properties. - */ - public 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/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/model/RemoveGroupPolicy.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/model/RemoveGroupPolicy.java deleted file mode 100644 index 83d0991f5..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/model/RemoveGroupPolicy.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.model; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; -import org.openecomp.policy.xacml.std.pap.StdPDPGroup; - -import com.att.research.xacml.api.pap.PDPPolicy; - -public class RemoveGroupPolicy { - - - //Container from where we are fetching the policies - private static PDPPolicyContainer policyContainer; - - private final RemoveGroupPolicy self = this; - private StdPDPGroup updatedObject; - private final StdPDPGroup group; - private boolean isSaved = false; - - public RemoveGroupPolicy(StdPDPGroup group) { - - this.group = group; - - } - - public void prepareToRemove(PDPPolicy policy) { - - if (this.group == null) { - return; - } - - RemoveGroupPolicy.policyContainer = new PDPPolicyContainer(group); - - RemoveGroupPolicy.policyContainer.removeItem(policy); - - self.doSave(); - - self.isSaved = true; - - } - - @SuppressWarnings("unchecked") - protected void doSave() { - if (this.group == null) { - return; - } - - //StdPDPGroup pdpGroup = (StdPDPGroup) group; - StdPDPGroup updatedGroupObject = new StdPDPGroup( - group.getId(), - group.isDefaultGroup(), - group.getName(), - group.getDescription(), - null); - - // replace the original set of Policies with the set from the container (possibly modified by the user) - Set changedPolicies = new HashSet<>(); - changedPolicies.addAll((Collection) RemoveGroupPolicy.policyContainer.getItemIds()); - updatedGroupObject.setPolicies(changedPolicies); - updatedGroupObject.setEcompPdps(this.group.getEcompPdps()); - - // replace the original set of PIP Configs with the set from the container - updatedGroupObject.setPipConfigs(this.group.getPipConfigs()); - - // copy those things that the user cannot change from the original to the new object - updatedGroupObject.setStatus(this.group.getStatus()); - - this.updatedObject = updatedGroupObject; - } - - public boolean isRemoved() { - return this.isSaved; - } - - public EcompPDPGroup getUpdatedObject() { - return this.updatedObject; - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/model/package-info.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/model/package-info.java deleted file mode 100644 index d3673eb2b..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/model/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.model; diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java deleted file mode 100644 index e6f322a72..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/PolicyCreation.java +++ /dev/null @@ -1,550 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.policycontroller; - -import java.io.File; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringUtils; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -import org.openecomp.policy.pap.xacml.rest.components.ActionPolicy; -import org.openecomp.policy.pap.xacml.rest.components.ClosedLoopPolicy; -import org.openecomp.policy.pap.xacml.rest.components.ConfigPolicy; -import org.openecomp.policy.pap.xacml.rest.components.CreateBrmsParamPolicy; -import org.openecomp.policy.pap.xacml.rest.components.CreateBrmsRawPolicy; -import org.openecomp.policy.pap.xacml.rest.components.CreateClosedLoopPerformanceMetrics; -import org.openecomp.policy.pap.xacml.rest.components.DecisionPolicy; -import org.openecomp.policy.pap.xacml.rest.components.FirewallConfigPolicy; -import org.openecomp.policy.pap.xacml.rest.components.MicroServiceConfigPolicy; -import org.openecomp.policy.pap.xacml.rest.components.Policy; -import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDao; -import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; -import org.openecomp.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController; -import org.openecomp.policy.pap.xacml.rest.util.AbstractPolicyCreation; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.ActionPolicyDict; -import org.openecomp.policy.rest.jpa.BRMSParamTemplate; -import org.openecomp.policy.rest.jpa.PolicyEditorScopes; -import org.openecomp.policy.rest.jpa.PolicyVersion; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.HttpMessageNotReadableException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; - -import com.fasterxml.jackson.databind.ObjectMapper; - - -@RestController -@RequestMapping("/") -public class PolicyCreation extends AbstractPolicyCreation{ - - private static final Logger LOGGER = FlexLogger.getLogger(PolicyCreation.class); - - private String ruleID = ""; - private PolicyDBDao policyDBDao; - String CLName = null; - - private static CommonClassDao commonClassDao; - - public static CommonClassDao getCommonClassDao() { - return commonClassDao; - } - - public static void setCommonClassDao(CommonClassDao commonClassDao) { - PolicyCreation.commonClassDao = commonClassDao; - } - - @Autowired - public PolicyCreation(CommonClassDao commonClassDao){ - PolicyCreation.commonClassDao = commonClassDao; - } - - public PolicyCreation(){} - - @RequestMapping(value="/policycreation/save_policy", method = RequestMethod.POST) - @ResponseBody - public ResponseEntity savePolicy(@RequestBody PolicyRestAdapter policyData, HttpServletResponse response) throws Exception{ - String body = null; - HttpStatus status = HttpStatus.BAD_REQUEST; - Map successMap = new HashMap<>(); - Map attributeMap = new HashMap<>(); - PolicyVersion policyVersionDao; - try { - - Policy newPolicy = null; - String policyConfigType = null; - String userId = policyData.getUserId(); - - if (policyData.getTtlDate()==null){ - policyData.setTtlDate("NA"); - }else{ - String dateTTL = policyData.getTtlDate(); - String newDate = convertDate(dateTTL, false); - policyData.setTtlDate(newDate); - } - - String policyType = policyData.getPolicyType(); - - String filePrefix = null; - if (policyType.equalsIgnoreCase("Config")) { - policyConfigType = policyData.getConfigPolicyType(); - if (policyConfigType.equalsIgnoreCase("Firewall Config")) { - filePrefix = "Config_FW_"; - }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_Fault")) { - filePrefix = "Config_Fault_"; - }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_PM")) { - filePrefix = "Config_PM_"; - }else if (policyConfigType.equalsIgnoreCase("Micro Service")) { - filePrefix = "Config_MS_"; - }else if (policyConfigType.equalsIgnoreCase("BRMS_Raw")) { - filePrefix = "Config_BRMS_Raw_"; - }else if (policyConfigType.equalsIgnoreCase("BRMS_Param")) { - filePrefix = "Config_BRMS_Param_"; - }else { - filePrefix = "Config_"; - } - } else if (policyType.equalsIgnoreCase("Action")) { - filePrefix = "Action_"; - } else if (policyType.equalsIgnoreCase("Decision")) { - filePrefix = "Decision_"; - } - - int version = 0; - int highestVersion = 0; - String createdBy = ""; - String modifiedBy = userId; - String scopeCheck = policyData.getDomainDir().replace(".", File.separator); - PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scopeCheck); - if(policyEditorScope == null){ - UserInfo userInfo = new UserInfo(); - userInfo.setUserName("API"); - userInfo.setUserLoginId("API"); - PolicyEditorScopes editorScope = new PolicyEditorScopes(); - editorScope.setScopeName(scopeCheck); - editorScope.setUserCreatedBy(userInfo); - editorScope.setUserModifiedBy(userInfo); - commonClassDao.save(editorScope); - } - //get the highest version of policy from policy version table. - String dbCheckPolicyName = policyData.getDomainDir() + File.separator + filePrefix + policyData.getPolicyName(); - PolicyVersion policyVersion = getPolicyVersionData(dbCheckPolicyName); - if(policyVersion == null){ - highestVersion = 0; - }else{ - highestVersion = policyVersion.getHigherVersion(); - } - - if(highestVersion != 0 && policyVersion != null){ - if(policyData.isEditPolicy()){ - version = highestVersion +1; - if(userId ==null){ - modifiedBy = "API"; - }else{ - modifiedBy = userId; - } - policyData.setUserId("API"); - createdBy = policyVersion.getCreatedBy(); - policyVersionDao = policyVersion; - policyVersionDao.setActiveVersion(version); - policyVersionDao.setHigherVersion(version); - policyVersionDao.setModifiedBy(modifiedBy); - }else{ - body = "policyExists"; - status = HttpStatus.CONFLICT; - response.setStatus(HttpServletResponse.SC_CONFLICT); - response.addHeader("error", "policyExists"); - response.addHeader("policyName", policyData.getPolicyName()); - return new ResponseEntity(body, status); - } - }else{ - version = 1; - if(userId == null){ - createdBy = "API"; - modifiedBy = "API"; - policyData.setUserId("API"); - }else{ - createdBy = userId; - modifiedBy = userId; - policyData.setUserId("API"); - } - policyVersionDao = new PolicyVersion(); - policyVersionDao.setPolicyName(dbCheckPolicyName); - policyVersionDao.setActiveVersion(version); - policyVersionDao.setHigherVersion(version); - policyVersionDao.setCreatedBy(createdBy); - policyVersionDao.setModifiedBy(modifiedBy); - } - - policyData.setPolicyID(newPolicyID()); - policyData.setRuleID(ruleID); - - String policyFileName = dbCheckPolicyName.replace(File.separator, ".")+ "." + version + ".xml"; - policyData.setNewFileName(policyFileName); - policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); - policyData.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"); - if(policyData.getApiflag() == null){ - //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON - if(policyData.getAttributes() != null){ - if(policyData.getAttributes().size() > 0){ - for(Object attribute : policyData.getAttributes()){ - if(attribute instanceof LinkedHashMap){ - String key = ((LinkedHashMap) attribute).get("key").toString(); - String value = ((LinkedHashMap) attribute).get("value").toString(); - attributeMap.put(key, value); - } - } - } - } - policyData.setDynamicFieldConfigAttributes(attributeMap); - } - - policyData.setVersion(String.valueOf(version)); - policyData.setHighestVersion(version); - - // Calling Component class per policy type - if (policyType.equalsIgnoreCase("Config")) { - if (policyConfigType.equalsIgnoreCase("Firewall Config")) { - newPolicy = new FirewallConfigPolicy(policyData); - }else if (policyConfigType.equalsIgnoreCase("BRMS_Raw")) { - policyData.setEcompName("DROOLS"); - policyData.setConfigName("BRMS_RAW_RULE"); - newPolicy = new CreateBrmsRawPolicy(policyData); - }else if (policyConfigType.equalsIgnoreCase("BRMS_Param")) { - policyData.setEcompName("DROOLS"); - policyData.setConfigName("BRMS_PARAM_RULE"); - Map drlRuleAndUIParams = new HashMap<>(); - if(policyData.getApiflag() == null){ - // If there is any dynamic field create the matches here - String key="templateName"; - String value=(String) policyData.getRuleName(); - drlRuleAndUIParams.put(key, value); - if(policyData.getRuleData().size() > 0){ - for(Object keyValue: policyData.getRuleData().keySet()){ - drlRuleAndUIParams.put(keyValue.toString(), policyData.getRuleData().get(keyValue).toString()); - } - } - policyData.setBrmsParamBody(drlRuleAndUIParams); - }else{ - drlRuleAndUIParams=policyData.getBrmsParamBody(); - String modelName= drlRuleAndUIParams.get("templateName"); - PolicyLogger.info("Template name from API is: "+modelName); - - BRMSParamTemplate template = (BRMSParamTemplate) commonClassDao.getEntityItem(BRMSParamTemplate.class, "ruleName", modelName); - if(template == null){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, " - + modelName + " was not found in the dictionary."; - body = message; - status = HttpStatus.BAD_REQUEST; - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); - response.addHeader("modelName", modelName); - return new ResponseEntity(body, status); - } - } - newPolicy = new CreateBrmsParamPolicy(policyData); - }else if (policyConfigType.equalsIgnoreCase("Base")) { - newPolicy = new ConfigPolicy(policyData); - }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_Fault")) { - newPolicy = new ClosedLoopPolicy(policyData); - }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_PM")) { - if(policyData.getApiflag() == null){ - policyData.setServiceType(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString()); - ObjectMapper jsonMapper = new ObjectMapper(); - String jsonBody = jsonMapper.writeValueAsString(policyData.getJsonBodyData()); - jsonBody = jsonBody.replaceFirst("\\{", "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\","); - jsonBody = jsonBody.replace("serviceTypeFieldValue", policyData.getServiceType()); - policyData.setJsonBody(jsonBody); - } - newPolicy = new CreateClosedLoopPerformanceMetrics(policyData); - }else if (policyConfigType.equalsIgnoreCase("Micro Service")) { - newPolicy = new MicroServiceConfigPolicy(policyData); - } - }else if(policyType.equalsIgnoreCase("Action")) { - if(policyData.getApiflag() == null){ - List dynamicRuleAlgorithmLabels = new LinkedList<>(); - List dynamicRuleAlgorithmCombo = new LinkedList<>(); - List dynamicRuleAlgorithmField1 = new LinkedList<>(); - List dynamicRuleAlgorithmField2 = new LinkedList<>(); - - - if(policyData.getRuleAlgorithmschoices().size() > 0){ - for(Object attribute : policyData.getRuleAlgorithmschoices()){ - if(attribute instanceof LinkedHashMap){ - 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(); - dynamicRuleAlgorithmLabels.add(label); - dynamicRuleAlgorithmField1.add(key); - dynamicRuleAlgorithmCombo.add(rule); - dynamicRuleAlgorithmField2.add(value); - } - } - } - - String actionDictValue = policyData.getActionAttributeValue(); - ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", actionDictValue)); - String actionBodyString = jsonData.getBody(); - String actionDictHeader = jsonData.getHeader(); - String actionDictType = jsonData.getType(); - String actionDictUrl = jsonData.getUrl(); - String actionDictMethod = jsonData.getMethod(); - policyData.setActionDictHeader(actionDictHeader); - policyData.setActionDictType(actionDictType); - policyData.setActionDictUrl(actionDictUrl); - policyData.setActionDictMethod(actionDictMethod); - policyData.setActionAttribute(actionDictValue); - policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); - policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); - policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); - policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); - if (actionBodyString != null) { - policyData.setActionBody(actionBodyString); - } - } - newPolicy = new ActionPolicy(policyData); - } else if (policyType.equalsIgnoreCase("Decision")) { - if(policyData.getApiflag() == null){ - Map settingsMap = new HashMap<>(); - Map treatmentMap = new HashMap<>(); - List dynamicRuleAlgorithmLabels = new LinkedList<>(); - List dynamicRuleAlgorithmCombo = new LinkedList<>(); - List dynamicRuleAlgorithmField1 = new LinkedList<>(); - List dynamicRuleAlgorithmField2 = new LinkedList<>(); - List dynamicVariableList = new LinkedList<>(); - List dataTypeList = new LinkedList<>(); - List errorCodeList = new LinkedList<>(); - List treatmentList = new LinkedList<>(); - - if(policyData.getSettings().size() > 0){ - for(Object settingsData : policyData.getSettings()){ - if(settingsData instanceof LinkedHashMap){ - String key = ((LinkedHashMap) settingsData).get("key").toString(); - String value = ((LinkedHashMap) settingsData).get("value").toString(); - settingsMap.put(key, value); - } - } - } - if(policyData.getRuleAlgorithmschoices()!=null && policyData.getRuleAlgorithmschoices().size() > 0){ - for(Object attribute : policyData.getRuleAlgorithmschoices()){ - if(attribute instanceof LinkedHashMap){ - 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(); - dynamicRuleAlgorithmLabels.add(label); - dynamicRuleAlgorithmField1.add(key); - dynamicRuleAlgorithmCombo.add(rule); - dynamicRuleAlgorithmField2.add(value); - } - } - } - if(policyData.getRuleProvider()!=null && (policyData.getRuleProvider().equals(DecisionPolicy.GUARD_YAML)|| policyData.getRuleProvider().equals(DecisionPolicy.GUARD_BL_YAML)) - && policyData.getYamlparams()!=null){ - attributeMap.put("actor", policyData.getYamlparams().getActor()); - attributeMap.put("recipe", policyData.getYamlparams().getRecipe()); - attributeMap.put("clname", policyData.getYamlparams().getClname()); - attributeMap.put("limit", policyData.getYamlparams().getLimit()); - attributeMap.put("timeWindow", policyData.getYamlparams().getTimeWindow()); - attributeMap.put("timeUnits", policyData.getYamlparams().getTimeUnits()); - attributeMap.put("guardActiveStart", policyData.getYamlparams().getGuardActiveStart()); - attributeMap.put("guardActiveEnd", policyData.getYamlparams().getGuardActiveEnd()); - if(policyData.getYamlparams().getBlackList()!=null){ - String blackList = StringUtils.join(policyData.getYamlparams().getBlackList(), ","); - attributeMap.put("blackList", blackList); - } - if(policyData.getYamlparams().getTargets()!=null){ - String targets = StringUtils.join(policyData.getYamlparams().getTargets(),","); - attributeMap.put("targets", targets); - } - } - if(policyData.getRuleProvider()!=null && policyData.getRuleProvider().equals(DecisionPolicy.RAINY_DAY)){ - attributeMap.put("ServiceType", policyData.getRainyday().getServiceType()); - attributeMap.put("VNFType", policyData.getRainyday().getVnfType()); - attributeMap.put("BB_ID", policyData.getRainyday().getBbid()); - attributeMap.put("WorkStep", policyData.getRainyday().getWorkstep()); - - if(policyData.getRainyday().getTreatmentTableChoices()!=null && policyData.getRainyday().getTreatmentTableChoices().size() > 0){ - for (Object table : policyData.getRainyday().getTreatmentTableChoices()){ - if(table instanceof LinkedHashMap){ - String errorcode = ((LinkedHashMap) table).get("errorcode").toString(); - String treatment = ((LinkedHashMap) table).get("treatment").toString(); - treatmentMap.put(errorcode, treatment); - } - } - } - } - - policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); - policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); - policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); - policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); - policyData.setDynamicVariableList(dynamicVariableList); - policyData.setDynamicSettingsMap(settingsMap); - policyData.setDynamicFieldConfigAttributes(attributeMap); - policyData.setDataTypeList(dataTypeList); - policyData.setRainydayMap(treatmentMap); - policyData.setErrorCodeList(errorCodeList); - policyData.setTreatmentList(treatmentList); - } - newPolicy = new DecisionPolicy(policyData); - } - - if(newPolicy != null){ - newPolicy.prepareToSave(); - }else{ - body = "error"; - status = HttpStatus.INTERNAL_SERVER_ERROR; - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "error"); - return new ResponseEntity(body, status); - } - - PolicyDBDaoTransaction policyDBDaoTransaction = null; - try{ - policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(XACMLPapServlet.getEmf()); - policyDBDaoTransaction = policyDBDao.getNewTransaction(); - policyDBDaoTransaction.createPolicy(newPolicy, policyData.getUserId()); - successMap = newPolicy.savePolicies(); - if(successMap.containsKey("success")){ - policyDBDaoTransaction.commitTransaction(); - if(policyData.isEditPolicy()){ - commonClassDao.update(policyVersionDao); - }else{ - commonClassDao.save(policyVersionDao); - } - try{ - PolicyElasticSearchController search= new PolicyElasticSearchController(); - search.updateElk(policyData); - }catch(Exception e){ - LOGGER.error("Error Occured while saving policy to Elastic Database"+e); - } - body = "success"; - status = HttpStatus.OK; - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("successMapKey", "success"); - response.addHeader("policyName", policyData.getNewFileName()); - - //get message from the SafetyCheckerResults if present - String safetyCheckerResponse = policyData.getClWarning(); - String existingCLName = policyData.getExistingCLName(); - - //if safetyCheckerResponse is not null add a header to send back with response - if(safetyCheckerResponse!=null) { - PolicyLogger.info("SafetyCheckerResponse message: " + safetyCheckerResponse); - response.addHeader("safetyChecker", safetyCheckerResponse); - response.addHeader("newCLName", CLName); - response.addHeader("conflictCLName", existingCLName); - } else { - PolicyLogger.info("SafetyCheckerResponse was empty or null."); - } - - }else if (successMap.containsKey("invalidAttribute")) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Attribute"; - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine " + policyData.getActionAttribute() + " in the ActionPolicyDict table."); - body = "invalidAttribute"; - status = HttpStatus.BAD_REQUEST; - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("invalidAttribute", policyData.getActionAttribute()); - response.addHeader("error", message); - response.addHeader("policyName", policyData.getPolicyName()); - }else if (successMap.containsKey("fwdberror")) { - policyDBDaoTransaction.rollbackTransaction(); - body = "fwdberror"; - status = HttpStatus.BAD_REQUEST; - String message = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Error when inserting Firewall ConfigBody data into the database."; - PolicyLogger.error(message); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); - response.addHeader("policyName", policyData.getPolicyName()); - } else if (successMap.get("error").equals("Validation Failed")) { - policyDBDaoTransaction.rollbackTransaction(); - String message = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Error Validating the Policy on the PAP."; - PolicyLogger.error(message); - body = "Validation"; - status = HttpStatus.BAD_REQUEST; - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); - response.addHeader("policyName", policyData.getPolicyName()); - }else { - policyDBDaoTransaction.rollbackTransaction(); - body = "error"; - status = HttpStatus.INTERNAL_SERVER_ERROR; - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "error"); - } - }catch(Exception e){ - if(policyDBDaoTransaction != null){ - policyDBDaoTransaction.rollbackTransaction(); - } - } - } - catch (Exception e){ - LOGGER.error("Exception Occured : "+e); - body = "error"; - response.addHeader("error", e.getMessage()); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - } - return new ResponseEntity<>(body, status); - } - - @ExceptionHandler({ HttpMessageNotReadableException.class }) - public ResponseEntity messageNotReadableExceptionHandler(HttpServletRequest req, HttpMessageNotReadableException exception) { - LOGGER.error("Request not readable: {}", exception); - StringBuilder message = new StringBuilder(); - message.append(exception.getMessage()); - if (exception.getCause() != null) { - message.append(" Reason Caused: " - + exception.getCause().getMessage()); - } - return new ResponseEntity<>(message.toString(), HttpStatus.BAD_REQUEST); - } - - public PolicyVersion getPolicyVersionData(String dbCheckPolicyName){ - PolicyVersion entityItem = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", dbCheckPolicyName); - if (entityItem != null) { - if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ - return entityItem; - } - } - return entityItem; - } -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/package-info.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/package-info.java deleted file mode 100644 index 4eacd4b76..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/policycontroller/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.policycontroller; \ No newline at end of file diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/DictionaryService.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/DictionaryService.java deleted file mode 100644 index 662df9a36..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/DictionaryService.java +++ /dev/null @@ -1,995 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.service; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.controller.ActionPolicyDictionaryController; -import org.openecomp.policy.pap.xacml.rest.controller.BRMSDictionaryController; -import org.openecomp.policy.pap.xacml.rest.controller.ClosedLoopDictionaryController; -import org.openecomp.policy.pap.xacml.rest.controller.DecisionPolicyDictionaryController; -import org.openecomp.policy.pap.xacml.rest.controller.DescriptiveDictionaryController; -import org.openecomp.policy.pap.xacml.rest.controller.DictionaryController; -import org.openecomp.policy.pap.xacml.rest.controller.EnforcerDictionaryController; -import org.openecomp.policy.pap.xacml.rest.controller.FirewallDictionaryController; -import org.openecomp.policy.pap.xacml.rest.controller.MicroServiceDictionaryController; -import org.openecomp.policy.pap.xacml.rest.controller.PolicyScopeDictionaryController; -import org.openecomp.policy.pap.xacml.rest.controller.SafePolicyController; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.stereotype.Service; -import org.springframework.web.servlet.ModelAndView; - - -@Service("DictionaryService") -public class DictionaryService { - - private static final Logger LOGGER = FlexLogger.getLogger(DictionaryService.class); - - /* - * Methods that call the controller method directly to Save and Update dictionary data - */ - public String saveEcompDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - DictionaryController dictionary = new DictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveEcompDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - - return responseString; - - } - - public String saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - DictionaryController dictionary = new DictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveAttributeDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - - return responseString; - } - - public String saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - ActionPolicyDictionaryController action = new ActionPolicyDictionaryController(); - String responseString = null; - try { - ModelAndView result = action.saveActionPolicyDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - - return responseString; - } - - public String saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - BRMSDictionaryController dictionary = new BRMSDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveBRMSParamDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - - return responseString; - } - - public String saveVSCLAction(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveVSCLAction(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - - return responseString; - } - - public String saveVnfType(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveVnfType(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - - return responseString; - } - - public String savePEPOptions(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.savePEPOptions(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - - return responseString; - } - - public String saveVarbind(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveVarbind(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - - return responseString; - } - - public String saveServiceType(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveServiceType(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - - return responseString; - } - - public String saveSiteType(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveSiteType(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - } - - return responseString; - } - - public String saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveSettingsDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveDescriptiveDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveEnforcerDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - EnforcerDictionaryController dictionary = new EnforcerDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveEnforcerDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveActionListDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveProtocolListDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveZoneDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveSecurityZoneDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.savePrefixListDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveAddressGroupDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveServiceGroupDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveServiceListDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveTermListDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - - - - public String saveMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveMicroServiceLocationDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveMicroServiceConfigNameDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveDCAEUUIDDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveMicroServiceModelsDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveMicroServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveMicroServiceAttributeDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.savePSServiceDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.savePSResourceDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.savePSTypeDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String savePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.savePSClosedLoopDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - String responseString = null; - try { - ModelAndView result = dictionary.savePSGroupScopeDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - SafePolicyController dictionary = new SafePolicyController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveRiskTypeDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - public String saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - SafePolicyController dictionary = new SafePolicyController(); - String responseString = null; - try { - ModelAndView result = dictionary.saveSafePolicyWarningDictionary(request, response); - responseString = result.getViewName(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - return responseString; - } - - - /* - * Methods that call the controller get methods directly to get dictionary data - */ - public void getEcompDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - DictionaryController dictionary = new DictionaryController(); - try { - dictionary.getEcompNameDictionaryEntityData(request, response); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - DictionaryController dictionary = new DictionaryController(); - try { - dictionary.getAttributeDictionaryEntityData(request, response); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - ActionPolicyDictionaryController action = new ActionPolicyDictionaryController(); - try { - action.getActionPolicyDictionaryEntityData(request, response); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - BRMSDictionaryController dictionary = new BRMSDictionaryController(); - try { - dictionary.getBRMSParamDictionaryEntityData(request, response); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - } - - public void getVSCLAction(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - try { - dictionary.getVSCLActionDictionaryEntityData(request, response); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getVnfType(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - try { - dictionary.getVNFTypeDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - } - - public void getPEPOptions(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - try { - dictionary.getPEPOptionsDictionaryEntityData(request, response); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getVarbind(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - try { - dictionary.getVarbindDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - - } - - public void getServiceType(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - try { - dictionary.getClosedLoopServiceDictionaryEntityData(request, response); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getSiteType(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); - try { - dictionary.getClosedLoopSiteDictionaryEntityData(request, response); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); - try { - dictionary.getSettingsDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController(); - try { - dictionary.getDescriptiveDictionaryEntityData(request, response); - - } catch (Exception e) { - - } - } - - public void getEnforcerDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - EnforcerDictionaryController dictionary = new EnforcerDictionaryController(); - try { - dictionary.getEnforcerDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - try { - dictionary.getActionListDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - try { - dictionary.getProtocolListDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - try { - dictionary.getZoneDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - try { - dictionary.getSecurityZoneDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getPrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - try { - dictionary.getPrefixListDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - try { - dictionary.getAddressGroupDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - try { - dictionary.getServiceGroupDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - try { - dictionary.getServiceListDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - FirewallDictionaryController dictionary = new FirewallDictionaryController(); - try { - dictionary.getTermListDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - - public void getMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - try { - dictionary.getMicroServiceLocationDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - try { - dictionary.getMicroServiceConfigNameDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - try { - dictionary.getDCAEUUIDDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - try { - dictionary.getMicroServiceModelsDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getMicroServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); - try { - dictionary.getMicroServiceModelsDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getPSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - try { - dictionary.getPSServiceEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getPSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - try { - dictionary.getPSResourceEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getPSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - try { - dictionary.getPSTypeEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getPSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - try { - dictionary.getPSClosedLoopEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getPSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); - try { - dictionary.getGroupPolicyScopeEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - SafePolicyController dictionary = new SafePolicyController(); - try { - dictionary.getEcompNameDictionaryEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } - - public void getSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ - - SafePolicyController dictionary = new SafePolicyController(); - try { - dictionary.getSafePolicyWarningeEntityData(request, response); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - - } - } -} \ No newline at end of file diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/ImportService.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/ImportService.java deleted file mode 100644 index 0b3e313d6..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/ImportService.java +++ /dev/null @@ -1,157 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.service; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.pap.xacml.rest.components.CreateBRMSRuleTemplate; -import org.openecomp.policy.pap.xacml.rest.components.CreateNewMicroServiceModel; - -public class ImportService { - - public void doImportMicroServicePut(HttpServletRequest request, HttpServletResponse response) { - String importServiceCreation = request.getParameter("importService");; - String fileName = request.getParameter("fileName"); - String version = request.getParameter("version"); - String serviceName = request.getParameter("serviceName"); - String description = request.getParameter("description"); - Map successMap = new HashMap<>(); - switch(importServiceCreation){ - case "BRMSPARAM": - StringBuilder builder = new StringBuilder(); - int ch; - try { - while((ch = request.getInputStream().read()) != -1){ - builder.append((char)ch); - } - } catch (IOException e) { - PolicyLogger.error("Error in reading in file from API call"); - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "missing"); - response.addHeader("operation", "import"); - response.addHeader("service", serviceName); - } - CreateBRMSRuleTemplate brmsRuleTemplate = new CreateBRMSRuleTemplate(); - successMap = brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API"); - break; - case "MICROSERVICE": - CreateNewMicroServiceModel newMS = null; - String randomID = UUID.randomUUID().toString(); - if ( fileName != null) { - File extracDir = new File("ExtractDir"); - if (!extracDir.exists()){ - extracDir.mkdirs(); - } - if (fileName.contains(".xmi")){ - // get the request content into a String - String xmi = null; - java.util.Scanner scanner; - try { - scanner = new java.util.Scanner(request.getInputStream()); - scanner.useDelimiter("\\A"); - xmi = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - } catch (IOException e1) { - PolicyLogger.error("Error in reading in file from API call"); - return; - } - PolicyLogger.info("XML request from API for import new Service"); - try (Writer writer = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream("ExtractDir" + File.separator + randomID+".xmi"), "utf-8"))) { - writer.write(xmi); - } catch (IOException e) { - PolicyLogger.error("Error in reading in file from API call"); - return; - } - }else{ - InputStream inputStream = null; - try(FileOutputStream outputStream = new FileOutputStream("ExtractDir" + File.separator + randomID+".zip")) { - inputStream = request.getInputStream(); - byte[] buffer = new byte[4096]; - int bytesRead = -1 ; - while ((bytesRead = inputStream.read(buffer)) != -1) { - outputStream.write(buffer, 0, bytesRead) ; - } - } catch (IOException e) { - PolicyLogger.error("Error in reading in Zip File from API call"+e); - return; - }finally{ - try { - if(inputStream != null){ - inputStream.close(); - } - } catch (IOException e) { - PolicyLogger.error("Exception Occured while closing the input/output stream"+e); - } - } - } - newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, randomID); - successMap = newMS.addValuesToNewModel(); - if (successMap.containsKey("success")) { - successMap.clear(); - successMap = newMS.saveImportService(); - } - } - break; - } - // return a response to the PAP - if (successMap.containsKey("success")) { - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "import"); - response.addHeader("service", serviceName); - } else if (successMap.containsKey("DBError")) { - if (successMap.get("DBError").contains("EXISTS")){ - response.setStatus(HttpServletResponse.SC_CONFLICT); - response.addHeader("service", serviceName); - response.addHeader("error", "modelExistsDB"); - }else{ - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "importDB"); - } - response.addHeader("operation", "import"); - response.addHeader("service", serviceName); - }else if (successMap.get("error").contains("MISSING")){ - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "missing"); - response.addHeader("operation", "import"); - response.addHeader("service", serviceName); - }else if (successMap.get("error").contains("VALIDATION")){ - response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - response.addHeader("error", "validation"); - response.addHeader("operation", "import"); - response.addHeader("service", serviceName); - } - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/MetricService.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/MetricService.java deleted file mode 100644 index 97e53e8eb..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/service/MetricService.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.service; - -import java.util.HashSet; -import java.util.Set; - -import javax.persistence.EntityManager; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.json.JSONObject; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; - -import com.att.research.xacml.api.pap.PDPPolicy; - -public class MetricService { - - public static void doGetPolicyMetrics(HttpServletRequest request, HttpServletResponse response) { - Set groups = new HashSet<>(); - try { - //get the count of policies on the PDP - if(XACMLPapServlet.getPAPEngine()!=null){ - groups = XACMLPapServlet.getPAPEngine().getEcompPDPGroups(); - } - int pdpCount = 0; - for (EcompPDPGroup group : groups) { - Set policies = group.getPolicies(); - pdpCount += policies.size(); - } - //get the count of policies on the PAP - EntityManager em = null; - if(XACMLPapServlet.getEmf()!=null){ - em = (EntityManager) XACMLPapServlet.getEmf().createEntityManager(); - } - if (em==null){ - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + XACMLPapServlet.getPersistenceUnit()); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", "Error creating entity manager with persistence unit"); - return; - } - int papCount = ((Number) em.createNamedQuery("PolicyVersion.findAllCount").getSingleResult()).intValue(); - em.close(); - int totalCount = pdpCount + papCount; - //create json string for API response - JSONObject json = new JSONObject(); - json.put("papCount", papCount); - json.put("pdpCount", pdpCount); - json.put("totalCount", totalCount); - if (pdpCount>0 && papCount>0 && totalCount>0) { - PolicyLogger.info("Metrics have been found on the Policy Engine for the number of policies on the PAP and PDP."); - response.setStatus(HttpServletResponse.SC_OK); - response.addHeader("successMapKey", "success"); - response.addHeader("operation", "getMetrics"); - response.addHeader("metrics", json.toString() ); - return; - }else{ - String message = "The policy count on the PAP and PDP is 0. Please check the database and file system to correct this error."; - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); - return; - } - } catch (Exception e) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Querying the Database: " + e.getMessage(); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error Querying the Database."); - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - response.addHeader("error", message); - return; - } - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/AbstractPolicyCreation.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/AbstractPolicyCreation.java deleted file mode 100644 index 5fa681e85..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/AbstractPolicyCreation.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.util; - - -import java.util.UUID; - -import org.openecomp.policy.rest.XACMLRestProperties; -import org.springframework.stereotype.Component; - -import com.att.research.xacml.util.XACMLProperties; -import com.google.common.base.Joiner; - -@Component -public abstract class AbstractPolicyCreation { - - public static String getDomain() { - return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn"); - } - - public String newPolicyID() { - return Joiner.on(':').skipNulls().join((getDomain().startsWith("urn") ? null: "urn"), - getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); - } - - public 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]; - } else { - date = dateTTL.split("T"); - parts = date[0].split("-"); - formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; - } - return formateDate; - } - - - - public void updatePolicyCreationToDatabase(){ - // Add it into our tree -/* Path finalPolicyPath = null; - finalPolicyPath = Paths.get(successMap.get("success")); - PolicyElasticSearchController controller = new PolicyElasticSearchController(); - controller.updateElk(finalPolicyPath.toString()); - File file = finalPolicyPath.toFile(); - if(file != null){ - String policyName = file.toString(); - String removePath = policyName.substring(policyName.indexOf("repository")+11); - String removeXml = removePath.replace(".xml", ""); - String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); - List policyVersionList = commonClassDao.getDataById(PolicyVersion.class, "policyName", removeExtension); - if (policyVersionList.size() > 0) { - for(int i = 0; i < policyVersionList.size(); i++) { - PolicyVersion entityItem = (PolicyVersion) policyVersionList.get(i); - if(entityItem.getPolicyName().equals(removeExtension)){ - version = entityItem.getHigherVersion() +1; - entityItem.setActiveVersion(version); - entityItem.setHigherVersion(version); - entityItem.setModifiedBy(userId); - commonClassDao.update(entityItem); - if(policyData.isEditPolicy){ - PolicyNotificationMail email = new PolicyNotificationMail(); - String mode = "EditPolicy"; - String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; - email.sendMail(entityItem, policyNameForEmail, mode, commonClassDao); - } - } - } - }else{ - PolicyVersion entityItem = new PolicyVersion(); - entityItem.setActiveVersion(version); - entityItem.setHigherVersion(version); - entityItem.setPolicyName(removeExtension); - entityItem.setCreatedBy(userId); - entityItem.setModifiedBy(userId); - commonClassDao.save(entityItem); - } - }*/ - } - - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/JPAUtils.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/JPAUtils.java deleted file mode 100644 index 9a23beed3..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/JPAUtils.java +++ /dev/null @@ -1,239 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.util; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Query; -import javax.servlet.ServletException; - -import org.openecomp.policy.rest.XacmlAdminAuthorization; -import org.openecomp.policy.rest.jpa.Attribute; -import org.openecomp.policy.rest.jpa.Datatype; -import org.openecomp.policy.rest.jpa.FunctionDefinition; -import org.openecomp.policy.rest.jpa.GlobalRoleSettings; - -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 org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -public class JPAUtils { - private static Logger LOGGER = FlexLogger.getLogger(JPAUtils.class); - - private EntityManagerFactory emf; - private static final Object mapAccess = new Object(); - private static Map> mapDatatype2Function = null; - private static Map mapID2Function = null; - private static JPAUtils currentInstance = null; - - - /** - * Get an instance of a JPAUtils. It creates one if it does not exist. - * Only one instance is allowed to be created per server. - * @param emf The EntityFactoryManager to be used for database connections - * @return The new instance of JPAUtils or throw exception if the given emf is null. - * @throws IllegalStateException if a JPAUtils has already been constructed. Call getJPAUtilsInstance() to get this. - */ - public static JPAUtils getJPAUtilsInstance(EntityManagerFactory emf) throws Exception{ - LOGGER.debug("getJPAUtilsInstance(EntityManagerFactory emf) as getJPAUtilsInstance("+emf+") called"); - if(currentInstance == null){ - if(emf != null){ - currentInstance = new JPAUtils(emf); - return currentInstance; - } - throw new IllegalStateException("The EntityManagerFactory is Null"); - } - return currentInstance; - } - - private JPAUtils(EntityManagerFactory emf){ - LOGGER.debug("JPAUtils(EntityManagerFactory emf) as JPAUtils("+emf+") called"); - this.emf = emf; - } - - /** - * Gets the current instance of JPAUtils. - * @return The instance of JPAUtils or throws exception if the given instance is null. - * @throws IllegalStateException if a JPAUtils instance is null. Call getJPAUtilsInstance(EntityManagerFactory emf) to get this. - */ - public static JPAUtils getJPAUtilsInstance() throws Exception{ - LOGGER.debug("getJPAUtilsInstance() as getJPAUtilsInstance() called"); - if(currentInstance != null){ - return currentInstance; - } - throw new IllegalStateException("The JPAUtils.currentInstance is Null. Use getJPAUtilsInstance(EntityManagerFactory emf)"); - } - - public static AttributeDesignatorType createDesignator(Attribute attribute) { - AttributeDesignatorType designator = new AttributeDesignatorType(); - designator.setAttributeId(attribute.getXacmlId()); - if (attribute.getCategoryBean() != null) { - designator.setCategory(attribute.getCategoryBean().getXacmlId()); - } else { - LOGGER.warn("No category bean"); - } - if (attribute.getDatatypeBean() != null) { - designator.setDataType(attribute.getDatatypeBean().getXacmlId()); - } else { - LOGGER.warn("No datatype bean"); - } - designator.setIssuer(attribute.getIssuer()); - designator.setMustBePresent(attribute.isMustBePresent()); - return designator; - } - - public static AttributeSelectorType createSelector(Attribute attribute) { - AttributeSelectorType selector = new AttributeSelectorType(); - selector.setContextSelectorId(attribute.getXacmlId()); - selector.setPath(attribute.getSelectorPath()); - if (attribute.getCategoryBean() != null) { - selector.setCategory(attribute.getCategoryBean().getXacmlId()); - } else { - LOGGER.warn("No category bean"); - } - if (attribute.getDatatypeBean() != null) { - selector.setDataType(attribute.getDatatypeBean().getXacmlId()); - } else { - LOGGER.warn("No datatype bean"); - } - selector.setMustBePresent(attribute.isMustBePresent()); - return selector; - } - - /** - * Builds a map in memory of a functions return datatype to function definition. Useful in limiting the number - * of SQL calls to DB especially when we don't expect these to change much. - * - * @return - A HashMap of Datatype JPA Container ID's to FunctionDefinition objects - */ - public Map> getFunctionDatatypeMap() { - - synchronized(mapAccess) { - if (mapDatatype2Function == null||mapDatatype2Function.isEmpty()) { - try { - buildFunctionMaps(); - } catch (ServletException e) { - LOGGER.error("Exception Occured"+e); - } - } - } - return mapDatatype2Function; - } - - public Map getFunctionIDMap() { - synchronized(mapAccess) { - if (mapID2Function == null||mapID2Function.equals("{}")) { - try { - buildFunctionMaps(); - } catch (ServletException e) { - LOGGER.error("Exception Occured"+e); - } - } - } - return mapID2Function; - } - - private void buildFunctionMaps() throws ServletException { - mapDatatype2Function = new HashMap<>(); - mapID2Function = new HashMap<>(); - - EntityManager em = emf.createEntityManager(); - Query getFunctionDefinitions = em.createNamedQuery("FunctionDefinition.findAll"); - List functionList = getFunctionDefinitions.getResultList(); - - for (Object id : functionList) { - FunctionDefinition value = (FunctionDefinition)id; - mapID2Function.put(value.getXacmlid(), value); - if (mapDatatype2Function.containsKey(value.getDatatypeBean()) == false) { - mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList()); - } - mapDatatype2Function.get(value.getDatatypeBean()).add(value); - } - - em.close(); - - } - - /** - * Returns the lockdown value, in case of exception it is assumed that lockdown functionality - * is not supported and returns false. - * - * - * @throws ReadOnlyException - * @throws ConversionException - */ - public boolean dbLockdownIgnoreErrors() { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("ENTER"); - - boolean lockdown = false; - try { - lockdown = dbLockdown(); - } catch (Exception e) { - LOGGER.warn("Cannot access DB lockdown value", e); - } - return lockdown; - } - - /** - * Returns the lockdown value from the database. - * - * @throws ReadOnlyException - * @throws ConversionException - */ - public boolean dbLockdown() - throws IllegalAccessException { - if (LOGGER.isTraceEnabled()) - LOGGER.trace("ENTER"); - - EntityManager em = emf.createEntityManager(); - Query globalRoleSettingsJPA = em.createNamedQuery("GlobalRoleSettings.findAll"); - - GlobalRoleSettings globalRoleSettings = (GlobalRoleSettings) globalRoleSettingsJPA.getSingleResult(); - - if (globalRoleSettings == null) { - // this should not happen - String msg = "NO GlobalSetttings for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString(); - if (LOGGER.isErrorEnabled()) - LOGGER.error(msg); - throw new IllegalAccessException(msg); - } - - if (!globalRoleSettings.getRole().equals(XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString())) { - String msg = "NOT FOUND db data for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString(); - if (LOGGER.isErrorEnabled()) - LOGGER.error(msg); - throw new IllegalAccessException(msg); - } - - return globalRoleSettings.isLockdown(); - } - - - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/JsonMessage.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/JsonMessage.java deleted file mode 100644 index 3e9351044..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/JsonMessage.java +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.util; - -public class JsonMessage { - - private String data; - private String data2; - private String data3; - public JsonMessage(String data) { - super(); - this.data = data; - } - public JsonMessage(String data,String data2) { - super(); - this.data = data; - this.data2 = data2; - } - - public JsonMessage(String data,String data2,String data3) { - super(); - this.data = data; - this.data2 = data2; - this.data3 = data3; - } - - public String getData() { - return data; - } - - public void setData(String data) { - this.data = data; - } - public String getData2() { - return data2; - } - public void setData2(String data2) { - this.data2 = data2; - } - public String getData3() { - return data3; - } - public void setData3(String data3) { - this.data3 = data3; - } - - -} - diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/PolicyContainer.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/PolicyContainer.java deleted file mode 100644 index 3741dbda9..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/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.pap.xacml.rest.util; - -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/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/PolicyItemSetChangeNotifier.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/PolicyItemSetChangeNotifier.java deleted file mode 100644 index da9278435..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/rest/util/PolicyItemSetChangeNotifier.java +++ /dev/null @@ -1,96 +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.pap.xacml.rest.util; - - -import java.io.Serializable; -import java.util.Collection; -import java.util.EventObject; -import java.util.LinkedList; - -import org.openecomp.policy.pap.xacml.rest.util.PolicyContainer.ItemSetChangeEvent; -import org.openecomp.policy.pap.xacml.rest.util.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/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/restAuth/AuthenticationService.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/restAuth/AuthenticationService.java deleted file mode 100644 index 78e652836..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/restAuth/AuthenticationService.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.restAuth; - -import java.util.Base64; -import java.util.StringTokenizer; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.rest.XACMLRestProperties; - -import com.att.research.xacml.util.XACMLProperties; - -public class AuthenticationService { - private String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); - private String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); - - public boolean authenticate(String authCredentials) { - - if (null == authCredentials) - return false; - // header value format will be "Basic encodedstring" for Basic authentication. - final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", ""); - String usernameAndPassword = null; - try { - byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword); - usernameAndPassword = new String(decodedBytes, "UTF-8"); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService", "Exception decoding username and password"); - return false; - } - try { - final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); - final String username = tokenizer.nextToken(); - final String password = tokenizer.nextToken(); - - boolean authenticationStatus = papID.equals(username) && papPass.equals(password); - return authenticationStatus; - } catch (Exception e){ - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService", "Exception authenticating user"); - return false; - } - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/restAuth/CheckPDP.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/restAuth/CheckPDP.java deleted file mode 100644 index c1a1907c0..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/restAuth/CheckPDP.java +++ /dev/null @@ -1,181 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.restAuth; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -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.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.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; - -public class CheckPDP { - - private static Path pdpPath = null; - private static Properties pdpProp = null; - private static Long oldModified = null; - private static Long newModified = null; - private static HashMap pdpMap = null; - private static final Logger logger = FlexLogger.getLogger(CheckPDP.class); - - public static boolean validateID(String id) { - // ReadFile - try { - readFile(); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception reading file"); - return false; - } - // Check ID - if (pdpMap.containsKey(id)) { - return true; - } - return false; - } - - private static void readFile() throws Exception { - String pdpFile = XACMLPapServlet.getPDPFile(); - if (pdpFile == null) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "PDP File name is undefined"); - throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"PDP File name not Valid : " + pdpFile); - } - if (pdpPath == null) { - pdpPath = Paths.get(pdpFile); - if (Files.notExists(pdpPath)) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path"); - throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"File doesn't exist in the specified Path : "+ pdpPath.toString()); - } - if (pdpPath.toString().endsWith(".properties")) { - readProps(); - } else { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "Not a .properties file"); - throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Not a .properties file"); - } - } - // Check if File is updated recently - else { - newModified = pdpPath.toFile().lastModified(); - if (newModified != oldModified) { - // File has been updated. - readProps(); - } - } - } - - @SuppressWarnings({ "rawtypes", "unchecked" }) - private static void readProps() throws Exception { - InputStream in; - pdpProp = new Properties(); - try { - in = new FileInputStream(pdpPath.toFile()); - oldModified = pdpPath.toFile().lastModified(); - pdpProp.load(in); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Cannot load the Properties file"); - throw new Exception("Cannot Load the Properties file", e); - } - // 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) { - if (propKey.startsWith("PDP_URL")) { - String check_val = pdpProp.getProperty(propKey); - if (check_val == null) { - throw new Exception("Properties file doesn't have the PDP_URL parameter"); - } - if (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++; - } - } else { - readPDPParam(check_val); - } - } - } - if (pdpMap == null || pdpMap.isEmpty()) { - logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs"); - throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Proceed without PDP_URLs"); - } - } - - private static void readPDPParam(String pdpVal) throws Exception{ - 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{ - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request"); - throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request. " + pdpValues); - } - }else{ - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal); - throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS +"No enough Credentials to send Request."); - } - } - - public static String getEncoding(String pdpID){ - try { - readFile(); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exeption reading Properties file"); - } - String encoding = null; - if(pdpMap!=null && (!pdpMap.isEmpty())){ - try{ - encoding = pdpMap.get(pdpID); - } catch(Exception e){ - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception encoding"); - } - return encoding; - }else{ - return null; - } - } - -} diff --git a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java b/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java deleted file mode 100644 index 2352beb4d..000000000 --- a/ECOMP-PAP-REST/src/main/java/org/openecomp/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java +++ /dev/null @@ -1,130 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.restAuth; - -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.annotation.WebFilter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Servlet Filter implementation class PAPAuthenticationFilter - */ -@WebFilter("/*") -public class PAPAuthenticationFilter implements Filter { - - private static final Log logger = LogFactory.getLog(PAPAuthenticationFilter.class); - public static final String AUTHENTICATION_HEADER = "Authorization"; - - @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain filter) throws IOException, ServletException { - - - if (request instanceof HttpServletRequest) { - HttpServletRequest httpServletRequest = (HttpServletRequest) request; - - String authCredentials = null; - String url = httpServletRequest.getRequestURI(); - - logger.info("Request URI: " + url); - System.out.println("Request URI: " + url); - - //getting authentication credentials - if(url.contains("@Auth@")){ - int authIndex = url.lastIndexOf("@"); - int endAuthIndex = url.indexOf("/ecomp"); - authCredentials = "Basic " + url.substring(authIndex+1, endAuthIndex); - - //parse the url for /pap/ecomp/ - String url1 = url.substring(0, 4); - String url2 = url.substring(endAuthIndex, url.length()); - url = url1 + url2; - - } else { - authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER); - } - - // Check Authentication credentials - AuthenticationService authenticationService = new AuthenticationService(); - boolean authenticationStatus = authenticationService.authenticate(authCredentials); - - if (authenticationStatus) { - //indicates the request comes from Traditional Admin Console or PolicyEngineAPI - if (url.equals("/pap/")){ - logger.info("Request comes from Traditional Admin Console or PolicyEngineAPI"); - - //forward request to the XACMLPAPServlet if authenticated - request.getRequestDispatcher("/pap/pap/").forward(request, response); - - }else if (url.startsWith("/pap/ecomp/")){ - - //indicates the request comes from the ECOMP Portal ecomp-sdk-app - if(response instanceof HttpServletResponse) { - HttpServletResponse alteredResponse = ((HttpServletResponse)response); - addCorsHeader(alteredResponse); - logger.info("Request comes from Ecomp Portal"); - //Spring dispatcher servlet is at the end of the filter chain at /pap/ecomp/ path - System.out.println("New Request URI: " + url); - filter.doFilter(request, response); - /*url = url.substring(url.indexOf("/pap/")+4); - request.getRequestDispatcher(url).forward(request, response);*/ - } - - } - - } else { - if (response instanceof HttpServletResponse) { - HttpServletResponse httpServletResponse = (HttpServletResponse) response; - httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } - } - - } - } - - //method to add CorsHeaders for ecomp portal rest call - private void addCorsHeader(HttpServletResponse response) { - logger.info("Adding Cors Response Headers!!!"); - response.addHeader("Access-Control-Allow-Origin", "*"); - response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD"); - response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept"); - response.addHeader("Access-Control-Max-Age", "1728000"); - } - - @Override - public void destroy() { - } - - @Override - public void init(FilterConfig arg0) throws ServletException { - } -} diff --git a/ECOMP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml b/ECOMP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml deleted file mode 100644 index 7e4201a58..000000000 --- a/ECOMP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml +++ /dev/null @@ -1,111 +0,0 @@ - - - ${description} - - - - - ${PolicyName} - - - - - - ${ECOMPName} - - - - ${actor} - - - - ${recipe} - - - - ${clname} - - - - - - - - - - - DECIDE - - - - - - - - - - - - - ${guardActiveStart} - ${guardActiveEnd} - - - - - - - - - ${blackListElement} - - - - - - - - - - - - DECIDE - - - - - - - - - - - - - - ${guardActiveStart} - ${guardActiveEnd} - - - - - - - - - ${blackListElement} - - - - - - - - - - Denied! - - - - - \ No newline at end of file diff --git a/ECOMP-PAP-REST/src/main/resources/Decision_GuardPolicyTemplate.xml b/ECOMP-PAP-REST/src/main/resources/Decision_GuardPolicyTemplate.xml deleted file mode 100644 index d404080e0..000000000 --- a/ECOMP-PAP-REST/src/main/resources/Decision_GuardPolicyTemplate.xml +++ /dev/null @@ -1,107 +0,0 @@ - - - ${description} - - - - - ${PolicyName} - - - - - - ${ECOMPName} - - - - ${actor} - - - - ${recipe} - - - - ${targets} - - - - ${clname} - - - - - - - - - - - DECIDE - - - - - - - - - - - - - ${guardActiveStart} - ${guardActiveEnd} - - - - - - ${limit} - - - - - - - - - - - DECIDE - - - - - - - - - - - - - - ${guardActiveStart} - ${guardActiveEnd} - - - - - - ${limit} - - - - - - - - - Denied! - - - - - \ No newline at end of file diff --git a/ECOMP-PAP-REST/src/main/resources/META-INF/generatedCreate.ddl b/ECOMP-PAP-REST/src/main/resources/META-INF/generatedCreate.ddl deleted file mode 100644 index 73ce58f3c..000000000 --- a/ECOMP-PAP-REST/src/main/resources/META-INF/generatedCreate.ddl +++ /dev/null @@ -1,119 +0,0 @@ -CREATE TABLE PolicyEntity (policyId BIGINT NOT NULL, created_by VARCHAR(255) NOT NULL, created_date TIMESTAMP, deleted BOOLEAN NOT NULL, description VARCHAR(2048) NOT NULL, modified_by VARCHAR(255) NOT NULL, modified_date TIMESTAMP NOT NULL, policyData TEXT, policyName VARCHAR(255) NOT NULL, policyVersion INTEGER, scope VARCHAR(255) NOT NULL, version INTEGER, actionBodyId BIGINT, configurationDataId BIGINT, PRIMARY KEY (policyId)) -CREATE TABLE ConfigurationDataEntity (configurationDataId BIGINT NOT NULL, configBody TEXT, configType VARCHAR(255) NOT NULL, configurationName VARCHAR(255) NOT NULL, created_by VARCHAR(255) NOT NULL, created_date TIMESTAMP, deleted BOOLEAN NOT NULL, description VARCHAR(2048) NOT NULL, modified_by VARCHAR(255) NOT NULL, modified_date TIMESTAMP NOT NULL, version INTEGER, PRIMARY KEY (configurationDataId)) -CREATE TABLE PolicyDBDaoEntity (policyDBDaoUrl VARCHAR NOT NULL, created_date TIMESTAMP, description VARCHAR(2048) NOT NULL, modified_date TIMESTAMP NOT NULL, password LONGVARCHAR, username VARCHAR, PRIMARY KEY (policyDBDaoUrl)) -CREATE TABLE GroupEntity (groupKey BIGINT NOT NULL, created_by VARCHAR(255) NOT NULL, created_date TIMESTAMP, defaultGroup BOOLEAN NOT NULL, deleted BOOLEAN NOT NULL, description VARCHAR(2048) NOT NULL, groupId VARCHAR NOT NULL, groupName VARCHAR(255) NOT NULL, modified_by VARCHAR(255) NOT NULL, modified_date TIMESTAMP NOT NULL, version INTEGER, PRIMARY KEY (groupKey)) -CREATE TABLE PdpEntity (pdpKey BIGINT NOT NULL, created_by VARCHAR(255) NOT NULL, created_date TIMESTAMP, deleted BOOLEAN NOT NULL, description VARCHAR(2048) NOT NULL, jmxPort INTEGER NOT NULL, modified_by VARCHAR(255) NOT NULL, modified_date TIMESTAMP NOT NULL, pdpId VARCHAR(255) NOT NULL, pdpName VARCHAR(255) NOT NULL, groupKey BIGINT, PRIMARY KEY (pdpKey)) -CREATE TABLE ActionBodyEntity (actionBodyId BIGINT NOT NULL, actionBody TEXT, actionBodyName VARCHAR(255) NOT NULL, created_by VARCHAR(255) NOT NULL, created_date TIMESTAMP, deleted BOOLEAN NOT NULL, modified_by VARCHAR(255) NOT NULL, modified_date TIMESTAMP NOT NULL, version INTEGER, PRIMARY KEY (actionBodyId)) -CREATE TABLE DatabaseLockEntity (lock_key INTEGER NOT NULL, PRIMARY KEY (lock_key)) -CREATE TABLE PolicyVersion (id INTEGER NOT NULL, ACTIVE_VERSION INTEGER, CREATED_BY VARCHAR(45) NOT NULL, created_date TIMESTAMP NOT NULL, HIGHEST_VERSION INTEGER, modified_by VARCHAR(45) NOT NULL, modified_date TIMESTAMP NOT NULL, POLICY_NAME VARCHAR(255) NOT NULL, PRIMARY KEY (id)) -CREATE TABLE POLICYSCORE (id INTEGER NOT NULL, POLICY_NAME VARCHAR NOT NULL, POLICY_SCORE VARCHAR, VERSIONEXTENSION VARCHAR NOT NULL, PRIMARY KEY (id)) -CREATE TABLE FunctionDefinition (id INTEGER NOT NULL, arg_lb INTEGER NOT NULL, arg_ub INTEGER NOT NULL, ho_arg_lb INTEGER, ho_arg_ub INTEGER, ho_primitive CHAR, is_bag_return INTEGER NOT NULL, is_higher_order INTEGER NOT NULL, short_name VARCHAR(64) NOT NULL, xacml_id VARCHAR(255) NOT NULL, return_datatype INTEGER, PRIMARY KEY (id)) -CREATE TABLE Attribute (id INTEGER NOT NULL, ATTRIBUTE_VALUE VARCHAR, created_date TIMESTAMP, description VARCHAR(2048), is_designator CHAR NOT NULL, modified_date TIMESTAMP NOT NULL, PRIORITY VARCHAR, selector_path VARCHAR(2048), xacml_id VARCHAR NOT NULL UNIQUE, category INTEGER, constraint_type INTEGER, datatype INTEGER, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) -CREATE TABLE Category (id INTEGER NOT NULL, grouping VARCHAR(64) NOT NULL, is_standard CHAR NOT NULL, short_name VARCHAR(64) NOT NULL, xacml_id VARCHAR(255) NOT NULL UNIQUE, PRIMARY KEY (id)) -CREATE TABLE ConstraintType (id INTEGER NOT NULL, constraint_type VARCHAR(64) NOT NULL, description VARCHAR(255) NOT NULL, PRIMARY KEY (id)) -CREATE TABLE ConstraintValues (id INTEGER NOT NULL, property VARCHAR, value VARCHAR, attribute_id INTEGER, PRIMARY KEY (id)) -CREATE TABLE Datatype (id INTEGER NOT NULL, is_standard CHAR NOT NULL, short_name VARCHAR(64) NOT NULL, xacml_id VARCHAR(255) NOT NULL UNIQUE, PRIMARY KEY (id)) -CREATE TABLE FunctionArguments (id INTEGER NOT NULL, arg_index INTEGER NOT NULL, is_bag INTEGER NOT NULL, datatype_id INTEGER, function_id INTEGER, PRIMARY KEY (id)) -CREATE TABLE UserInfo (loginid VARCHAR(45) NOT NULL, name VARCHAR NOT NULL UNIQUE, PRIMARY KEY (loginid)) -CREATE TABLE ActionPolicyDict (id INTEGER NOT NULL, ATTRIBUTE_NAME VARCHAR NOT NULL, Body VARCHAR, created_date TIMESTAMP, description VARCHAR(2048), Headers VARCHAR, Method VARCHAR NOT NULL, modified_date TIMESTAMP NOT NULL, Type VARCHAR NOT NULL, URL VARCHAR NOT NULL, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) -CREATE TABLE DecisionSettings (id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), modified_date TIMESTAMP NOT NULL, PRIORITY VARCHAR, xacml_id VARCHAR NOT NULL UNIQUE, datatype INTEGER, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) -CREATE TABLE MicroServiceModels (id INTEGER NOT NULL, annotation VARCHAR(2000) NOT NULL, attributes VARCHAR(255) NOT NULL, dependency VARCHAR(2048), description VARCHAR(2048), enumValues VARCHAR(2000) NOT NULL, modelName VARCHAR NOT NULL UNIQUE, ref_attributes VARCHAR(255) NOT NULL, sub_attributes VARCHAR(2000) NOT NULL, version VARCHAR(2000) NOT NULL, imported_by VARCHAR(45), PRIMARY KEY (id)) -CREATE TABLE actionlist (id INTEGER NOT NULL, actionname VARCHAR NOT NULL, description VARCHAR, PRIMARY KEY (id)) -CREATE TABLE AddressGroup (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, prefixlist VARCHAR, PRIMARY KEY (id)) -CREATE TABLE AttributeAssignment (id INTEGER NOT NULL, attribute_id INTEGER, expression VARCHAR NOT NULL, OBADVICE_id INTEGER, PRIMARY KEY (id)) -CREATE TABLE BRMSParamTemplate (id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), rule LONGVARCHAR NOT NULL, param_template_name VARCHAR NOT NULL UNIQUE, created_by VARCHAR(45), PRIMARY KEY (id)) -CREATE TABLE ClosedLoopD2Services (id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), modified_date TIMESTAMP NOT NULL, service_Name VARCHAR NOT NULL UNIQUE, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) -CREATE TABLE ClosedLoopSite (id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), modified_date TIMESTAMP NOT NULL, site_Name VARCHAR NOT NULL UNIQUE, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) -CREATE TABLE DCAEUsers (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) -CREATE TABLE DCAEuuid (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) -CREATE TABLE DescriptiveScope (Id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), scopename VARCHAR NOT NULL, modified_date TIMESTAMP NOT NULL, search VARCHAR, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (Id)) -CREATE TABLE EcompName (id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), ecomp_Name VARCHAR NOT NULL UNIQUE, modified_date TIMESTAMP NOT NULL, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) -CREATE TABLE EnforcingType (id INTEGER NOT NULL, connectionQuery VARCHAR(255) NOT NULL, enforcingType VARCHAR NOT NULL UNIQUE, script VARCHAR(255) NOT NULL, valueQuery VARCHAR(255) NOT NULL, PRIMARY KEY (id)) -CREATE TABLE GlobalRoleSettings (role VARCHAR(45) NOT NULL, lockdown BOOLEAN, PRIMARY KEY (role)) -CREATE TABLE GroupPolicyScopeList (id INTEGER NOT NULL, description VARCHAR, groupList VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) -CREATE TABLE GroupServiceList (id INTEGER NOT NULL, name VARCHAR NOT NULL, serviceList VARCHAR, PRIMARY KEY (id)) -CREATE TABLE MicroServiceConfigName (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) -CREATE TABLE MicroServiceLocation (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) -CREATE TABLE Obadvice (id INTEGER NOT NULL, created_by VARCHAR(255) NOT NULL, created_date TIMESTAMP NOT NULL, description VARCHAR(2048), fulfill_on VARCHAR(32), modified_by VARCHAR(255) NOT NULL, modified_date TIMESTAMP NOT NULL, type VARCHAR NOT NULL, xacml_id VARCHAR(255) NOT NULL, PRIMARY KEY (id)) -CREATE TABLE ObadviceExpressions (id INTEGER NOT NULL, type VARCHAR NOT NULL, obadvice_id INTEGER, attribute_id INTEGER, PRIMARY KEY (id)) -CREATE TABLE PEPOptions (Id INTEGER NOT NULL, Actions VARCHAR, created_date TIMESTAMP, description VARCHAR(2048), modified_date TIMESTAMP NOT NULL, PEP_NAME VARCHAR NOT NULL, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (Id)) -CREATE TABLE PIPConfigParams (id INTEGER NOT NULL, PARAM_DEFAULT VARCHAR(2048), PARAM_NAME VARCHAR(1024) NOT NULL, PARAM_VALUE VARCHAR(2048) NOT NULL, REQUIRED CHAR NOT NULL, PIP_ID INTEGER, PRIMARY KEY (id)) -CREATE TABLE PIPConfiguration (id INTEGER NOT NULL, CLASSNAME VARCHAR(2048) NOT NULL, CREATED_BY VARCHAR(255) NOT NULL, CREATED_DATE TIMESTAMP NOT NULL, DESCRIPTION VARCHAR(2048), ISSUER VARCHAR(1024), MODIFIED_BY VARCHAR(255) NOT NULL, MODIFIED_DATE TIMESTAMP NOT NULL, NAME VARCHAR(255) NOT NULL, READ_ONLY CHAR NOT NULL, REQUIRES_RESOLVER CHAR NOT NULL, TYPE INTEGER, PRIMARY KEY (id)) -CREATE TABLE PIPResolver (id INTEGER NOT NULL, CLASSNAME VARCHAR(2048) NOT NULL, CREATED_BY VARCHAR(255) NOT NULL, CREATED_DATE TIMESTAMP NOT NULL, DESCRIPTION VARCHAR(2048), ISSUER VARCHAR(1024), MODIFIED_BY VARCHAR(255) NOT NULL, MODIFIED_DATE TIMESTAMP NOT NULL, NAME VARCHAR(255) NOT NULL, READ_ONLY CHAR NOT NULL, PIP_ID INTEGER, PRIMARY KEY (id)) -CREATE TABLE PIPResolverParams (id INTEGER NOT NULL, PARAM_DEFAULT VARCHAR(2048), PARAM_NAME VARCHAR(1024) NOT NULL, PARAM_VALUE VARCHAR(2048) NOT NULL, REQUIRED CHAR NOT NULL, ID_RESOLVER INTEGER, PRIMARY KEY (id)) -CREATE TABLE PIPType (id INTEGER NOT NULL, type VARCHAR(45) NOT NULL, PRIMARY KEY (id)) -CREATE TABLE PolicyAlgorithms (id INTEGER NOT NULL, is_standard CHAR NOT NULL, short_name VARCHAR(64) NOT NULL, xacml_id VARCHAR(255) NOT NULL UNIQUE, PRIMARY KEY (id)) -CREATE TABLE policy_manangement (id INTEGER NOT NULL, CONFIG_NAME VARCHAR(45) NOT NULL, CREATE_DATE_TIME TIMESTAMP NOT NULL, CREATED_BY VARCHAR(45) NOT NULL, ECOMP_NAME VARCHAR(45) NOT NULL, POLICY_NAME VARCHAR(45) NOT NULL, scope VARCHAR(45) NOT NULL, UPDATE_DATE_TIME TIMESTAMP NOT NULL, UPDATED_BY VARCHAR(45) NOT NULL, XML CLOB NOT NULL, PRIMARY KEY (id)) -CREATE TABLE PolicyScopeService (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) -CREATE TABLE PolicyScopeType (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) -CREATE TABLE PolicyScopeResource (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) -CREATE TABLE PolicyScopeClosedLoop (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) -CREATE TABLE portlist (id INTEGER NOT NULL, description VARCHAR, portname VARCHAR NOT NULL, PRIMARY KEY (id)) -CREATE TABLE protocollist (id INTEGER NOT NULL, description VARCHAR, protocolname VARCHAR NOT NULL, PRIMARY KEY (id)) -CREATE TABLE RemoteCatalogValues (id INTEGER NOT NULL, name VARCHAR NOT NULL, value VARCHAR, PRIMARY KEY (id)) -CREATE TABLE roles (id INTEGER NOT NULL, role VARCHAR(45) NOT NULL, scope VARCHAR(45), loginid VARCHAR(45), PRIMARY KEY (id)) -CREATE TABLE RuleAlgorithms (id INTEGER NOT NULL, is_standard CHAR NOT NULL, short_name VARCHAR(64) NOT NULL, xacml_id VARCHAR(255) NOT NULL UNIQUE, PRIMARY KEY (id)) -CREATE TABLE securityzone (id INTEGER NOT NULL, name VARCHAR NOT NULL, value VARCHAR, PRIMARY KEY (id)) -CREATE TABLE servicegroup (id INTEGER NOT NULL, appprotocol VARCHAR, description VARCHAR, name VARCHAR NOT NULL, ports VARCHAR, transportprotocol VARCHAR, type VARCHAR, PRIMARY KEY (id)) -CREATE TABLE SystemLogDB (id INTEGER NOT NULL, date TIMESTAMP NOT NULL, description VARCHAR(2048), logtype VARCHAR(255) NOT NULL, remote VARCHAR(255) NOT NULL, system VARCHAR(255) NOT NULL, type VARCHAR NOT NULL, PRIMARY KEY (id)) -CREATE TABLE TERM (id INTEGER NOT NULL, action VARCHAR, created_date TIMESTAMP, destIPList VARCHAR, destPortList VARCHAR, fromzone VARCHAR, modified_date TIMESTAMP NOT NULL, portList VARCHAR, protocolList VARCHAR, srcIPList VARCHAR, srcPortList VARCHAR, description VARCHAR, termName VARCHAR NOT NULL, tozone VARCHAR, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) -CREATE TABLE VarbindDictionary (Id INTEGER NOT NULL, created_date TIMESTAMP, modified_date TIMESTAMP NOT NULL, varbind_Description VARCHAR(2048), varbind_Name VARCHAR NOT NULL UNIQUE, varbind_oid VARCHAR NOT NULL, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (Id)) -CREATE TABLE VMType (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) -CREATE TABLE VNFType (id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), modified_date TIMESTAMP NOT NULL, vnf_type VARCHAR NOT NULL UNIQUE, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) -CREATE TABLE VSCLAction (id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), modified_date TIMESTAMP NOT NULL, vscl_action VARCHAR NOT NULL UNIQUE, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) -CREATE TABLE zone (id INTEGER NOT NULL, zonename VARCHAR NOT NULL, zonevalue VARCHAR, PRIMARY KEY (id)) -CREATE TABLE BackUpMonitorEntity (id INTEGER NOT NULL, flag VARCHAR NOT NULL, notification_record LONGVARCHAR, resource_name VARCHAR NOT NULL UNIQUE, node_name VARCHAR NOT NULL, last_seen TIMESTAMP, PRIMARY KEY (id)) -CREATE TABLE StateManagementEntity (id BIGINT NOT NULL, adminState VARCHAR(20) NOT NULL, availStatus VARCHAR(20) NOT NULL, created_Date TIMESTAMP, modifiedDate TIMESTAMP NOT NULL, opState VARCHAR(20) NOT NULL, resourceName VARCHAR(100) NOT NULL UNIQUE, standbyStatus VARCHAR(20) NOT NULL, PRIMARY KEY (id)) -CREATE TABLE ForwardProgressEntity (forwardProgressId BIGINT NOT NULL, created_date TIMESTAMP, fpc_count BIGINT NOT NULL, last_updated TIMESTAMP, resourceName VARCHAR(100) NOT NULL UNIQUE, PRIMARY KEY (forwardProgressId)) -CREATE TABLE ResourceRegistrationEntity (ResourceRegistrationId BIGINT NOT NULL, created_date TIMESTAMP, last_updated TIMESTAMP, nodeType VARCHAR(50), resourceName VARCHAR(100) NOT NULL UNIQUE, resourceUrl VARCHAR(255) NOT NULL UNIQUE, site VARCHAR(50), PRIMARY KEY (ResourceRegistrationId)) -CREATE TABLE IntegrityAuditEntity (id BIGINT NOT NULL, createdDate TIMESTAMP, designated BOOLEAN, jdbcDriver VARCHAR NOT NULL, jdbcPassword VARCHAR NOT NULL, jdbcUrl VARCHAR NOT NULL, jdbcUser VARCHAR NOT NULL, lastUpdated TIMESTAMP, nodeType VARCHAR, persistenceUnit VARCHAR NOT NULL, resourceName VARCHAR NOT NULL UNIQUE, site VARCHAR, PRIMARY KEY (id)) -CREATE TABLE PolicyGroupEntity (groupKey BIGINT NOT NULL, policyId BIGINT NOT NULL, PRIMARY KEY (groupKey, policyId)) -ALTER TABLE PolicyEntity ADD CONSTRAINT FK_PolicyEntity_configurationDataId FOREIGN KEY (configurationDataId) REFERENCES ConfigurationDataEntity (configurationDataId) -ALTER TABLE PolicyEntity ADD CONSTRAINT FK_PolicyEntity_actionBodyId FOREIGN KEY (actionBodyId) REFERENCES ActionBodyEntity (actionBodyId) -ALTER TABLE PdpEntity ADD CONSTRAINT FK_PdpEntity_groupKey FOREIGN KEY (groupKey) REFERENCES GroupEntity (groupKey) -ALTER TABLE FunctionDefinition ADD CONSTRAINT FK_FunctionDefinition_return_datatype FOREIGN KEY (return_datatype) REFERENCES Datatype (id) -ALTER TABLE Attribute ADD CONSTRAINT FK_Attribute_category FOREIGN KEY (category) REFERENCES Category (id) -ALTER TABLE Attribute ADD CONSTRAINT FK_Attribute_constraint_type FOREIGN KEY (constraint_type) REFERENCES ConstraintType (id) -ALTER TABLE Attribute ADD CONSTRAINT FK_Attribute_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) -ALTER TABLE Attribute ADD CONSTRAINT FK_Attribute_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) -ALTER TABLE Attribute ADD CONSTRAINT FK_Attribute_datatype FOREIGN KEY (datatype) REFERENCES Datatype (id) -ALTER TABLE ConstraintValues ADD CONSTRAINT FK_ConstraintValues_attribute_id FOREIGN KEY (attribute_id) REFERENCES Attribute (id) -ALTER TABLE FunctionArguments ADD CONSTRAINT FK_FunctionArguments_function_id FOREIGN KEY (function_id) REFERENCES FunctionDefinition (id) -ALTER TABLE FunctionArguments ADD CONSTRAINT FK_FunctionArguments_datatype_id FOREIGN KEY (datatype_id) REFERENCES Datatype (id) -ALTER TABLE ActionPolicyDict ADD CONSTRAINT FK_ActionPolicyDict_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) -ALTER TABLE ActionPolicyDict ADD CONSTRAINT FK_ActionPolicyDict_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) -ALTER TABLE DecisionSettings ADD CONSTRAINT FK_DecisionSettings_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) -ALTER TABLE DecisionSettings ADD CONSTRAINT FK_DecisionSettings_datatype FOREIGN KEY (datatype) REFERENCES Datatype (id) -ALTER TABLE DecisionSettings ADD CONSTRAINT FK_DecisionSettings_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) -ALTER TABLE MicroServiceModels ADD CONSTRAINT FK_MicroServiceModels_imported_by FOREIGN KEY (imported_by) REFERENCES UserInfo (loginid) -ALTER TABLE AttributeAssignment ADD CONSTRAINT FK_AttributeAssignment_OBADVICE_id FOREIGN KEY (OBADVICE_id) REFERENCES Obadvice (id) -ALTER TABLE BRMSParamTemplate ADD CONSTRAINT FK_BRMSParamTemplate_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) -ALTER TABLE ClosedLoopD2Services ADD CONSTRAINT FK_ClosedLoopD2Services_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) -ALTER TABLE ClosedLoopD2Services ADD CONSTRAINT FK_ClosedLoopD2Services_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) -ALTER TABLE ClosedLoopSite ADD CONSTRAINT FK_ClosedLoopSite_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) -ALTER TABLE ClosedLoopSite ADD CONSTRAINT FK_ClosedLoopSite_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) -ALTER TABLE DescriptiveScope ADD CONSTRAINT FK_DescriptiveScope_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) -ALTER TABLE DescriptiveScope ADD CONSTRAINT FK_DescriptiveScope_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) -ALTER TABLE EcompName ADD CONSTRAINT FK_EcompName_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) -ALTER TABLE EcompName ADD CONSTRAINT FK_EcompName_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) -ALTER TABLE ObadviceExpressions ADD CONSTRAINT FK_ObadviceExpressions_obadvice_id FOREIGN KEY (obadvice_id) REFERENCES Obadvice (id) -ALTER TABLE ObadviceExpressions ADD CONSTRAINT FK_ObadviceExpressions_attribute_id FOREIGN KEY (attribute_id) REFERENCES Attribute (id) -ALTER TABLE PEPOptions ADD CONSTRAINT FK_PEPOptions_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) -ALTER TABLE PEPOptions ADD CONSTRAINT FK_PEPOptions_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) -ALTER TABLE PIPConfigParams ADD CONSTRAINT FK_PIPConfigParams_PIP_ID FOREIGN KEY (PIP_ID) REFERENCES PIPConfiguration (id) -ALTER TABLE PIPConfiguration ADD CONSTRAINT FK_PIPConfiguration_TYPE FOREIGN KEY (TYPE) REFERENCES PIPType (id) -ALTER TABLE PIPResolver ADD CONSTRAINT FK_PIPResolver_PIP_ID FOREIGN KEY (PIP_ID) REFERENCES PIPConfiguration (id) -ALTER TABLE PIPResolverParams ADD CONSTRAINT FK_PIPResolverParams_ID_RESOLVER FOREIGN KEY (ID_RESOLVER) REFERENCES PIPResolver (id) -ALTER TABLE roles ADD CONSTRAINT FK_roles_loginid FOREIGN KEY (loginid) REFERENCES UserInfo (loginid) -ALTER TABLE TERM ADD CONSTRAINT FK_TERM_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) -ALTER TABLE TERM ADD CONSTRAINT FK_TERM_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) -ALTER TABLE VarbindDictionary ADD CONSTRAINT FK_VarbindDictionary_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) -ALTER TABLE VarbindDictionary ADD CONSTRAINT FK_VarbindDictionary_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) -ALTER TABLE VNFType ADD CONSTRAINT FK_VNFType_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) -ALTER TABLE VNFType ADD CONSTRAINT FK_VNFType_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) -ALTER TABLE VSCLAction ADD CONSTRAINT FK_VSCLAction_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) -ALTER TABLE VSCLAction ADD CONSTRAINT FK_VSCLAction_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) -ALTER TABLE PolicyGroupEntity ADD CONSTRAINT FK_PolicyGroupEntity_policyId FOREIGN KEY (policyId) REFERENCES PolicyEntity (policyId) -ALTER TABLE PolicyGroupEntity ADD CONSTRAINT FK_PolicyGroupEntity_groupKey FOREIGN KEY (groupKey) REFERENCES GroupEntity (groupKey) -CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT NUMERIC(38), PRIMARY KEY (SEQ_NAME)) -INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0) diff --git a/ECOMP-PAP-REST/src/main/resources/META-INF/generatedDrop.ddl b/ECOMP-PAP-REST/src/main/resources/META-INF/generatedDrop.ddl deleted file mode 100644 index 70ef3cb75..000000000 --- a/ECOMP-PAP-REST/src/main/resources/META-INF/generatedDrop.ddl +++ /dev/null @@ -1,118 +0,0 @@ -ALTER TABLE PolicyEntity DROP CONSTRAINT FK_PolicyEntity_configurationDataId -ALTER TABLE PolicyEntity DROP CONSTRAINT FK_PolicyEntity_actionBodyId -ALTER TABLE PdpEntity DROP CONSTRAINT FK_PdpEntity_groupKey -ALTER TABLE FunctionDefinition DROP CONSTRAINT FK_FunctionDefinition_return_datatype -ALTER TABLE Attribute DROP CONSTRAINT FK_Attribute_category -ALTER TABLE Attribute DROP CONSTRAINT FK_Attribute_constraint_type -ALTER TABLE Attribute DROP CONSTRAINT FK_Attribute_created_by -ALTER TABLE Attribute DROP CONSTRAINT FK_Attribute_modified_by -ALTER TABLE Attribute DROP CONSTRAINT FK_Attribute_datatype -ALTER TABLE ConstraintValues DROP CONSTRAINT FK_ConstraintValues_attribute_id -ALTER TABLE FunctionArguments DROP CONSTRAINT FK_FunctionArguments_function_id -ALTER TABLE FunctionArguments DROP CONSTRAINT FK_FunctionArguments_datatype_id -ALTER TABLE ActionPolicyDict DROP CONSTRAINT FK_ActionPolicyDict_modified_by -ALTER TABLE ActionPolicyDict DROP CONSTRAINT FK_ActionPolicyDict_created_by -ALTER TABLE DecisionSettings DROP CONSTRAINT FK_DecisionSettings_created_by -ALTER TABLE DecisionSettings DROP CONSTRAINT FK_DecisionSettings_datatype -ALTER TABLE DecisionSettings DROP CONSTRAINT FK_DecisionSettings_modified_by -ALTER TABLE MicroServiceModels DROP CONSTRAINT FK_MicroServiceModels_imported_by -ALTER TABLE AttributeAssignment DROP CONSTRAINT FK_AttributeAssignment_OBADVICE_id -ALTER TABLE BRMSParamTemplate DROP CONSTRAINT FK_BRMSParamTemplate_created_by -ALTER TABLE ClosedLoopD2Services DROP CONSTRAINT FK_ClosedLoopD2Services_modified_by -ALTER TABLE ClosedLoopD2Services DROP CONSTRAINT FK_ClosedLoopD2Services_created_by -ALTER TABLE ClosedLoopSite DROP CONSTRAINT FK_ClosedLoopSite_modified_by -ALTER TABLE ClosedLoopSite DROP CONSTRAINT FK_ClosedLoopSite_created_by -ALTER TABLE DescriptiveScope DROP CONSTRAINT FK_DescriptiveScope_created_by -ALTER TABLE DescriptiveScope DROP CONSTRAINT FK_DescriptiveScope_modified_by -ALTER TABLE EcompName DROP CONSTRAINT FK_EcompName_created_by -ALTER TABLE EcompName DROP CONSTRAINT FK_EcompName_modified_by -ALTER TABLE ObadviceExpressions DROP CONSTRAINT FK_ObadviceExpressions_obadvice_id -ALTER TABLE ObadviceExpressions DROP CONSTRAINT FK_ObadviceExpressions_attribute_id -ALTER TABLE PEPOptions DROP CONSTRAINT FK_PEPOptions_modified_by -ALTER TABLE PEPOptions DROP CONSTRAINT FK_PEPOptions_created_by -ALTER TABLE PIPConfigParams DROP CONSTRAINT FK_PIPConfigParams_PIP_ID -ALTER TABLE PIPConfiguration DROP CONSTRAINT FK_PIPConfiguration_TYPE -ALTER TABLE PIPResolver DROP CONSTRAINT FK_PIPResolver_PIP_ID -ALTER TABLE PIPResolverParams DROP CONSTRAINT FK_PIPResolverParams_ID_RESOLVER -ALTER TABLE roles DROP CONSTRAINT FK_roles_loginid -ALTER TABLE TERM DROP CONSTRAINT FK_TERM_modified_by -ALTER TABLE TERM DROP CONSTRAINT FK_TERM_created_by -ALTER TABLE VarbindDictionary DROP CONSTRAINT FK_VarbindDictionary_modified_by -ALTER TABLE VarbindDictionary DROP CONSTRAINT FK_VarbindDictionary_created_by -ALTER TABLE VNFType DROP CONSTRAINT FK_VNFType_modified_by -ALTER TABLE VNFType DROP CONSTRAINT FK_VNFType_created_by -ALTER TABLE VSCLAction DROP CONSTRAINT FK_VSCLAction_modified_by -ALTER TABLE VSCLAction DROP CONSTRAINT FK_VSCLAction_created_by -ALTER TABLE PolicyGroupEntity DROP CONSTRAINT FK_PolicyGroupEntity_policyId -ALTER TABLE PolicyGroupEntity DROP CONSTRAINT FK_PolicyGroupEntity_groupKey -DROP TABLE PolicyEntity -DROP TABLE ConfigurationDataEntity -DROP TABLE PolicyDBDaoEntity -DROP TABLE GroupEntity -DROP TABLE PdpEntity -DROP TABLE ActionBodyEntity -DROP TABLE DatabaseLockEntity -DROP TABLE PolicyVersion -DROP TABLE POLICYSCORE -DROP TABLE FunctionDefinition -DROP TABLE Attribute -DROP TABLE Category -DROP TABLE ConstraintType -DROP TABLE ConstraintValues -DROP TABLE Datatype -DROP TABLE FunctionArguments -DROP TABLE UserInfo -DROP TABLE ActionPolicyDict -DROP TABLE DecisionSettings -DROP TABLE MicroServiceModels -DROP TABLE actionlist -DROP TABLE AddressGroup -DROP TABLE AttributeAssignment -DROP TABLE BRMSParamTemplate -DROP TABLE ClosedLoopD2Services -DROP TABLE ClosedLoopSite -DROP TABLE DCAEUsers -DROP TABLE DCAEuuid -DROP TABLE DescriptiveScope -DROP TABLE EcompName -DROP TABLE EnforcingType -DROP TABLE GlobalRoleSettings -DROP TABLE GroupPolicyScopeList -DROP TABLE GroupServiceList -DROP TABLE MicroServiceConfigName -DROP TABLE MicroServiceLocation -DROP TABLE Obadvice -DROP TABLE ObadviceExpressions -DROP TABLE PEPOptions -DROP TABLE PIPConfigParams -DROP TABLE PIPConfiguration -DROP TABLE PIPResolver -DROP TABLE PIPResolverParams -DROP TABLE PIPType -DROP TABLE PolicyAlgorithms -DROP TABLE policy_manangement -DROP TABLE PolicyScopeService -DROP TABLE PolicyScopeType -DROP TABLE PolicyScopeResource -DROP TABLE PolicyScopeClosedLoop -DROP TABLE portlist -DROP TABLE protocollist -DROP TABLE RemoteCatalogValues -DROP TABLE roles -DROP TABLE RuleAlgorithms -DROP TABLE securityzone -DROP TABLE servicegroup -DROP TABLE SystemLogDB -DROP TABLE TERM -DROP TABLE VarbindDictionary -DROP TABLE VMType -DROP TABLE VNFType -DROP TABLE VSCLAction -DROP TABLE zone -DROP TABLE BackUpMonitorEntity -DROP TABLE StateManagementEntity -DROP TABLE ForwardProgressEntity -DROP TABLE ResourceRegistrationEntity -DROP TABLE IntegrityAuditEntity -DROP TABLE PolicyGroupEntity -DELETE FROM SEQUENCE WHERE SEQ_NAME = 'SEQ_GEN' diff --git a/ECOMP-PAP-REST/src/main/resources/META-INF/persistence.xml b/ECOMP-PAP-REST/src/main/resources/META-INF/persistence.xml deleted file mode 100644 index 1d7692a3d..000000000 --- a/ECOMP-PAP-REST/src/main/resources/META-INF/persistence.xml +++ /dev/null @@ -1,201 +0,0 @@ - - - - - org.openecomp.policy.rest.jpa.PolicyEntity - org.openecomp.policy.rest.jpa.ConfigurationDataEntity - org.openecomp.policy.rest.jpa.PolicyDBDaoEntity - org.openecomp.policy.rest.jpa.GroupEntity - org.openecomp.policy.rest.jpa.PdpEntity - org.openecomp.policy.rest.jpa.ActionBodyEntity - org.openecomp.policy.rest.jpa.DatabaseLockEntity - org.openecomp.policy.rest.jpa.PolicyVersion - org.openecomp.policy.rest.jpa.PolicyScore - org.openecomp.policy.rest.jpa.FunctionDefinition - org.openecomp.policy.rest.jpa.Attribute - org.openecomp.policy.rest.jpa.Category - org.openecomp.policy.rest.jpa.ConstraintType - org.openecomp.policy.rest.jpa.ConstraintValue - org.openecomp.policy.rest.jpa.Datatype - org.openecomp.policy.rest.jpa.FunctionArgument - org.openecomp.policy.rest.jpa.UserInfo - org.openecomp.policy.rest.jpa.ActionPolicyDict - org.openecomp.policy.rest.jpa.DecisionSettings - org.openecomp.policy.rest.jpa.MicroServiceModels - org.openecomp.policy.rest.jpa.BRMSParamTemplate - org.openecomp.policy.rest.jpa.PolicyEditorScopes - - org.openecomp.policy.jpa.BackUpMonitorEntity - - org.openecomp.policy.common.im.jpa.StateManagementEntity - org.openecomp.policy.common.im.jpa.ForwardProgressEntity - org.openecomp.policy.common.im.jpa.ResourceRegistrationEntity - - org.openecomp.policy.common.ia.jpa.IntegrityAuditEntity - false - NONE - - - - - - - - - - - - - - - org.openecomp.policy.jpa.BackUpMonitorEntity - - org.openecomp.policy.common.im.jpa.StateManagementEntity - org.openecomp.policy.common.im.jpa.ForwardProgressEntity - org.openecomp.policy.common.im.jpa.ResourceRegistrationEntity - - org.openecomp.policy.common.ia.jpa.IntegrityAuditEntity - true - NONE - - - - - - org.eclipse.persistence.jpa.PersistenceProvider - org.openecomp.policy.rest.jpa.PolicyEntity - org.openecomp.policy.rest.jpa.ConfigurationDataEntity - org.openecomp.policy.rest.jpa.PolicyDBDaoEntity - org.openecomp.policy.rest.jpa.GroupEntity - org.openecomp.policy.rest.jpa.PdpEntity - org.openecomp.policy.rest.jpa.ActionBodyEntity - org.openecomp.policy.rest.jpa.DatabaseLockEntity - org.openecomp.policy.rest.jpa.PolicyVersion - org.openecomp.policy.rest.jpa.PolicyScore - org.openecomp.policy.rest.jpa.FunctionDefinition - org.openecomp.policy.rest.jpa.Attribute - org.openecomp.policy.rest.jpa.Category - org.openecomp.policy.rest.jpa.ConstraintType - org.openecomp.policy.rest.jpa.ConstraintValue - org.openecomp.policy.rest.jpa.Datatype - org.openecomp.policy.rest.jpa.FunctionArgument - org.openecomp.policy.rest.jpa.UserInfo - org.openecomp.policy.rest.jpa.ActionPolicyDict - org.openecomp.policy.rest.jpa.DecisionSettings - org.openecomp.policy.rest.jpa.MicroServiceModels - - org.openecomp.policy.rest.jpa.ActionList - org.openecomp.policy.rest.jpa.AddressGroup - org.openecomp.policy.rest.jpa.AttributeAssignment - org.openecomp.policy.rest.jpa.BRMSParamTemplate - org.openecomp.policy.rest.jpa.ClosedLoopD2Services - org.openecomp.policy.rest.jpa.ClosedLoopSite - org.openecomp.policy.rest.jpa.DCAEUsers - org.openecomp.policy.rest.jpa.DCAEuuid - org.openecomp.policy.rest.jpa.DescriptiveScope - org.openecomp.policy.rest.jpa.EcompName - org.openecomp.policy.rest.jpa.EnforcingType - org.openecomp.policy.rest.jpa.GlobalRoleSettings - org.openecomp.policy.rest.jpa.GroupPolicyScopeList - org.openecomp.policy.rest.jpa.GroupServiceList - org.openecomp.policy.rest.jpa.MicroServiceConfigName - org.openecomp.policy.rest.jpa.MicroServiceLocation - org.openecomp.policy.rest.jpa.Obadvice - org.openecomp.policy.rest.jpa.ObadviceExpression - org.openecomp.policy.rest.jpa.PEPOptions - org.openecomp.policy.rest.jpa.PIPConfigParam - org.openecomp.policy.rest.jpa.PIPConfiguration - org.openecomp.policy.rest.jpa.PIPResolver - org.openecomp.policy.rest.jpa.PIPResolverParam - org.openecomp.policy.rest.jpa.PIPType - org.openecomp.policy.rest.jpa.PolicyAlgorithms - org.openecomp.policy.rest.jpa.PolicyManagement - org.openecomp.policy.rest.jpa.PolicyScopeService - org.openecomp.policy.rest.jpa.PolicyScopeType - org.openecomp.policy.rest.jpa.PolicyScopeResource - org.openecomp.policy.rest.jpa.PolicyScopeClosedLoop - org.openecomp.policy.rest.jpa.PortList - org.openecomp.policy.rest.jpa.PREFIXLIST - org.openecomp.policy.rest.jpa.ProtocolList - org.openecomp.policy.rest.jpa.RemoteCatalogValues - org.openecomp.policy.rest.jpa.PolicyRoles - org.openecomp.policy.rest.jpa.RuleAlgorithms - org.openecomp.policy.rest.jpa.SecurityZone - org.openecomp.policy.rest.jpa.ServiceList - org.openecomp.policy.rest.jpa.SystemLogDB - org.openecomp.policy.rest.jpa.TermList - org.openecomp.policy.rest.jpa.VarbindDictionary - org.openecomp.policy.rest.jpa.VMType - org.openecomp.policy.rest.jpa.VNFType - org.openecomp.policy.rest.jpa.VSCLAction - org.openecomp.policy.rest.jpa.Zone - - org.openecomp.policy.jpa.BackUpMonitorEntity - - org.openecomp.policy.common.im.jpa.StateManagementEntity - org.openecomp.policy.common.im.jpa.ForwardProgressEntity - org.openecomp.policy.common.im.jpa.ResourceRegistrationEntity - - org.openecomp.policy.common.ia.jpa.IntegrityAuditEntity - - false - NONE - - - - - - - - - - - - - - - diff --git a/ECOMP-PAP-REST/src/main/resources/log4j.properties b/ECOMP-PAP-REST/src/main/resources/log4j.properties deleted file mode 100644 index 80f85e945..000000000 --- a/ECOMP-PAP-REST/src/main/resources/log4j.properties +++ /dev/null @@ -1,71 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PAP-REST -# ================================================================================ -# 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========================================================= -### - -# -# Use this properties for deployments. -# -# -# Set root logger level to DEBUG and its only appender to FILE. -#log4j.rootLogger=DEBUG, FILE, CONSOLE -log4j.rootLogger=INFO, FILE - -# FILE appender -log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender -log4j.appender.FILE.File=${catalina.base}/logs/pap-rest.log -log4j.appender.FILE.ImmediateFlush=true -log4j.appender.FILE.Threshold=debug -log4j.appender.FILE.append=true -log4j.appender.FILE.DatePattern='.'yyyy-MM-dd -log4j.appender.FILE.layout=org.apache.log4j.PatternLayout -log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss}{GMT+0}+00:00|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%l||%m%n - -# for Developments and Debugging -#log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender -#log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout -#log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n - -# -# This is specifically for Xacml request/response logging -# -log4j.logger.xacml.request=INFO, REQUEST_LOG - -log4j.appender.REQUEST_LOG=org.apache.log4j.DailyRollingFileAppender -log4j.appender.REQUEST_LOG.File=${catalina.base}/logs/pap-rest-reqres.log -log4j.appender.REQUEST_LOG.ImmediateFlush=true -log4j.appender.REQUEST_LOG.Threshold=debug -log4j.appender.REQUEST_LOG.append=true -log4j.appender.REQUEST_LOG.DatePattern='.'yyyy-MM-dd - -log4j.appender.REQUEST_LOG.layout=org.apache.log4j.PatternLayout -log4j.appender.REQUEST_LOG.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} %m%n - -# -# audit (transaction) logging -# -log4j.logger.auditLogger=INFO,AUDIT_LOG -log4j.additivity.auditLogger=false - -log4j.appender.AUDIT_LOG=org.apache.log4j.DailyRollingFileAppender -log4j.appender.AUDIT_LOG.File=${catalina.base}/logs/audit.log -log4j.appender.AUDIT_LOG.Append=true -log4j.appender.AUDIT_LOG.DatePattern='.'yyyy-MM-dd -log4j.appender.AUDIT_LOG.threshold=INFO -log4j.appender.AUDIT_LOG.layout=org.apache.log4j.EnhancedPatternLayout -log4j.appender.AUDIT_LOG.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss}{GMT+0}+00:00|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%X{className}|%X{timer}|%m%n diff --git a/ECOMP-PAP-REST/src/main/resources/logback.xml b/ECOMP-PAP-REST/src/main/resources/logback.xml deleted file mode 100644 index d406431db..000000000 --- a/ECOMP-PAP-REST/src/main/resources/logback.xml +++ /dev/null @@ -1,254 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --> - - - - - - - - - - - - - - - - - - - - ${defaultPattern} - - - - - - - - - - - - - ${logDirectory}/${auditLogName}.log - - ${logDirectory}/${auditLogName}.%i.log.zip - - 1 - 9 - - - 5MB - - - ${defaultAuditPattern} - - - - - 256 - - - - - - - - ${logDirectory}/${metricsLogName}.log - - ${logDirectory}/${metricsLogName}.%i.log.zip - - 1 - 9 - - - 5MB - - - - ${defaultMetricPattern} - - - - - 256 - - - - - - - - ${logDirectory}/${errorLogName}.log - - ${logDirectory}/${errorLogName}.%i.log.zip - - 1 - 9 - - - ERROR - - - 5MB - - - ${defaultErrorPattern} - - - - - 256 - - - - - - - ${debugLogDirectory}/${debugLogName}.log - - ${debugLogDirectory}/${debugLogName}.%i.log.zip - - 1 - 9 - - - DEBUG - - - 5MB - - - ${debugLoggerPattern} - - - - - 256 - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ECOMP-PAP-REST/src/main/resources/spring.xml b/ECOMP-PAP-REST/src/main/resources/spring.xml deleted file mode 100644 index 20414fabe..000000000 --- a/ECOMP-PAP-REST/src/main/resources/spring.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - classpath:hibernate.cfg.xml - - - - org.hibernate.dialect.MySQLDialect - thread - false - - - - diff --git a/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/ia/DbAuditCompareEntriesTest.java b/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/ia/DbAuditCompareEntriesTest.java deleted file mode 100644 index 2fef9a7cb..000000000 --- a/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/ia/DbAuditCompareEntriesTest.java +++ /dev/null @@ -1,450 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.ia; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Properties; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.Persistence; - -import org.apache.commons.lang3.SerializationUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.policy.common.ia.DbAudit; -import org.openecomp.policy.common.ia.DbDAO; -import org.openecomp.policy.common.ia.IntegrityAuditProperties; -import org.openecomp.policy.common.ia.jpa.IntegrityAuditEntity; -import org.openecomp.policy.common.im.jpa.ForwardProgressEntity; -import org.openecomp.policy.common.im.jpa.ResourceRegistrationEntity; -import org.openecomp.policy.common.im.jpa.StateManagementEntity; -import org.openecomp.policy.jpa.BackUpMonitorEntity; - -public class DbAuditCompareEntriesTest { - - private static Log logger = LogFactory.getLog(DbAuditCompareEntriesTest.class); - private DbDAO dbDAO; - private String persistenceUnit; - private Properties properties; - private String resourceName; - private String dbDriver; - private String dbUrl; - private String dbUser; - private String dbPwd; - private String siteName; - private String nodeType; - - @Before - public void setUp() throws Exception { - logger.info("setUp: Entering"); - - properties = new Properties(); - properties.put(IntegrityAuditProperties.DB_DRIVER, IntegrityAuditProperties.DEFAULT_DB_DRIVER); - properties.put(IntegrityAuditProperties.DB_URL, "jdbc:h2:file:./sql/xacmlTest"); - properties.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); - properties.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.DEFAULT_DB_PWD); - properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); - properties.put(IntegrityAuditProperties.NODE_TYPE, "pap"); - - dbDriver = IntegrityAuditProperties.DEFAULT_DB_DRIVER; - dbUrl = "jdbc:h2:file:./sql/xacmlTest"; - dbUser = IntegrityAuditProperties.DEFAULT_DB_USER; - dbPwd = IntegrityAuditProperties.DEFAULT_DB_PWD; - siteName = "SiteA"; - nodeType = "pap"; - persistenceUnit = "testPapPU"; - resourceName = "siteA.pap1"; - - //Clean the iaTest DB table for IntegrityAuditEntity entries - cleanDb(persistenceUnit, properties); - - logger.info("setUp: Exiting"); - } - - @After - public void tearDown() throws Exception { - logger.info("tearDown: Entering"); - //nothing to do - logger.info("tearDown: Exiting"); - } - - public void cleanDb(String persistenceUnit, Properties properties){ - logger.debug("cleanDb: enter"); - - EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); - - EntityManager em = emf.createEntityManager(); - // Start a transaction - EntityTransaction et = em.getTransaction(); - - et.begin(); - - // Clean up the DB - em.createQuery("Delete from IntegrityAuditEntity").executeUpdate(); - - // commit transaction - et.commit(); - em.close(); - logger.debug("cleanDb: exit"); - } - - - /* - * Tests that a comparison between hashsets is successful if - * the entries match - */ - @Test - public void runAllTests() throws Exception { - logger.info("runAllTests: Entering"); - - - testIntegrityAuditEntity(); - testBackupMonitorEntity(); - testStateManagementEntity(); - testForwardProgressEntity(); - testResourceRegistrationEntity(); - - //clean up the IntegrityAuditEntity table - cleanDb(persistenceUnit, properties); - - logger.info("runAllTests: Exit"); - } - - - public void testIntegrityAuditEntity() throws Exception { - logger.info("testIntegrityAuditEntity: Entering"); - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); - DbAudit dbAudit = new DbAudit(dbDAO); - - String className = null; - //There is only one entry IntegrityAuditEntity, but we will check anyway - HashSet classNameSet = dbDAO.getPersistenceClassNames(); - for(String c : classNameSet){ - if (c.equals("org.openecomp.policy.common.ia.jpa.IntegrityAuditEntity")){ - className = c; - } - } - String resourceName1 = resourceName; - String resourceName2 = resourceName; - - IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); - IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); - Date date = new Date(); - - /* - * Two entries with the same field values - */ - entry1.setDesignated(false); - entry1.setJdbcDriver(dbDriver); - entry1.setJdbcPassword(dbPwd); - entry1.setJdbcUrl(dbUrl); - entry1.setJdbcUser(dbUser); - entry1.setLastUpdated(date); - entry1.setNodeType(nodeType); - entry1.setPersistenceUnit(persistenceUnit); - entry1.setResourceName(resourceName1); - entry1.setSite(siteName); - - entry2 = SerializationUtils.clone(entry1); - - dbAudit.writeAuditDebugLog(className, resourceName1, resourceName2, entry1, entry2); - - HashMap myEntries = new HashMap<>(); - HashMap theirEntries = new HashMap<>(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - HashSet result = dbAudit.compareEntries(myEntries, theirEntries); - - /* - * Assert that there are no mismatches returned - */ - assertTrue(result.isEmpty()); - - /* - * ************************************ - * Now test with a mis-matched entry - * ************************************ - */ - - /* - * Change the entry2 to different designated value - */ - entry2.setDesignated(true); - - myEntries = new HashMap<>(); - theirEntries = new HashMap<>(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - result = dbAudit.compareEntries(myEntries, theirEntries); - - /* - * Assert that there was one mismatch - */ - assertEquals(1, result.size()); - logger.info("testIntegrityAuditEntity: Exit"); - } - - void testBackupMonitorEntity() throws Exception { - logger.info("testBackupMonitorEntity: Entering"); - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); - DbAudit dbAudit = new DbAudit(dbDAO); - - BackUpMonitorEntity entry1 = new BackUpMonitorEntity(); - BackUpMonitorEntity entry2 = new BackUpMonitorEntity(); - - // Two entries with the same field values - - - entry1.setFlag("flag1"); - entry1.setResoruceNodeName("node1"); - entry1.setResourceName("resourceName"); - entry1.setTimeStamp(new Date()); - - // Clone the first entry - entry2 = SerializationUtils.clone(entry1); - - HashMap myEntries = new HashMap<>(); - HashMap theirEntries = new HashMap<>(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - HashSet result = dbAudit.compareEntries(myEntries, theirEntries); - - - // Assert that there are no mismatches returned - - assertTrue(result.isEmpty()); - - - /* ************************************ - * Now test with a mis-matched entry - * ************************************/ - - - - // Change a field on entry2 - - entry2.setFlag("flag2"); - - myEntries = new HashMap<>(); - theirEntries = new HashMap<>(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - result = dbAudit.compareEntries(myEntries, theirEntries); - - - //Assert that there was one mismatch - - assertEquals(1, result.size()); - logger.info("testBackupMonitorEntity: Exit"); - } - - void testStateManagementEntity() throws Exception { - logger.info("testStateManagementEntity: Entering"); - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); - DbAudit dbAudit = new DbAudit(dbDAO); - - StateManagementEntity entry1 = new StateManagementEntity(); - StateManagementEntity entry2 = new StateManagementEntity(); - - // Two entries with the same field values - - entry1.setAdminState("locked"); - entry1.setAvailStatus("null"); - entry1.setModifiedDate(new Date()); - entry1.setOpState("enabled"); - entry1.setResourceName("myResource"); - entry1.setStandbyStatus("coldstandby"); - - // Clone the first entry - entry2 = SerializationUtils.clone(entry1); - - HashMap myEntries = new HashMap<>(); - HashMap theirEntries = new HashMap<>(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - HashSet result = dbAudit.compareEntries(myEntries, theirEntries); - - - // Assert that there are no mismatches returned - - assertTrue(result.isEmpty()); - - - /* ************************************ - * Now test with a mis-matched entry - * ************************************/ - - - - // Change a field on entry2 - - entry2.setAdminState("unlocked"); - - myEntries = new HashMap<>(); - theirEntries = new HashMap<>(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - result = dbAudit.compareEntries(myEntries, theirEntries); - - - //Assert that there was one mismatch - - assertEquals(1, result.size()); - logger.info("testStateManagementEntity: Exit"); - } - - void testForwardProgressEntity() throws Exception { - logger.info("testForwardProgressEntity: Entering"); - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); - DbAudit dbAudit = new DbAudit(dbDAO); - - ForwardProgressEntity entry1 = new ForwardProgressEntity(); - ForwardProgressEntity entry2 = new ForwardProgressEntity(); - - // Two entries with the same field values - - entry1.setFpcCount(123L); - entry1.setLastUpdated(new Date()); - entry1.setResourceName("myResource"); - - // Clone the first entry - entry2 = SerializationUtils.clone(entry1); - - HashMap myEntries = new HashMap(); - HashMap theirEntries = new HashMap(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - HashSet result = dbAudit.compareEntries(myEntries, theirEntries); - - - // Assert that there are no mismatches returned - - assertTrue(result.isEmpty()); - - - /* ************************************ - * Now test with a mis-matched entry - * ************************************/ - - // Change a field on entry2 - - entry2.setFpcCount(321L); - - myEntries = new HashMap<>(); - theirEntries = new HashMap<>(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - result = dbAudit.compareEntries(myEntries, theirEntries); - - - //Assert that there was one mismatch - - assertEquals(1, result.size()); - logger.info("testForwardProgressEntity: Exit"); - } - - void testResourceRegistrationEntity() throws Exception { - logger.info("testResourceRegistrationEntity: Entering"); - - dbDAO = new DbDAO(resourceName, persistenceUnit, properties); - DbAudit dbAudit = new DbAudit(dbDAO); - - ResourceRegistrationEntity entry1 = new ResourceRegistrationEntity(); - ResourceRegistrationEntity entry2 = new ResourceRegistrationEntity(); - - // Two entries with the same field values - - entry1.setNodeType("pap"); - entry1.setLastUpdated(new Date()); - entry1.setResourceName("myResource"); - entry1.setResourceUrl("http://nowhere.com"); - entry1.setSite("site_1"); - - // Clone the first entry - entry2 = SerializationUtils.clone(entry1); - - HashMap myEntries = new HashMap<>(); - HashMap theirEntries = new HashMap<>(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - HashSet result = dbAudit.compareEntries(myEntries, theirEntries); - - - // Assert that there are no mismatches returned - - assertTrue(result.isEmpty()); - - - /* ************************************ - * Now test with a mis-matched entry - * ************************************/ - - // Change a field on entry2 - - entry2.setSite("site_1a"); - - myEntries = new HashMap<>(); - theirEntries = new HashMap<>(); - - myEntries.put("pdp1", entry1); - theirEntries.put("pdp1", entry2); - - result = dbAudit.compareEntries(myEntries, theirEntries); - - - //Assert that there was one mismatch - - assertEquals(1, result.size()); - logger.info("testResourceRegistrationEntity: Exit"); - } -} \ No newline at end of file diff --git a/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDaoTest.java b/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDaoTest.java deleted file mode 100644 index 9d7fae209..000000000 --- a/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/components/PolicyDBDaoTest.java +++ /dev/null @@ -1,636 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.components; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Paths; -import java.util.Date; -import java.util.List; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.Persistence; -import javax.persistence.PersistenceException; -import javax.persistence.Query; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.junit.After; -import org.junit.Assert; -//import org.apache.commons.logging.Log; -//import org.apache.commons.logging.LogFactory; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pap.xacml.rest.components.PolicyDBDao.PolicyDBDaoTestClass; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.rest.adapter.PolicyRestAdapter; -import org.openecomp.policy.rest.jpa.GroupEntity; -import org.openecomp.policy.rest.jpa.PdpEntity; -import org.openecomp.policy.rest.jpa.PolicyEntity; -import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; -import org.openecomp.policy.xacml.std.pap.StdPDPGroup; -import org.openecomp.policy.xacml.util.XACMLPolicyWriter; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.util.XACMLProperties; - -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; - -public class PolicyDBDaoTest { - - private static Logger logger = FlexLogger.getLogger(PolicyDBDaoTest.class); - - PolicyDBDaoTestClass d; - PolicyDBDao dbd; - PolicyDBDao dbd2; - EntityManagerFactory emf; - @Before - public void init(){ - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"xacml.pap.properties"); - emf = Persistence.createEntityManagerFactory("testPapPU"); - EntityManager em = emf.createEntityManager(); - em.getTransaction().begin(); - try{ - em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate(); - em.createQuery("DELETE FROM PolicyEntity").executeUpdate(); - em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate(); - em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate(); - em.createQuery("DELETE FROM PdpEntity").executeUpdate(); - em.createQuery("DELETE FROM GroupEntity").executeUpdate(); - - em.getTransaction().commit(); - } catch(Exception e){ - logger.error("Exception Occured"+e); - em.getTransaction().rollback(); - } - em.close(); - try { - dbd = PolicyDBDao.getPolicyDBDaoInstance(emf); - dbd2 = PolicyDBDao.getPolicyDBDaoInstance(emf); - } catch (Exception e) { - //logger.error("Exception Occured"+e); - Assert.fail(); - } - - d = PolicyDBDao.getPolicyDBDaoTestClass(); - } - - @After - public void cleanUp(){ - EntityManager em = emf.createEntityManager(); - em.getTransaction().begin(); - try{ - em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate(); - em.createQuery("DELETE FROM PolicyEntity").executeUpdate(); - em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate(); - em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate(); - em.createQuery("DELETE FROM PdpEntity").executeUpdate(); - em.createQuery("DELETE FROM GroupEntity").executeUpdate(); - - em.getTransaction().commit(); - } catch(Exception e){ - em.getTransaction().rollback(); - } - em.close(); - try { - FileUtils.forceDelete(new File("src/test/resources/junitTestCreatedDirectory")); - } catch (IOException e) { - //could not delete - } - - } - - @Test - public void computeScopeTest(){ - Assert.assertEquals("com",d.computeScope("C:\\Users\\testuser\\admin\\repo\\com\\", "C:\\Users\\testuser\\admin\\repo")); - Assert.assertEquals("org.openecomp.policy",d.computeScope("/Users/testuser/admin/repo/org/openecomp/policy", "/Users/testuser/admin/repo")); - } - @Test - public void getConfigFileTest(){ - PolicyRestAdapter pra = new PolicyRestAdapter(); - pra.setConfigType(ConfigPolicy.JSON_CONFIG); - String configFile = d.getConfigFile("Config_mypolicy.xml", "org.openecomp", pra); - Assert.assertEquals("org.openecomp.Config_mypolicy.json", configFile); - //yes, we can do action files too even though they don't have configs - configFile = d.getConfigFile("Action_mypolicy.xml", "org.openecomp", pra); - Assert.assertEquals("org.openecomp.Action_mypolicy.json", configFile); - } - - @Ignore - @Test - public void createFromPolicyObject(){ - String workspaceDir = "src/test/resources/"; - File parentPath = new File(workspaceDir+"/com"); - Policy policyObject = new ConfigPolicy(); - policyObject.policyAdapter = new PolicyRestAdapter(); - policyObject.policyAdapter.setConfigName("testpolicy1"); - policyObject.policyAdapter.setParentPath(parentPath.getAbsolutePath()); - policyObject.policyAdapter.setPolicyDescription("my description"); - policyObject.policyAdapter.setConfigBodyData("this is my test config file"); - policyObject.policyAdapter.setPolicyName("testpolicy1"); - policyObject.policyAdapter.setConfigType(ConfigPolicy.OTHER_CONFIG); - policyObject.policyAdapter.setPolicyType("Config"); - policyObject.policyAdapter.setDomainDir("org.openecomp"); - PolicyType policyTypeObject = new PolicyType(); - policyObject.policyAdapter.setPolicyData(policyTypeObject); - PolicyDBDaoTransaction transaction = dbd.getNewTransaction(); - try{ - transaction.createPolicy(policyObject, "testuser1"); - transaction.commitTransaction(); - } catch(Exception e){ - transaction.rollbackTransaction(); - Assert.fail(); - } - - EntityManager getData = emf.createEntityManager(); - Query getDataQuery = getData.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:name"); - getDataQuery.setParameter("scope", "org.openecomp"); - getDataQuery.setParameter("name","Config_testpolicy1.xml"); - PolicyEntity result = null; - try{ - result = (PolicyEntity)getDataQuery.getSingleResult(); - } catch(Exception e){ - logger.error("Exception Occured"+e); - Assert.fail(); - } - String expectedData; - try { - expectedData = IOUtils.toString(XACMLPolicyWriter.getXmlAsInputStream(policyTypeObject)); - } catch (IOException e1) { - expectedData = ""; - } - Assert.assertEquals(expectedData, result.getPolicyData()); - getData.close(); - result = null; - File policyFile = new File(workspaceDir+"/org/openecomp/Config_testpolicy1.xml"); - try{ - transaction = dbd.getNewTransaction(); - transaction.deletePolicy(policyFile.getAbsolutePath()); - } catch(Exception e){ - logger.error("Exception Occured"+e); - Assert.fail(); - } - Assert.assertTrue(transaction.isTransactionOpen()); - try{ - transaction.deletePolicy(policyFile.getAbsolutePath()); - Assert.fail(); - } catch(IllegalStateException e){ - //pass - } catch(Exception e){ - Assert.fail(); - } - transaction.commitTransaction(); - Assert.assertFalse(transaction.isTransactionOpen()); - try{ - transaction = dbd.getNewTransaction(); - transaction.deletePolicy(policyFile.getAbsolutePath()); - } catch(Exception e){ - logger.error("Exception Occured"+e); - Assert.fail(); - } - //Assert.assertFalse(transaction.isTransactionOpen()); - transaction.commitTransaction(); - } - - @Ignore - @Test - public void groupTransactions(){ - PolicyDBDaoTransaction group = dbd.getNewTransaction(); - String groupName = "test group 1"; - try{ - group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "this is a test group","testuser"); - group.commitTransaction(); - } catch(Exception e){ - group.rollbackTransaction(); - logger.error("Exception Occured"+e); - Assert.fail(); - } - EntityManager em = emf.createEntityManager(); - Query getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - getGroup.setParameter("groupId", PolicyDBDao.createNewPDPGroupId(groupName)); - getGroup.setParameter("deleted", false); - List groups = getGroup.getResultList(); - if(groups.size() != 1){ - Assert.fail(); - } - GroupEntity groupEntity = (GroupEntity)groups.get(0); - em.close(); - Assert.assertEquals(groupName, groupEntity.getgroupName()); - Assert.assertEquals("this is a test group", groupEntity.getDescription()); - group = dbd.getNewTransaction(); - try{ - EcompPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId(groupName),Paths.get("/")); - group.deleteGroup(groupToDelete, null,"testuser"); - group.commitTransaction(); - } catch(Exception e){ - group.rollbackTransaction(); - logger.error("Exception Occured"+e); - Assert.fail(); - } - em = emf.createEntityManager(); - getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - getGroup.setParameter("groupId", PolicyDBDao.createNewPDPGroupId(groupName)); - getGroup.setParameter("deleted", false); - groups = getGroup.getResultList(); - if(groups.size() != 0){ - System.out.println("Group size: "+groups.size()); - Assert.fail(); - } - em.close(); - //add a pdp to a group - group = dbd.getNewTransaction(); - try{ - group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "test group", "testuser"); - group.commitTransaction(); - } catch(Exception e){ - group.rollbackTransaction(); - logger.error("Exception Occured"+e); - Assert.fail(); - } - group = dbd.getNewTransaction(); - try{ - group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId(groupName), "primary", "the main pdp", 3232, "testuser"); - group.commitTransaction(); - } catch(Exception e){ - group.rollbackTransaction(); - logger.error("Exception Occured"+e); - Assert.fail(); - } - em = emf.createEntityManager(); - Query getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); - getPdp.setParameter("pdpId", "http://localhost:4344/pdp/"); - getPdp.setParameter("deleted", false); - List pdps = getPdp.getResultList(); - if(pdps.size() != 1){ - System.out.println("Group size: "+pdps.size()); - Assert.fail(); - } - PdpEntity pdp = (PdpEntity)pdps.get(0); - Assert.assertEquals(groupName, pdp.getGroup().getgroupName()); - Assert.assertEquals(pdp.getPdpName(), "primary"); - em.close(); - group = dbd.getNewTransaction(); - try{ - group.removePdpFromGroup("http://localhost:4344/pdp/","testuser"); - group.commitTransaction(); - } catch(Exception e){ - group.rollbackTransaction(); - logger.error("Exception Occured"+e); - Assert.fail(); - } - em = emf.createEntityManager(); - getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); - getPdp.setParameter("pdpId", "http://localhost:4344/pdp/"); - getPdp.setParameter("deleted", false); - pdps = getPdp.getResultList(); - if(pdps.size() != 0){ - System.out.println("Group size: "+pdps.size()); - Assert.fail(); - } - em.close(); - - //add some pdps to groups - group = dbd.getNewTransaction(); - try{ - group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"), "testgroup1", "test group", "testuser"); - group.commitTransaction(); - } catch(Exception e){ - group.rollbackTransaction(); - logger.error("Exception Occured"+e); - Assert.fail(); - } - group = dbd.getNewTransaction(); - try{ - group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"), "testgroup2", "test group", "testuser"); - group.commitTransaction(); - } catch(Exception e){ - group.rollbackTransaction(); - logger.error("Exception Occured"+e); - Assert.fail(); - } - - group = dbd.getNewTransaction(); - try{ - group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), "primary", "the main pdp", 3232, "testuser"); - group.commitTransaction(); - } catch(Exception e){ - group.rollbackTransaction(); - logger.error("Exception Occured"+e); - Assert.fail(); - } - group = dbd.getNewTransaction(); - try{ - group.addPdpToGroup("http://localhost:4345/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), "secondary", "the second pdp", 3233, "testuser"); - group.commitTransaction(); - } catch(Exception e){ - group.rollbackTransaction(); - logger.error("Exception Occured"+e); - Assert.fail(); - } - em = emf.createEntityManager(); - getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.deleted=:deleted"); - getPdp.setParameter("deleted", false); - pdps = getPdp.getResultList(); - for(Object o : pdps){ - Assert.assertEquals("testgroup1",((PdpEntity)o).getGroup().getgroupName()); - } - em.close(); - - group = dbd.getNewTransaction(); - try{ - EcompPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"),Paths.get("/")); - EcompPDPGroup groupToMoveTo = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"),Paths.get("/")); - group.deleteGroup(groupToDelete, groupToMoveTo,"testuser"); - group.commitTransaction(); - } catch(Exception e){ - group.rollbackTransaction(); - logger.error("Exception Occured"+e); - Assert.fail(); - } - em = emf.createEntityManager(); - getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - getGroup.setParameter("groupId", "testgroup1"); - getGroup.setParameter("deleted", false); - groups = getGroup.getResultList(); - if(groups.size() != 0){ - System.out.println("Group size: "+groups.size()); - Assert.fail(); - } - em.close(); - - em = emf.createEntityManager(); - getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.deleted=:deleted"); - getPdp.setParameter("deleted", false); - pdps = getPdp.getResultList(); - for(Object o : pdps){ - Assert.assertEquals("testgroup2",((PdpEntity)o).getGroup().getgroupName()); - } - em.close(); - - group = dbd.getNewTransaction(); - try{ - EcompPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"),Paths.get("/")); - EcompPDPGroup groupToMoveTo = null; - group.deleteGroup(groupToDelete, groupToMoveTo,"testuser"); - group.commitTransaction(); - Assert.fail(); - } catch(PAPException pe){ - //good, can't delete group with pdps - group.rollbackTransaction(); - } catch(Exception e){ - group.rollbackTransaction(); - logger.error("Exception Occured"+e); - Assert.fail(); - } - - - //add policy to group - - //update group - EcompPDPGroup pdpGroup = new StdPDPGroup("testgroup2", false, "newtestgroup2", "this is my new description", Paths.get("/")); - group = dbd.getNewTransaction(); - try{ - group.updateGroup(pdpGroup, "testuser"); - group.commitTransaction(); - }catch (Exception e){ - logger.error("Exception Occured"+e); - group.rollbackTransaction(); - Assert.fail(); - } - em = emf.createEntityManager(); - getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - getGroup.setParameter("groupId", "newtestgroup2"); - getGroup.setParameter("deleted", false); - groups = getGroup.getResultList(); - if(groups.size() != 1){ - System.out.println("Group size: "+groups.size()); - Assert.fail(); - } - em.close(); - em = emf.createEntityManager(); - getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); - getGroup.setParameter("groupId", "testgroup2"); - getGroup.setParameter("deleted", false); - groups = getGroup.getResultList(); - if(groups.size() != 0){ - System.out.println("Group size: "+groups.size()); - Assert.fail(); - } - em.close(); - } - - @Test - public void encryptionTest(){ - try { - String encr = d.encryptPassword("testpassword"); - System.out.println("original password: "+"testpassword"); - System.out.println("Encrypted password: "+encr); - String decr = d.decryptPassword(encr); - System.out.println("Decrypted password: "+decr); - Assert.assertEquals("testpassword", decr); - } catch (Exception e) { - logger.error("Exception Occured"+e); - Assert.fail(); - } - - } - @Test - public void getDescriptionFromXacmlTest(){ - String myTestDesc = "hello this is a test"; - String desc = d.getDescriptionFromXacml(""+myTestDesc+""); - Assert.assertEquals(myTestDesc, desc); - } - @Ignore - @Test - public void threadingStabilityTest(){ - if(logger.isDebugEnabled()){ - logger.debug("\n\n****************************" - + "threadingStabilityTest() entry" - + "******************************\n\n"); - } - - PolicyDBDaoTransaction t = dbd.getNewTransaction(); - Assert.assertTrue(t.isTransactionOpen()); - try { - //Add 1000 ms to the timeout just to be sure it actually times out - int sleepTime = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)) + 1000; - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n sleepTime = " + sleepTime - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - Thread.sleep(sleepTime); - } catch (InterruptedException e) { - logger.error("Exception Occured"+e); - } - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n Assert.assertFalse(t.isTransactionOpen() = " + t.isTransactionOpen() + ")" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - Assert.assertFalse(t.isTransactionOpen()); - - - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n a = dbd.getNewTransaction() " - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - PolicyDBDaoTransaction a = dbd.getNewTransaction(); - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n Assert.assertTrue(a.isTransactionOpen() = " + a.isTransactionOpen() + ")" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - Assert.assertTrue(a.isTransactionOpen()); - - try { - //Add 1000 ms to the timeout just to be sure it actually times out - int sleepTime = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)) + 1000; - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n sleepTime = " + sleepTime - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - Thread.sleep(sleepTime); - } catch (InterruptedException e) { - logger.error("Exception Occured"+e); - } - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n b = dbd.getNewTransaction() " - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - PolicyDBDaoTransaction b = dbd.getNewTransaction(); - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n Assert.assertFalse(a.isTransactionOpen() = " + a.isTransactionOpen() + ")" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - Assert.assertFalse(a.isTransactionOpen()); - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n Assert.assertTrue(b.isTransactionOpen() = " + b.isTransactionOpen() + ")" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - Assert.assertTrue(b.isTransactionOpen()); - b.close(); - - - - //Now let's test the transaction wait time timeout. Shorten the wait time to 1000 ms - System.setProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT,"1000"); - //And let's lengthen the transaction timeout to 5000 ms - System.setProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT,"5000"); - //get a transacton - PolicyDBDaoTransaction t1 = dbd.getNewTransaction(); - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n Assert.assertTrue(t1.isTransactionOpen() = " + t1.isTransactionOpen() + ")" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - Assert.assertTrue(t1.isTransactionOpen()); - //while it is open, get another from a different DB Dao so it will not collide on the synchronized code segment - //but will collide at the DB. Remember that the wait time is only 1000 ms - try { - //Now the 2nd transaction has a wait timeout in 1000 ms - PolicyDBDaoTransaction t2 = dbd2.getNewTransaction(); - /* - * Give it plenty of time to time out the second transaction - * It will actually hang right here until it either gets the lock from the DB or the - * request for the DB lock times out. The timers are very sloppy so, I have given - * this plenty of leeway. - */ - - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n Thread.sleep(3000)" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - Thread.sleep(3000); - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n Assert.assertTrue(t1.isTransactionOpen() = " + t1.isTransactionOpen() + ")" - + "\n Assert.assertFalse(t2.isTransactionOpen() = " + t2.isTransactionOpen() + ")" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - //Assert.assertTrue(t1.isTransactionOpen()); - //Assert.assertFalse(t2.isTransactionOpen()); - - Assert.fail("\n\nTransaction timeout of 1000 ms exceeded without a PersistenceException\n\n"); - } catch (PersistenceException e) { - //success - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " - + "\n SUCCESS! Transaction Wait Timeout worked!" - + "\n Caught PersistenceException = " + e - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - } catch (Exception e) { - // failure due to some other reason - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() FAILURE" - + "\n Caught Exception = " + e - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - logger.error("Exception Occured"+e); - Assert.fail(); - } - - if(logger.isDebugEnabled()){ - Date date= new java.util.Date(); - logger.debug("\n\nthreadingStabilityTest() exit" - + "\n TimeStamp = " + date.getTime() - + "\n\n"); - } - } - -} diff --git a/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryControllerTest.java b/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryControllerTest.java deleted file mode 100644 index 82427e8cb..000000000 --- a/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/controller/DictionaryControllerTest.java +++ /dev/null @@ -1,319 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.controller; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.BufferedReader; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; - -import javax.json.Json; -import javax.json.JsonObject; -import javax.servlet.http.HttpServletRequest; - -import org.json.JSONObject; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -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.Attribute; -import org.openecomp.policy.rest.jpa.MicroServiceModels; -import org.openecomp.policy.rest.jpa.PolicyEditorScopes; -import org.springframework.mock.web.MockHttpServletResponse; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.github.fge.jackson.JsonLoader; - -/** - * The class DictionaryControllerTest contains tests - * for the class {@link DictionaryController}* - * - * All JUnits are designed to run in the local development environment - * where they have write privileges and can execute time-sensitive - * tasks. - */ -public class DictionaryControllerTest { - - private static Logger logger = FlexLogger.getLogger(DictionaryControllerTest.class); - private static CommonClassDao commonClassDao; - private String jsonString = null; - private String configBodyString = null; - private HttpServletRequest request = null; - private DictionaryController controller = null; - private BufferedReader br = null; - - @Before - public void setUp() throws Exception { - logger.info("setUp: Entering"); - commonClassDao = Mockito.mock(CommonClassDao.class); - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - List microServiceModelsData = new ArrayList(); - MicroServiceModels testData = new MicroServiceModels(); - testData.setVersion("1707.4.1.2-Junit"); - - //--- mock the getDataByColumn() call - List microList = new ArrayList(); - microList.add("123"); - List listId = new ArrayList(); - when(commonClassDao.getDataByColumn(Attribute.class, "xacmlId")).thenReturn(microList); - PolicyEditorScopes editorScope = new PolicyEditorScopes(); - doNothing().when(commonClassDao).save(editorScope); - doNothing().when(commonClassDao).update(editorScope); - - when(commonClassDao.getData(Attribute.class)).thenReturn(listId); - - jsonString = "{\"attributeDictionaryDatas\": {\"error\": \"\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; - - configBodyString = "{\"service\":\"SniroPolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\",\"templateVersion\":\"1607\",\"version\":\"HD\"," - + "\"priority\":\"2\",\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\",\"retiredDate\":\"test\",\"scope\":\"SNIRO_PLACEMENT_VDHV\"," - + "\"name\":\"test\",\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\",\"target\":\"SNIRO\"}}"; - - request = mock(HttpServletRequest.class); - BufferedReader br = new BufferedReader(new StringReader(jsonString)); - //--- mock the getReader() call - when(request.getReader()).thenReturn(br); - - controller = new DictionaryController(commonClassDao); - - logger.info("setUp: exit"); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testGetAttributeDictionaryEntityDatabyAttributeName() { - logger.info("testGetAttributeDictionaryEntityDatabyAttributeName: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - - controller.getAttributeDictionaryEntityDatabyAttributeName(request, response); - - try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - } catch (UnsupportedEncodingException e) { - fail("Exception: " + e); - } - - logger.info("testGetAttributeDictionaryEntityDatabyAttributeName: exit"); - } - - @Test - public void testGetAttributeDictionaryEntityData() { - logger.info("testGetAttributeDictionaryEntityData: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - - controller.getAttributeDictionaryEntityData(request, response); - - try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - } catch (UnsupportedEncodingException e) { - fail("Exception: " + e); - } - - logger.info("testGetAttributeDictionaryEntityData: exit"); - } - - @Test - public void testSaveAttributeDictionary() { - logger.info("testSaveAttributeDictionary: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - jsonString = "{\"attributeDictionaryData\": {\"userDataTypeValues\": [{\"attributeValues\": \"Values1\"}, {\"attributeValues\": \"Values2\"}], \"datatypeBean\": {\"type\": \"C\"},\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"userDataTypeValues\": [\"user-type\"],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"some\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"}, \"userid\":\"smetest\", \"userDataTypeValues\":[\"type-one\"]}"; - - BufferedReader br = new BufferedReader(new StringReader(jsonString)); - when(request.getReader()).thenReturn(br); - controller.saveAttributeDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testSaveAttributeDictionary: exit"); - } - - @Test - public void testRemoveAttributeDictionary() { - logger.info("testRemoveAttributeDictionary: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; - BufferedReader br = new BufferedReader(new StringReader(jsonString)); - when(request.getReader()).thenReturn(br); - controller.removeAttributeDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testRemoveAttributeDictionary: exit"); - } - - @Test - public void testGetEcompNameDictionaryByNameEntityData() { - logger.info("testGetEcompNameDictionaryByNameEntityData: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - - controller.getEcompNameDictionaryByNameEntityData(request, response); - - try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("ecompNameDictionaryDatas")); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - } catch (UnsupportedEncodingException e) { - fail("Exception: " + e); - } - - logger.info("testGetEcompNameDictionaryByNameEntityData: exit"); - } - - @Test - public void testGetEcompNameDictionaryEntityData() { - logger.info("testGetEcompNameDictionaryEntityData: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - - controller.getEcompNameDictionaryEntityData(request, response); - - try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("ecompNameDictionaryDatas")); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - } catch (UnsupportedEncodingException e) { - fail("Exception: " + e); - } - - logger.info("testGetEcompNameDictionaryEntityData: exit"); - } - - @Test - public void testSaveEcompDictionary() { - - logger.info("testSaveEcompDictionary: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - jsonString = "{\"ecompNameDictionaryData\": {\"userDataTypeValues\": [{\"attributeValues\": \"Values1\"}, {\"attributeValues\": \"Values2\"}], \"datatypeBean\": {\"type\": \"C\"},\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"userDataTypeValues\": [\"user-type\"],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"some\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"}, \"userid\":\"smetest\", \"userDataTypeValues\":[\"type-one\"]}"; - - BufferedReader br = new BufferedReader(new StringReader(jsonString)); - when(request.getReader()).thenReturn(br); - controller.saveEcompDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("ecompNameDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testSaveEcompDictionary: exit"); - } - - @Test - public void testRemoveEcompDictionary() { - logger.info("testRemoveEcompDictionary: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; - BufferedReader br = new BufferedReader(new StringReader(jsonString)); - when(request.getReader()).thenReturn(br); - controller.removeEcompDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("ecompNameDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testRemoveEcompDictionary: exit"); - } - -} diff --git a/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java b/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java deleted file mode 100644 index c1f2973d3..000000000 --- a/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java +++ /dev/null @@ -1,693 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.controller; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.BufferedReader; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -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.DCAEuuid; -import org.openecomp.policy.rest.jpa.MicroServiceLocation; -import org.openecomp.policy.rest.jpa.MicroServiceModels; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.springframework.mock.web.MockHttpServletResponse; - -/** - * The class MicroServiceDictionaryControllerTest contains tests - * for the class {@link MicroServiceDictionaryController}* - * - * All JUnits are designed to run in the local development environment - * where they have write privileges and can execute time-sensitive - * tasks. - */ - -public class MicroServiceDictionaryControllerTest { - - private static Logger logger = FlexLogger.getLogger(MicroServiceDictionaryControllerTest.class); - private static CommonClassDao commonClassDao; - private String jsonString = null; - private String configBodyString = null; - private HttpServletRequest request = null; - private MicroServiceDictionaryController controller = null; - BufferedReader br = null; - - @Before - public void setUp() throws Exception { - logger.info("setUp: Entering"); - commonClassDao = Mockito.mock(CommonClassDao.class); - UserInfo userInfo = new UserInfo(); - userInfo.setUserLoginId("testUserId"); - userInfo.setUserName("John"); - when(commonClassDao.getEntityItem(UserInfo.class, "userLoginId", "testing")).thenReturn(userInfo); - - List listIds = new ArrayList(); - listIds.add("Jack"); - when(commonClassDao.getDataByColumn(DCAEuuid.class, "name")).thenReturn(listIds); - - List microList = new ArrayList(); - microList.add("MC-Model"); - when(commonClassDao.getDataByColumn(MicroServiceLocation.class, "name")).thenReturn(microList); - - List listId = new ArrayList(); - listId.add("smith"); - when(commonClassDao.getData(DCAEuuid.class)).thenReturn(listId); - MicroServiceModels microServiceModels = new MicroServiceModels(); - - doNothing().when(commonClassDao).delete(microServiceModels); - - MicroServiceDictionaryController.setCommonClassDao(commonClassDao); - - controller = new MicroServiceDictionaryController(); - - HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - - jsonString = "{\"microServiceModelsDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; - - configBodyString = "{\"service\":\"SniroPolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\",\"templateVersion\":\"1607\",\"version\":\"HD\"," - + "\"priority\":\"2\",\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\",\"retiredDate\":\"test\",\"scope\":\"SNIRO_PLACEMENT_VDHV\"," - + "\"name\":\"test\",\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\",\"target\":\"SNIRO\"}}"; - - br = new BufferedReader(new StringReader(jsonString)); - //--- mock the getReader() call - when(request.getReader()).thenReturn(br); - - logger.info("setUp: exit"); - } - - @After - public void tearDown() throws Exception { - } - - - @Test - public void testGetUserInfo() { - - logger.info("testGetUserInfo: Entering"); - - UserInfo userInfo = controller.getUserInfo("testing"); - logger.info("userInfo.getUserName() : " + userInfo.getUserName()); - - assertEquals("John", userInfo.getUserName()); - - logger.info("testGetUserInfo: exit"); - } - - @Test - public void testGetDCAEUUIDDictionaryByNameEntityData() { - - logger.info("testGetDCAEUUIDDictionaryByNameEntityData: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - - controller.getDCAEUUIDDictionaryByNameEntityData(request, response); - - try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeUUIDDictionaryDatas")); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - } catch (UnsupportedEncodingException e) { - fail("Exception: " + e); - } - - logger.info("testGetDCAEUUIDDictionaryByNameEntityData: exit"); - } - - @Test - public void testGetDCAEUUIDDictionaryEntityData() { - - logger.info("testGetDCAEUUIDDictionaryEntityData: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - - controller.getDCAEUUIDDictionaryEntityData(request, response); - - try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeUUIDDictionaryDatas")); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - } catch (UnsupportedEncodingException e) { - fail("Exception: " + e); - } - - logger.info("testGetDCAEUUIDDictionaryEntityData: exit"); - } - - @Test - public void testSaveDCAEUUIDDictionary() { - logger.info("testSaveDCAEUUIDDictionary: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - jsonString = "{\"dcaeUUIDDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; - BufferedReader br = new BufferedReader(new StringReader(jsonString)); - when(request.getReader()).thenReturn(br); - controller.saveDCAEUUIDDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeUUIDDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testSaveDCAEUUIDDictionary: exit"); - } - - @Test - public void testRemoveDCAEUUIDDictionary() { - logger.info("testRemoveDCAEUUIDDictionary: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; - BufferedReader br = new BufferedReader(new StringReader(jsonString)); - when(request.getReader()).thenReturn(br); - controller.removeMicroServiceConfigNameDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceCongigNameDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testRemoveDCAEUUIDDictionary: exit"); - } - - @Test - public void testGetMicroServiceConfigNameByNameDictionaryEntityData() { - logger.info("testGetMicroServiceConfigNameByNameDictionaryEntityData: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - - controller.getMicroServiceConfigNameByNameDictionaryEntityData(request, response); - - try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceCongigNameDictionaryDatas")); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - } catch (UnsupportedEncodingException e) { - fail("Exception: " + e); - } - - logger.info("testGetMicroServiceConfigNameByNameDictionaryEntityData: exit"); - } - - @Test - public void testGetMicroServiceConfigNameDictionaryEntityData() { - logger.info("testGetMicroServiceConfigNameByNameDictionaryEntityData: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - - controller.getMicroServiceConfigNameDictionaryEntityData(request, response); - - try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceCongigNameDictionaryDatas")); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - } catch (UnsupportedEncodingException e) { - fail("Exception: " + e); - } - - logger.info("testGetMicroServiceConfigNameDictionaryEntityData: exit"); - } - - @Test - public void testSaveMicroServiceConfigNameDictionary() { - logger.info("testSaveMicroServiceConfigNameDictionary: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - jsonString = "{\"microServiceCongigNameDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; - BufferedReader br = new BufferedReader(new StringReader(jsonString)); - when(request.getReader()).thenReturn(br); - controller.saveMicroServiceConfigNameDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceCongigNameDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testSaveMicroServiceConfigNameDictionary: exit"); - } - - @Test - public void testRemoveMicroServiceConfigNameDictionary() { - logger.info("testRemoveMicroServiceConfigNameDictionary: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; - BufferedReader br = new BufferedReader(new StringReader(jsonString)); - when(request.getReader()).thenReturn(br); - controller.removeMicroServiceConfigNameDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceCongigNameDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testRemoveMicroServiceConfigNameDictionary: exit"); - } - - @Test - public void testGetMicroServiceLocationByNameDictionaryEntityData() { - - logger.info("testGetMicroServiceLocationByNameDictionaryEntityData: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - - controller.getMicroServiceLocationByNameDictionaryEntityData(request, response); - - try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas")); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - } catch (UnsupportedEncodingException e) { - fail("Exception: " + e); - } - - logger.info("testGetMicroServiceLocationByNameDictionaryEntityData: exit"); - } - - @Test - public void testGetMicroServiceLocationDictionaryEntityData() { - logger.info("testGetMicroServiceLocationDictionaryEntityData: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - - controller.getMicroServiceLocationDictionaryEntityData(request, response); - - try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas")); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - } catch (UnsupportedEncodingException e) { - fail("Exception: " + e); - } - - logger.info("testGetMicroServiceLocationDictionaryEntityData: exit"); - } - - @Test - public void testSaveMicroServiceLocationDictionary() { - logger.info("testSaveMicroServiceLocationDictionary: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - jsonString = "{\"microServiceLocationDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; - BufferedReader br = new BufferedReader(new StringReader(jsonString)); - when(request.getReader()).thenReturn(br); - controller.saveMicroServiceLocationDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testSaveMicroServiceLocationDictionary: exit"); - } - - @Test - public void testRemoveMicroServiceLocationDictionary() { - logger.info("testRemoveMicroServiceLocationDictionary: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; - BufferedReader br = new BufferedReader(new StringReader(jsonString)); - - when(request.getReader()).thenReturn(br); - controller.removeMicroServiceLocationDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testRemoveMicroServiceLocationDictionary: exit"); - } - - @Test - public void testGetMicroServiceAttributeByNameDictionaryEntityData() { - logger.info("testGetMicroServiceAttributeByNameDictionaryEntityData: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - - controller.getMicroServiceAttributeByNameDictionaryEntityData(request, response); - - try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas")); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - } catch (UnsupportedEncodingException e) { - fail("Exception: " + e); - } - - logger.info("testGetMicroServiceAttributeByNameDictionaryEntityData: exit"); - } - - @Test - public void testGetMicroServiceAttributeDictionaryEntityData() { - logger.info("testGetMicroServiceAttributeDictionaryEntityData: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - - controller.getMicroServiceAttributeDictionaryEntityData(request, response); - - try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas")); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - } catch (UnsupportedEncodingException e) { - fail("Exception: " + e); - } - - logger.info("testGetMicroServiceAttributeDictionaryEntityData: exit"); - } - - @Test - public void testSaveMicroServiceAttributeDictionary() { - logger.info("testSaveMicroServiceAttributeDictionary: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - jsonString = "{\"modelAttributeDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; - BufferedReader br = new BufferedReader(new StringReader(jsonString)); - when(request.getReader()).thenReturn(br); - controller.saveMicroServiceAttributeDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testSaveMicroServiceAttributeDictionary: exit"); - } - - @Test - public void testRemoveMicroServiceAttributeDictionary() { - logger.info("testRemoveMicroServiceAttributeDictionary: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; - BufferedReader br = new BufferedReader(new StringReader(jsonString)); - when(request.getReader()).thenReturn(br); - controller.removeMicroServiceAttributeDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testRemoveMicroServiceAttributeDictionary: exit"); - } - - @Test - public void testGetMicroServiceModelsDictionaryByNameEntityData() { - logger.info("testGetMicroServiceModelsDictionaryByNameEntityData: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - - controller.getMicroServiceModelsDictionaryByNameEntityData(request, response); - - try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas")); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - } catch (UnsupportedEncodingException e) { - fail("Exception: " + e); - } - - logger.info("testGetMicroServiceModelsDictionaryByNameEntityData: exit"); - } - - @Test - public void testGetMicroServiceModelsDictionaryByVersionEntityData() { - logger.info("testGetMicroServiceModelsDictionaryByVersionEntityData: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}"; - - BufferedReader br = new BufferedReader(new StringReader(msModelJson)); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - when(request.getReader()).thenReturn(br); - controller.getMicroServiceModelsDictionaryByVersionEntityData(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("No model name given")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testGetMicroServiceModelsDictionaryByVersionEntityData: exit"); - } - - @Test - public void testGetMicroServiceModelsDictionaryEntityData() { - logger.info("testGetMicroServiceModelsDictionaryEntityData: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}"; - - BufferedReader br = new BufferedReader(new StringReader(msModelJson)); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - when(request.getReader()).thenReturn(br); - controller.getMicroServiceModelsDictionaryEntityData(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testGetMicroServiceModelsDictionaryEntityData: exit"); - } - - @Test - public void testGetMicroServiceModelsDictionaryEntityDataServiceVersion() { - logger.info("testGetMicroServiceModelsDictionaryEntityDataServiceVersion: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}"; - - BufferedReader br = new BufferedReader(new StringReader(msModelJson)); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - when(request.getReader()).thenReturn(br); - controller.getMicroServiceModelsDictionaryEntityDataServiceVersion(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testGetMicroServiceModelsDictionaryEntityDataServiceVersion: exit"); - } - - @Test - public void testGetMicroServiceModelsDictionaryClassEntityData() { - logger.info("testGetMicroServiceModelsDictionaryClassEntityData: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}"; - - BufferedReader br = new BufferedReader(new StringReader(msModelJson)); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - when(request.getReader()).thenReturn(br); - controller.getMicroServiceModelsDictionaryClassEntityData(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryClassDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testGetMicroServiceModelsDictionaryClassEntityData: exit"); - } - - @Test - public void testSaveMicroServiceModelsDictionary() { - logger.info("testSaveMicroServiceModelsDictionary: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - when(request.getReader()).thenReturn(br); - controller.saveMicroServiceModelsDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testSaveMicroServiceModelsDictionary: exit"); - } - - @Test - public void testRemoveMicroServiceModelsDictionary() { - logger.info("testRemoveMicroServiceModelsDictionary: Entering"); - - MockHttpServletResponse response = new MockHttpServletResponse(); - request = mock(HttpServletRequest.class); - - try { - // mock the getReader() call - jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " - + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " - + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," - + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," - + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " - + " \"policyDescription\": \"testing input\", \"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," - + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " - + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; - - BufferedReader br = new BufferedReader(new StringReader(jsonString)); - when(request.getReader()).thenReturn(br); - controller.removeMicroServiceModelsDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas")); - - } catch (Exception e) { - fail("Exception: " + e); - } - - logger.info("testRemoveMicroServiceModelsDictionary: exit"); - } - -} diff --git a/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/jpa/PolicyEntityTest.java b/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/jpa/PolicyEntityTest.java deleted file mode 100644 index 04ddd66e5..000000000 --- a/ECOMP-PAP-REST/src/test/java/org/openecomp/policy/pap/xacml/rest/jpa/PolicyEntityTest.java +++ /dev/null @@ -1,803 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.pap.xacml.rest.jpa; - -import static org.junit.Assert.*; - -//import org.apache.commons.logging.Log; -//import org.apache.commons.logging.LogFactory; -import org.junit.*; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.rest.jpa.ActionBodyEntity; -import org.openecomp.policy.rest.jpa.ConfigurationDataEntity; -import org.openecomp.policy.rest.jpa.PolicyDBDaoEntity; -import org.openecomp.policy.rest.jpa.PolicyEntity; - -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; -import javax.persistence.EntityTransaction; -import javax.persistence.Persistence; -import javax.persistence.Query; - -import java.util.Date; -import java.util.List; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -import java.util.Properties; - -public class PolicyEntityTest { - - private static Logger logger = FlexLogger.getLogger(PolicyEntityTest.class); - - @Test - public void testAllOps(){ - Properties properties = new Properties(); - properties.put(XACMLRestProperties.PROP_PAP_DB_DRIVER,"org.h2.Driver"); - properties.put(XACMLRestProperties.PROP_PAP_DB_URL, "jdbc:h2:file:./sql/xacmlTest"); - properties.put(XACMLRestProperties.PROP_PAP_DB_USER, "sa"); - properties.put(XACMLRestProperties.PROP_PAP_DB_PASSWORD, ""); - EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPapPU", properties); - EntityManager em = emf.createEntityManager(); - // Start a transaction - EntityTransaction et = em.getTransaction(); - - et.begin(); - //Make sure the DB is clean - em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate(); - em.createQuery("DELETE FROM PolicyEntity").executeUpdate(); - em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate(); - em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate(); - - //Create a policy object - PolicyEntity p1 = new PolicyEntity(); - - //persist the policy - em.persist(p1); - - long policyId1 = p1.getPolicyId(); - - String policyName1 = p1.getPolicyName(); - - int version1 = p1.getVersion(); - - String policyData1 = p1.getPolicyData(); - - ConfigurationDataEntity configData1 = p1.getConfigurationData(); - String configDataStr1 = (configData1!=null ? "configurationDataId = " + configData1.getConfigurationDataId() : "configurationData is null"); - - ActionBodyEntity actionBody1 = p1.getActionBodyEntity(); - String actionBodyStr1 = (actionBody1!=null ? "actionBodyId = " + actionBody1.getActionBodyId() : "actionBody is null"); - - String createdBy1 = p1.getCreatedBy(); - - Date createdDate1 = p1.getCreatedDate(); - String createdDateStr1 = (createdDate1 != null ? createdDate1.toString() : "createdDate is null"); - - String description = p1.getDescription(); - - String modifiedBy1 = p1.getModifiedBy(); - - Date modifiedDate1 = p1.getModifiedDate(); - String modifiedDateStr1 = (modifiedDate1 != null ? modifiedDate1.toString() : "modifiedDate is null"); - - - logger.debug("\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects before persist*********" - + "\npolicyId1 = " + policyId1 - + "\npolicyName1 = " + policyName1 - + "\nversion1 = " + version1 - + "\npolicyData1 = " + policyData1 - + "\nconfigDataStr1 = " + configDataStr1 - + "\nactionBodyStr1 = " + actionBodyStr1 - + "\nscope = " + p1.getScope() - + "\ncreatedBy1 = " + createdBy1 - + "\ncreatedDateStr1 = " + createdDateStr1 - + "\ndescription = " + description - + "\nmodifiedBy1 = " + modifiedBy1 - + "\nmodifiedDateStr1 = " + modifiedDateStr1 - + "\ndeleted = " + p1.isDeleted()); - - //Set policyID - p1.setPolicyName("testPID2"); - - //Set policyData - p1.setPolicyData("PolicyData"); - - //We will NOT set the ConfigurationDataEntity or ActionBodyEntity object just to test that it is optional - - //set createdBy - p1.setCreatedBy("kevin"); - - //createdDate will be set when it is persisted - - //set scope - p1.setScope("mckiou.kevin"); - - //set description - p1.setDescription("PolicyEntity Description"); - - //set modifiedBy - p1.setModifiedBy("kevin"); - - //modifiedDate will be set when it is persisted - - //Flush to the DB - em.flush(); - - //Now lets get some attribute values - - policyId1 = p1.getPolicyId(); - - policyName1 = p1.getPolicyName(); - - version1 = p1.getVersion(); - - policyData1 = p1.getPolicyData(); - - configData1 = p1.getConfigurationData(); - configDataStr1 = (configData1!=null ? "configurationDataId = " + configData1.getConfigurationDataId() : "configurationData is null"); - - actionBody1 = p1.getActionBodyEntity(); - actionBodyStr1 = (actionBody1!=null ? "actionBodyId = " + actionBody1.getActionBodyId() : "actionBody is null"); - - createdBy1 = p1.getCreatedBy(); - - createdDate1 = p1.getCreatedDate(); - createdDateStr1 = (createdDate1 != null ? createdDate1.toString() : "createdDate is null"); - - description = p1.getDescription(); - - modifiedBy1 = p1.getModifiedBy(); - - modifiedDate1 = p1.getModifiedDate(); - modifiedDateStr1 = (modifiedDate1 != null ? modifiedDate1.toString() : "modifiedDate is null"); - - logger.debug("\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects after persist*********" - + "\npolicyId1 = " + policyId1 - + "\npolicyName1 = " + policyName1 - + "\nversion1 = " + version1 - + "\npolicyData1 = " + policyData1 - + "\nconfigDataStr1 = " + configDataStr1 - + "\nactionBodyStr1 = " + actionBodyStr1 - + "\nscopeId = " + p1.getScope() - + "\ncreatedBy1 = " + createdBy1 - + "\ncreatedDateStr1 = " + createdDateStr1 - + "\ndescription = " + description - + "\nmodifiedBy1 = " + modifiedBy1 - + "\nmodifiedDateStr1 = " + modifiedDateStr1 - + "\ndeleted = " + p1.isDeleted()); - - //Now lets fully configure the configurationData and actionBody - - //Create a ConfigurationDataEntity object and set ID - ConfigurationDataEntity c1 = new ConfigurationDataEntity(); - - ActionBodyEntity a1 = new ActionBodyEntity(); - - //persist the configuration Data - em.persist(c1); - - c1.setConfigType("OTHER"); - - c1.setConfigBody("ABC"); - - c1.setDescription("ConfigurationDataEntity Description"); - - c1.setCreatedBy("kevin"); - - //c1.setModifiedBy("kevin"); - - c1.setDeleted(true); - - //persist the action Body - - em.persist(a1); - - a1.setActionBody("myActionBody"); - - a1.setActionBodyName("myActionBodyName"); - - a1.setCreatedBy("kevin"); - - a1.setModifiedBy("kevin"); - - a1.setDeleted(false); - - - long configurationDataId = c1.getConfigurationDataId(); - - int cdVersion = c1.getVersion(); - - String cdConfigType = c1.getConfigType(); - - String cdConfigBody = c1.getConfigBody(); - - String cdCreatedBy = c1.getCreatedBy(); - - Date cdCreatedDate = c1.getCreatedDate(); - - String cdDescription = c1.getDescription(); - - String cdModifiedBy = c1.getModifiedBy(); - - Date cdModifiedDate = c1.getModifiedDate(); - - logger.debug("\n\n********PolicyEntityTest: Local Configuration object after setting values *********" - + "\nconfigurationDataId = " + configurationDataId - + "\ncdVersion = " + cdVersion - + "\ncdConfigType = " + cdConfigType - + "\ncdConfigBody = " + cdConfigBody - + "\ncdCreatedBy = " + cdCreatedBy - + "\ncdCreatedDate = " + cdCreatedDate - + "\ncdDescription = " + cdDescription - + "\ncdModifiedBy = " + cdModifiedBy - + "\ncdModifiedDate = " + cdModifiedDate - + "\ndeleted = " + c1.isDeleted()); - - - - logger.debug("\n\n********PolicyEntityTest: Local Action Body object after setting values *********" - + "\nactionBodyId = " + a1.getActionBodyId() - + "\nactionBodyVersion = " + a1.getVersion() - + "\nactionBody = " + a1.getActionBody() - + "\nactionBodyCeatedBy = " + a1.getCreatedBy() - + "\nactionBodyCreatedDate = " + a1.getCreatedDate() - + "\nactionBodyModifiedBy = " + a1.getModifiedBy() - + "\nactionBodyModifiedDate = " + a1.getModifiedDate() - + "\nactionBodyDeleted = " + a1.isDeleted()); - - p1.setScope("mckiou.kevin.kim"); - - //flush to the db - em.flush(); - - //Perform policy selects - - Query query = em.createQuery("Select p from PolicyEntity p where p.policyId=:pid"); - Query queryscope = em.createQuery("Select p from PolicyEntity p where p.scope=:s"); - - query.setParameter("pid", p1.getPolicyId()); - queryscope.setParameter("s", "mckiou.kevin.kim"); - - //Just test that we are retrieving the right object - @SuppressWarnings("rawtypes") - List psList = queryscope.getResultList(); - PolicyEntity px = null; - if(!psList.isEmpty()){ - //ignores multiple results - px = (PolicyEntity) psList.get(0); - }else{ - fail("\nPolicyEntityTest: No PolicyEntity using scope DB entry found"); - } - - //The scope object on the retrieved policy object should be same as the one we used to find it - assertSame(p1,px); - - - //Because getSingleResult() throws an unchecked exception which is an indication of a - //programming error, we are not going to use it. - @SuppressWarnings("rawtypes") - List resultList = query.getResultList(); - PolicyEntity p2 = null; - if(!resultList.isEmpty()){ - // ignores multiple results - p2 = (PolicyEntity) resultList.get(0); - }else{ - fail("\nPolicyEntityTest: No PolicyEntity DB entry found"); - } - - logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB BEFORE assigning configurationData*********" - + "\npolicyId2 = " + p2.getPolicyId() - + "\npolicyName2 = " + p2.getPolicyName() - + "\nversion2 = " + p2.getVersion() - + "\npolicyData2 = " + p2.getPolicyData() - + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null") - + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null") - + "\nscope2 = " + p2.getScope() - + "\ncreatedBy2 = " + p2.getCreatedBy() - + "\ncreatedDate2 = " + p2.getCreatedDate() - + "\ndescription2 = " + p2.getDescription() - + "\nmodifiedBy2 = " + p2.getModifiedBy() - + "\nmodifiedDate2 = " + p2.getModifiedDate() - + "\ndeleted2 = " + p2.isDeleted()); - - //Confirm that the retrieved policy object is the same as the persisted object - assertSame(p1,p2); - - //Perform configurationData selects - Query query2 = em.createQuery("Select c from ConfigurationDataEntity c where c.configurationDataId=:cid"); - - query2.setParameter("cid", c1.getConfigurationDataId()); - - //Get the database version of the Configuration Data - resultList = query2.getResultList(); - ConfigurationDataEntity c2 = null; - if(!resultList.isEmpty()){ - // ignores multiple results - c2 = (ConfigurationDataEntity) resultList.get(0); - }else{ - fail("\nPolicyEntityTest: No ConfigurationDataEntity DB entry found"); - } - - logger.debug("\n\n********PolicyEntityTest: Configuration object after retrieving from DB BEFORE assigning to policy*********" - + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() - + "\nversion2 = " + c2.getVersion() - + "\nconfigType2 = " + c2.getConfigType() - + "\nconfigBody2 = " + c2.getConfigBody() - + "\ncreatedBy2 = " + c2.getCreatedBy() - + "\ncreatedDate2 = " + c2.getCreatedDate() - + "\ndescription2 = " + c2.getDescription() - + "\nmodifiedBy2 = " + c2.getModifiedBy() - + "\nmodifiedDate2 = " + c2.getModifiedDate() - + "\ndeleted2 = " + c2.isDeleted()); - - //Confirm the retrieved ConfigurationDataEntity object is the same as the persisted - assertSame(c1,c2); - - //Now assign the configurationData to the policy - p1.setConfigurationData(c1); - - //Perform actionBody selects - Query querya2 = em.createQuery("Select a from ActionBodyEntity a where a.actionBodyId=:aid"); - - querya2.setParameter("aid", a1.getActionBodyId()); - - //Get the database version of the Action Body - resultList = querya2.getResultList(); - ActionBodyEntity a2 = null; - if(!resultList.isEmpty()){ - // ignores multiple results - a2 = (ActionBodyEntity) resultList.get(0); - }else{ - fail("\nPolicyEntityTest: No ActionBodyEntity DB entry found"); - } - - - logger.debug("\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB BEFORE assigning to policy *********" - + "\nactionBodyId2 = " + a2.getActionBodyId() - + "\nactionBodyVersion2 = " + a2.getVersion() - + "\nactionBody2 = " + a2.getActionBody() - + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() - + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() - + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy() - + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() - + "\nactionBodyDeleted2 = " + a2.isDeleted()); - - - //Confirm the retrieved ActionBodyEntity object is the same as the persisted - assertSame(a1,a2); - - //Now assign the ActionBodyEntity to the policy - p1.setActionBodyEntity(a1); - - em.flush(); - - //Let's retrieve the policy, configurationData and actionBody from the DB and look at them - //Here is the policy object - resultList = query.getResultList(); - p2 = null; - if(!resultList.isEmpty()){ - // ignores multiple results - p2 = (PolicyEntity) resultList.get(0); - }else{ - fail("PolicyEntityTest: No PolicyEntity DB entry found"); - } - - logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB AFTER assigning configurationData*********" - + "\npolicyId2 = " + p2.getPolicyId() - + "\npolicyName2 = " + p2.getPolicyName() - + "\nversion2 = " + p2.getVersion() - + "\npolicyData2 = " + p2.getPolicyData() - + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null") - + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null") - + "\nscope2 = " + p2.getScope() - + "\ncreatedBy2 = " + p2.getCreatedBy() - + "\ncreatedDate2 = " + p2.getCreatedDate() - + "\ndescription2 = " + p2.getDescription() - + "\nmodifiedBy2 = " + p2.getModifiedBy() - + "\nmodifiedDate2 = " + p2.getModifiedDate() - + "\ndeleted2 = " + p2.isDeleted()); - - //And now the ConfigurationDataEntity object - resultList = query2.getResultList(); - c2 = null; - if(!resultList.isEmpty()){ - // ignores multiple results - c2 = (ConfigurationDataEntity) resultList.get(0); - }else{ - fail("\nPolicyEntityTest: No ConfigurationDataEntity DB entry found"); - } - - logger.debug("\n\n********PolicyEntityTest: Configuration object after retrieving from DB AFTER assigning to policy*********" - + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() - + "\nversion2 = " + c2.getVersion() - + "\nconfigType2 = " + c2.getConfigType() - + "\nconfigBody2 = " + c2.getConfigBody() - + "\ncreatedBy2 = " + c2.getCreatedBy() - + "\ncreatedDate2 = " + c2.getCreatedDate() - + "\ndescription2 = " + c2.getDescription() - + "\nmodifiedBy = " + c2.getModifiedBy() - + "\nmodifiedDate = " + c2.getModifiedDate() - + "\ndeleted2 = " + c2.isDeleted()); - - - //Get the database version of the Action Body - resultList = querya2.getResultList(); - a2 = null; - if(!resultList.isEmpty()){ - // ignores multiple results - a2 = (ActionBodyEntity) resultList.get(0); - }else{ - fail("\nPolicyEntityTest: No ActionBodyEntity DB entry found"); - } - - - logger.debug("\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB AFTER assigning to policy *********" - + "\nactionBodyId2 = " + a2.getActionBodyId() - + "\nactionBodyVersion2 = " + a2.getVersion() - + "\nactionBody2 = " + a2.getActionBody() - + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() - + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() - + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy() - + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() - + "\nactionBodyDeleted2 = " + a2.isDeleted()); - - - //****Now lets see if the orphanRemoval=true does anything useful*** - //Remove the configurationData from the policy relationship - - p1.setConfigurationData(null); - - p1.setActionBodyEntity(null); - - //flush the update to the DB - em.flush(); - - //Attempt to retrieve the configuration data object from the db. It should not be there - //Reusing the previous query - resultList = query2.getResultList(); - c2 = null; - if(resultList.isEmpty()){ - logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******" - + "\n Success!! No ConfigurationDataEntity DB entry found"); - - }else{ - c2 = (ConfigurationDataEntity) resultList.get(0); - fail("\nPolicyEntityTest: ConfigurationDataEntity DB entry found - and none should exist" - + "\nconfigurationDataId = " + c2.getConfigurationDataId()); - } - - //Attempt to retrieve the actionBody data object from the db. It should not be there - //Reusing the previous query - resultList = querya2.getResultList(); - a2 = null; - if(resultList.isEmpty()){ - logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******" - + "\n Success!! No ActionBodyEntity DB entry found"); - - }else{ - a2 = (ActionBodyEntity) resultList.get(0); - fail("\nPolicyEntityTest: ActionBodyEntity DB entry found - and none should exist" - + "\nactionBodyId = " + a2.getActionBodyId()); - } - - //Now lets put the configurationData and actionBody back into the policy object and see what appears - //in the DB after a flush - - //put c1 back into the persistence context since the orphanRemoval removed it. - em.persist(c1); - p1.setConfigurationData(c1); - - em.persist(a1); - p1.setActionBodyEntity(a1); - - em.flush(); - - //retrieve the policy object - resultList = query.getResultList(); - p2 = null; - if(!resultList.isEmpty()){ - // ignores multiple results - p2 = (PolicyEntity) resultList.get(0); - }else{ - fail("\nPolicyEntityTest: No PolicyEntity DB entry found"); - } - - //output what we policy object found - logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after again adding ConfigurationDataEntity and retrieving from DB*********" - + "\npolicyId2 = " + p2.getPolicyId() - + "\npolicyName2 = " + p2.getPolicyName() - + "\nversion2 = " + p2.getVersion() - + "\npolicyData2 = " + p2.getPolicyData() - + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null") - + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null") - + "\nscope2 = " + p2.getScope() - + "\ncreatedBy2 = " + p2.getCreatedBy() - + "\ncreatedDate2 = " + p2.getCreatedDate() - + "\ndescription2 = " + p2.getDescription() - + "\nmodifiedBy2 = " + p2.getModifiedBy() - + "\nmodifiedDate2 = " + p2.getModifiedDate() - + "\ndeleted2 = " + p2.isDeleted()); - - - //now lets see if it put the configurationData c1 back into the table - resultList = query2.getResultList(); - c2 = null; - if(!resultList.isEmpty()){ - // ignores multiple results - c2 = (ConfigurationDataEntity) resultList.get(0); - }else{ - fail("\nPolicyEntityTest - Check re-entry of configurationData into DB" - + "No ConfigurationDataEntity DB entry found"); - } - - //output what configurationData object we found - logger.debug("\n\n********PolicyEntityTest: Configuration object after re-enter into policy object and retrieving from DB *********" - + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() - + "\nversion2 = " + c2.getVersion() - + "\nconfigType2 = " + c2.getConfigType() - + "\nconfigBody2 = " + c2.getConfigBody() - + "\ncreatedBy2 = " + c2.getCreatedBy() - + "\ncreatedDate2 = " + c2.getCreatedDate() - + "\ndescription2 = " + c2.getDescription() - + "\nmodifiedBy = " + c2.getModifiedBy() - + "\nmodifiedDate = " + c2.getModifiedDate() - + "\ndeleted2 = " + c2.isDeleted()); - - //now lets see if it put the actionBody a1 back into the table - //Get the database version of the Action Body - resultList = querya2.getResultList(); - a2 = null; - if(!resultList.isEmpty()){ - // ignores multiple results - a2 = (ActionBodyEntity) resultList.get(0); - }else{ - fail("\nPolicyEntityTest - Check re-entry of actionBody into DB" - + "No ActionBodyEntity DB entry found"); - } - - logger.debug("\n\n********PolicyEntityTest: Local Action Body object after re-enter into policy object and retrieving from DB *********" - + "\nactionBodyId2 = " + a2.getActionBodyId() - + "\nactionBodyVersion2 = " + a2.getVersion() - + "\nactionBody2 = " + a2.getActionBody() - + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() - + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() - + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy() - + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() - + "\nactionBodyDeleted2 = " + a2.isDeleted()); - - //I want to save all the above in the DB - try{ - et.commit(); - logger.debug("\n\n***********PolicyEntityTest: et.commit Succeeded********"); - }catch(Exception e){ - logger.debug("\n\n***********PolicyEntityTest: et.commit Failed********" - + "\nTRANSACTION ROLLBACK " - + "\n with exception: " + e); - } - - // Start a new transaction - EntityTransaction et2 = em.getTransaction(); - - et2.begin(); - - //Let's test if the PolicyEntity uniqueConstraint for policyName and scopeId hold - PolicyEntity p3 = new PolicyEntity(); - em.persist(p3); - - - //first let's assure that you can save with the same name but a different scope - p3.setPolicyName(p1.getPolicyName()); - p3.setScope("mckiou.kevin.kory"); - em.flush(); - logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********" - + "\nSuccess! PolicyEntity uniqueness constraint allowed " - + "\n policyId1 " + p1.getPolicyId() - + "\n policyName1 " + p1.getPolicyName() - + "\n scope1 = " + p1.getScope() - + "\n policyId3 " + p3.getPolicyId() - + "\n policyName3 " + p3.getPolicyName() - + "\n scope3 = " + p3.getScope()); - - //Assert that the policyIds are NOT the same to show that the automatic sequencing is working - assert(p1.getPolicyId() != p3.getPolicyId()); - - try{ - //Now set the scope the same to verify the uniqueness constraint will be enforced - p3.setScope(p1.getScope()); - - em.flush(); - logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********" - + "\nFailed! PolicyEntity Uniqueness constraint FAILED and DID allow " - + "\n policyId1 " + p1.getPolicyId() - + "\n policyName1 " + p1.getPolicyName() - + "\n scope1 = " + p1.getScope() - + "\n policyId3 " + p3.getPolicyId() - + "\n policyName3 " + p3.getPolicyName() - + "\n scope3 = " + p3.getScope());; - } - catch(Exception e){ - //Success - logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********" - + "\nSuccess! PolicyEntity Uniqueness constraint SUCCEEDED and did NOT allow " - + "\n policyId1 " + p1.getPolicyId() - + "\n policyName1 " + p1.getPolicyName() - + "\n scope1 = " + p1.getScope() - + "\n policyId3 " + p3.getPolicyId() - + "\n policyName3 " + p3.getPolicyName() - + "\n scope3 = " + p3.getScope() - + "\n with excpetion: " + e); - } - - - try{ - et2.commit(); - logger.debug("\n\n***********PolicyEntityTest: et2.commit Succeeded********"); - }catch(Exception e){ - logger.debug("\n\n***********PolicyEntityTest: et2.commit Failed********" - + "\nTRANSACTION ROLLBACK " - + "\n with exception: " + e); - } - - //****************Test the PolicyDBDaoEntity************************ - - //Create a transaction - EntityTransaction et3 = em.getTransaction(); - - et3.begin(); - - //create one - PolicyDBDaoEntity pe1 = new PolicyDBDaoEntity(); - em.persist(pe1); - - pe1.setDescription("This is pe1"); - - pe1.setPolicyDBDaoUrl("http://123.45.2.456:2345"); - - //push it to the DB - em.flush(); - - //create another - PolicyDBDaoEntity pe2 = new PolicyDBDaoEntity(); - em.persist(pe2); - - pe2.setDescription("This is pe2"); - - pe2.setPolicyDBDaoUrl("http://789.01.2.345:2345"); - - //Print them to the log before flushing - logger.debug("\n\n***********PolicyEntityTest: PolicyDBDaoEntity objects before flush********" - + "\n policyDBDaoUrl-1 = " + pe1.getPolicyDBDaoUrl() - + "\n description-1 = " + pe1.getDescription() - + "\n createdDate-1 = " + pe1.getCreatedDate() - + "\n modifiedDate-1 " + pe1.getModifiedDate() - + "\n*****************************************" - + "\n policyDBDaoUrl-2 = " + pe2.getPolicyDBDaoUrl() - + "\n description-2 = " + pe2.getDescription() - + "\n createdDate-2 = " + pe2.getCreatedDate() - + "\n modifiedDate-2 " + pe2.getModifiedDate() - ); - - //push it to the DB - em.flush(); - - //Now let's retrieve them from the DB using the named query - - resultList = em.createNamedQuery("PolicyDBDaoEntity.findAll").getResultList(); - - PolicyDBDaoEntity pex = null; - PolicyDBDaoEntity pey = null; - - if(!resultList.isEmpty()){ - if (resultList.size() != 2){ - fail("\nPolicyEntityTest: Number of PolicyDBDaoEntity entries = " + resultList.size() + " instead of 2"); - } - for(Object policyDBDaoEntity: resultList){ - PolicyDBDaoEntity pdbdao = (PolicyDBDaoEntity)policyDBDaoEntity; - if(pdbdao.getPolicyDBDaoUrl().equals("http://123.45.2.456:2345")){ - pex = pdbdao; - }else if(pdbdao.getPolicyDBDaoUrl().equals("http://789.01.2.345:2345")){ - pey = pdbdao; - } - } - - //Print them to the log before flushing - logger.debug("\n\n***********PolicyEntityTest: PolicyDBDaoEntity objects retrieved from DB********" - + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl() - + "\n description-x = " + pex.getDescription() - + "\n createdDate-x = " + pex.getCreatedDate() - + "\n modifiedDate-x " + pex.getModifiedDate() - + "\n*****************************************" - + "\n policyDBDaoUrl-y = " + pey.getPolicyDBDaoUrl() - + "\n description-y = " + pey.getDescription() - + "\n createdDate-y = " + pey.getCreatedDate() - + "\n modifiedDate-y " + pey.getModifiedDate() - ); - //Verify the retrieved objects are the same as the ones we stored in the DB - if(pex.getPolicyDBDaoUrl().equals("http://123.45.2.456:2345")){ - assertSame(pe1,pex); - assertSame(pe2,pey); - }else{ - assertSame(pe2,pex); - assertSame(pe1,pey); - } - - }else{ - fail("\nPolicyEntityTest: No PolicyDBDaoEntity DB entry found"); - } - - //Now let's see if we can do an update on the PolicyDBDaoEntity which we retrieved. - //em.persist(pex); - pex.setDescription("This is pex"); - em.flush(); - - //retrieve it - Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyDBDaoEntity p WHERE p.description=:desc"); - resultList = createPolicyQuery.setParameter("desc", "This is pex").getResultList(); - - PolicyDBDaoEntity pez = null; - - if(!resultList.isEmpty()){ - if (resultList.size() != 1){ - fail("\nPolicyEntityTest: Update Test - Number of PolicyDBDaoEntity entries = " + resultList.size() + " instead of 1"); - } - pez = (PolicyDBDaoEntity) resultList.get(0); - - //Print them to the log before flushing - logger.debug("\n\n***********PolicyEntityTest: Update Test - PolicyDBDaoEntity objects retrieved from DB********" - + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl() - + "\n description-x = " + pex.getDescription() - + "\n createdDate-x = " + pex.getCreatedDate() - + "\n modifiedDate-x " + pex.getModifiedDate() - + "\n*****************************************" - + "\n policyDBDaoUrl-z = " + pez.getPolicyDBDaoUrl() - + "\n description-z = " + pez.getDescription() - + "\n createdDate-z = " + pez.getCreatedDate() - + "\n modifiedDate-z " + pez.getModifiedDate() - ); - //Verify the retrieved objects are the same as the ones we stored in the DB - assertSame(pex,pez); - }else{ - fail("\nPolicyEntityTest: Update Test - No PolicyDBDaoEntity DB updated entry found"); - } - - //Clean up the DB - em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate(); - em.createQuery("DELETE FROM PolicyEntity").executeUpdate(); - em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate(); - em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate(); - - //Wrap up the transaction - try{ - et3.commit(); - logger.debug("\n\n***********PolicyEntityTest: et3.commit Succeeded********"); - }catch(Exception e){ - logger.debug("\n\n***********PolicyEntityTest: et3.commit Failed********" - + "\nTRANSACTION ROLLBACK " - + "\n with exception: " + e); - } - - - //Tidy up - em.close(); - } - -} diff --git a/ECOMP-PAP-REST/test.properties b/ECOMP-PAP-REST/test.properties deleted file mode 100644 index 251a69e5e..000000000 --- a/ECOMP-PAP-REST/test.properties +++ /dev/null @@ -1,22 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PAP-REST -# ================================================================================ -# 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========================================================= -### - -PDP_URL=http://localhost:8082/pdp/, testpdp, alpha456 -#PAP_URL=http://localhost:8070/pap/, testpap, alpha123 diff --git a/ECOMP-PAP-REST/xacml.pap.properties b/ECOMP-PAP-REST/xacml.pap.properties deleted file mode 100644 index 0c6edc155..000000000 --- a/ECOMP-PAP-REST/xacml.pap.properties +++ /dev/null @@ -1,165 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PAP-REST -# ================================================================================ -# 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========================================================= -### -#=====================================================================================# -#================The Below Properties are default, shouldn't change them==============# -#=====================================================================================# -# -# This is our factory that will create our engine -# -xacml.PAP.papEngineFactory=org.openecomp.policy.xacml.std.pap.StdEngineFactory -# Dictionary and Policy Implementation Classes Properties -dictionary.impl.className=org.openecomp.policy.pap.xacml.rest.handler.DictionaryHandlerImpl -savePolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.SavePolicyHandler -pushPolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.PushPolicyHandler -deletePolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.DeleteHandler -#AutoPush Policy -xacml.rest.pap.autopush.file=autopush.properties -#=====================================================================================# -#===============The Below Properties will be changed based on Environment=============# -#=====================================================================================# -# -# Where we store our PAP PDP Group/Node information -# -xacml.pap.pdps=pdps -# -# Need the PAP's url (how PDPs will reach it) configured here -# because we need it to generate the URLs of the Policy Files -# sent to the PDPs in the configuration when the PAP is first brought up. -# (In other cases, such as the PDP calling the PAP, we could generate this URL, -# but for startup there is no other way to get it.) -# -# -xacml.rest.pap.url=http://localhost:8070/pap/ - -# -# Upon startup, have the PAP servlet send latest configuration information to all -# the PDP nodes it knows about. -# -xacml.rest.pap.initiate.pdp=true -# -# Heartbeat from PAP to PDPs -# -# How much time (in milliseconds) between heartbeats -# (i.e. the time between completing the heartbeat with all PDPs and starting the next cycle) -# -xacml.rest.pap.heartbeat.interval=100000 -# -# Heartbeat connection timeout (in milliseconds) -# -xacml.rest.pap.heartbeat.timeout=100000 - -# new Property Please mention your PAP-REST webapps Location here. -xacml.rest.config.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ - -#Turn the audit on to synchronize the DB/file system -#xacml.rest.pap.run.audit.flag=true -#Turn the audit off to not synchronize the DB/file system -#xacml.rest.pap.run.audit.flag=false -xacml.rest.pap.run.audit.flag=true - -#Audit will synchronize the file system to match the contents of the DB -#xacml.rest.pap.filesystem.audit=true -#Audit will synchronize the DB to match the contents of the file system -#xacml.rest.pap.filesystem.audit=false -xacml.rest.pap.filesystem.audit=false -xacm.xcor.required.pattern=1,1 -# id -xacml.rest.pap.userid=testpap -# pass -xacml.rest.pap.password=alpha123 -# pdps file -xacml.rest.pdp.idfile=test.properties - -#Properties for db access -#properties for MySql xacml database: PLEASE DO NOT REMOVE... NEEDED FOR APIs -javax.persistence.jdbc.driver=com.mysql.jdbc.Driver -javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/ecomp_sdk?failOverReadOnly=false&autoReconnect=true -javax.persistence.jdbc.user=policy_user -javax.persistence.jdbc.password=policy_user - -#Time in ms which a Policy DB transaction will wait to get the transaction lock object -xacml.rest.pap.transaction.waitms=500000 - -#Policy DB transaction timeout in ms after it has obtained the transaction lock object -xacml.rest.pap.transaction.timeoutms=500000 - -#Policy Audit timeout in ms after it has obtained the transaction lock object -xacml.rest.pap.audit.timeoutms=500000 - -#controls how long the pap will wait before giving up when sending notifications to other paps -xacml.rest.pap.notify.timeoutms=10000 - -#the number of times an incoming policy update notification will be tried to be processed (or until it succeeds) -xacml.rest.pap.incomingnotification.tries=4 - -#AutoPush Policy Flag -xacml.rest.pap.autopush.flag=false - -#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java*** - -#The name of the PAP. Must be unique across the system -xacml.rest.pap.resource.name=site_1.pap_1 - -#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** - -#Interval between forward progress counter updates in seconds -fp_monitor_interval=30 - -#Number of forward progress counter failures before failover -failed_counter_threshold=3 - -#Interval in seconds between test transactions if there is no other traffic -test_trans_interval=10 - -#Interval in seconds between updates of the forward progress counter in the DB -write_fpc_interval=5 - -#Name of the site -site_name=site_1 - -#Node type. Can take values of: pdp-xacml, pdp-drools, pap, pap-admin, logparser, brms-gateway, -#astra-gateway, elk-server -node_type=pap - -#Dependency groups are groups of resources upon which a node operational state is dependent upon (dependency_groups). -#Each group is a comma-separated list of resource names and groups are separated by a semicolon. A group may contain -#one or more members. -dependency_groups=site_1.logparser_1;site_1.adminconsole_1;site_1.elk_1 - -# The (optional) period of time in seconds between executions of the integrity audit. -# Value < 0 : Audit does not run (default value if property is not present = -1) -# Value = 0 : Audit runs continuously -# Value > 0 : The period of time in seconds between execution of the audit on a particular node -integrity_audit_period_seconds=-1 - -ENVIRONMENT=DEVL - -# -#PolicySafetyChecker properties -# -#Turn safetyChecker on/off -xacml.rest.pap.safetychecker=on -PDP_URL1 = http://localhost:8082/pdp/, testpdp, alpha456 -CLIENT_ID= -CLIENT_KEY= - -#Micro Service Model Properties -xacml.policy.msEcompName=http://org.openecomp -xacml.policy.msPolicyName=http://org.openecomp/policy \ No newline at end of file diff --git a/ECOMP-PAP-REST/xacml.pap.test.properties b/ECOMP-PAP-REST/xacml.pap.test.properties deleted file mode 100644 index fbeb5bd81..000000000 --- a/ECOMP-PAP-REST/xacml.pap.test.properties +++ /dev/null @@ -1,145 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PAP-REST -# ================================================================================ -# 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========================================================= -### -#=====================================================================================# -#================The Below Properties are default, shouldn't change them==============# -#=====================================================================================# -# -# This is our factory that will create our engine -# -xacml.PAP.papEngineFactory=org.openecomp.policy.xacml.std.pap.StdEngineFactory -# Dictionary and Policy Implementation Classes Properties -dictionary.impl.className=org.openecomp.policy.pap.xacml.rest.handler.DictionaryHandlerImpl -savePolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.SavePolicyHandler -pushPolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.PushPolicyHandler -deletePolicy.impl.className=org.openecomp.policy.pap.xacml.rest.handler.DeleteHandler -#AutoPush Policy -xacml.rest.pap.autopush.file=autopush.properties -#=====================================================================================# -#===============The Below Properties will be changed based on Environment=============# -#=====================================================================================# -# -# Where we store our PAP PDP Group/Node information -# -xacml.pap.pdps=pdps -# -# Need the PAP's url (how PDPs will reach it) configured here -# because we need it to generate the URLs of the Policy Files -# sent to the PDPs in the configuration when the PAP is first brought up. -# (In other cases, such as the PDP calling the PAP, we could generate this URL, -# but for startup there is no other way to get it.) -# -# -xacml.rest.pap.url=http://localhost:8070/pap/ -# -# Upon startup, have the PAP servlet send latest configuration information to all -# the PDP nodes it knows about. -# -xacml.rest.pap.initiate.pdp=true -# -# Heartbeat from PAP to PDPs -# -# How much time (in milliseconds) between heartbeats -# (i.e. the time between completing the heartbeat with all PDPs and starting the next cycle) -# -xacml.rest.pap.heartbeat.interval=10000 -# -# Heartbeat connection timeout (in milliseconds) -# -xacml.rest.pap.heartbeat.timeout=10000 - -# new Property Please mention your PAP-REST webapps Location here. -xacml.rest.config.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ - -#Turn the audit on to synchronize the DB/file system -#xacml.rest.pap.run.audit.flag=true -#Turn the audit off to not synchronize the DB/file system -#xacml.rest.pap.run.audit.flag=false -xacml.rest.pap.run.audit.flag=false - -#Audit will synchronize the file system to match the contents of the DB -#xacml.rest.pap.filesystem.audit=true -#Audit will synchronize the DB to match the contents of the file system -#xacml.rest.pap.filesystem.audit=false -xacml.rest.pap.filesystem.audit=false - -# id -xacml.rest.pap.userid=testpap -# pass -xacml.rest.pap.password=alpha123 -# pdps file -xacml.rest.pdp.idfile=test.properties - -#Properties for db access -javax.persistence.jdbc.driver=org.h2.Driver -javax.persistence.jdbc.url=jdbc:h2:file:./sql/xacmlTest -javax.persistence.jdbc.user=sa -javax.persistence.jdbc.password= - -#Time in ms which a Policy DB transaction will wait to get the transaction lock object -xacml.rest.pap.transaction.waitms=1000 - -#Policy DB transaction timeout in ms after it has obtained the transaction lock object -xacml.rest.pap.transaction.timeoutms=500 - -#Policy Audit timeout in ms after it has obtained the transaction lock object -xacml.rest.pap.audit.timeoutms=5000 - -#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** - -#JMX URL for the PAP-REST. Need to update to real IP and port -xacml.rest.pap.jmx.url=service:jmx:rmi:///jndi/rmi://localhost:9990/jmxrmi - -#The name of the PAP. Must be unique across the system -xacml.rest.pap.resource.name=site_1.pap_1 - -#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** - -#Interval between forward progress counter updates in seconds -fp_monitor_interval=30 - -#Number of forward progress counter failures before failover -failed_counter_threshold=3 - -#Interval in seconds between test transactions if there is no other traffic -test_trans_interval=10 - -#Interval in seconds between updates of the forward progress counter in the DB -write_fpc_interval=5 - -#Name of the site -site_name=site_1 - -#Node type. Can take values of: pdp-xacml, pdp-drools, pap, pap-admin, logparser, brms-gateway, -#astra-gateway, elk-server -node_type=pap - -#Dependency groups are groups of resources upon which a node operational state is dependent upon (dependency_groups). -#Each group is a comma-separated list of resource names and groups are separated by a semicolon. A group may contain -#one or more members. -dependency_groups=site_1.logparser_1;site_1.adminconsole_1;site_1.elk_1 - -# The (optional) period of time in seconds between executions of the integrity audit. -# Value < 0 : Audit does not run (default value if property is not present = -1) -# Value = 0 : Audit runs continuously -# Value > 0 : The period of time in seconds between execution of the audit on a particular node -#integrity_audit_period_seconds=-1 -integrity_audit_period_seconds=0 - -ENVIRONMENT=DEVL diff --git a/ECOMP-PDP-REST/config/policyLogger.properties b/ECOMP-PDP-REST/config/policyLogger.properties deleted file mode 100644 index d4e9525b8..000000000 --- a/ECOMP-PDP-REST/config/policyLogger.properties +++ /dev/null @@ -1,44 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP-REST -# ================================================================================ -# 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========================================================= -### - -################################### Set concurrentHashMap and timer info ####################### -#Timer initial delay and the delay between in milliseconds before task is to be execute. -timer.delay.time=1000 -#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. -check.interval= 30000 -#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. -event.expired.time=86400 -#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed -#to remove all expired records from this concurrentHashMap. -concurrentHashMap.limit=5000 -#Size of the concurrentHashMap - when its size drops to this point, stop the Timer -stop.check.point=2500 -################################### Set logging format ############################################# -# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println -logger.type=EELF -#################################### Set level for EELF or SYSTEMOUT logging ################################## -# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all -debugLogger.level=INFO -# Set level for metrics file. Set OFF to disable; set ON to enable -metricsLogger.level=ON -# Set level for error file. Set OFF to disable; set ON to enable -error.level=ON -# Set level for audit file. Set OFF to disable; set ON to enable -audit.level=ON diff --git a/ECOMP-PDP-REST/policyLogger.properties b/ECOMP-PDP-REST/policyLogger.properties deleted file mode 100644 index d4e9525b8..000000000 --- a/ECOMP-PDP-REST/policyLogger.properties +++ /dev/null @@ -1,44 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP-REST -# ================================================================================ -# 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========================================================= -### - -################################### Set concurrentHashMap and timer info ####################### -#Timer initial delay and the delay between in milliseconds before task is to be execute. -timer.delay.time=1000 -#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. -check.interval= 30000 -#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. -event.expired.time=86400 -#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed -#to remove all expired records from this concurrentHashMap. -concurrentHashMap.limit=5000 -#Size of the concurrentHashMap - when its size drops to this point, stop the Timer -stop.check.point=2500 -################################### Set logging format ############################################# -# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println -logger.type=EELF -#################################### Set level for EELF or SYSTEMOUT logging ################################## -# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all -debugLogger.level=INFO -# Set level for metrics file. Set OFF to disable; set ON to enable -metricsLogger.level=ON -# Set level for error file. Set OFF to disable; set ON to enable -error.level=ON -# Set level for audit file. Set OFF to disable; set ON to enable -audit.level=ON diff --git a/ECOMP-PDP-REST/pom.xml b/ECOMP-PDP-REST/pom.xml deleted file mode 100644 index 142d81bc9..000000000 --- a/ECOMP-PDP-REST/pom.xml +++ /dev/null @@ -1,223 +0,0 @@ - - - - - 4.0.0 - - - org.openecomp.policy.engine - PolicyEngineSuite - 1.1.0-SNAPSHOT - - - ECOMP-PDP-REST - - ECOMP PDP REST - - 4.3.3.RELEASE - - war - - - - maven-war-plugin - 2.1 - - true - - - - - - - org.openecomp.policy.engine - ECOMP-PDP - ${project.version} - - - commons-logging - commons-logging - 1.1.3 - - - javax.servlet - servlet-api - - - - - log4j - apache-log4j-extras - 1.2.17 - - - commons-io - commons-io - 2.4 - - - com.google.guava - guava - 19.0 - - - mysql - mysql-connector-java - 5.1.30 - - - org.mariadb.jdbc - mariadb-java-client - 1.2.3 - - - postgresql - postgresql - 9.1-901.jdbc4 - - - org.springframework - spring-test - ${springframework.version} - test - - - org.awaitility - awaitility - 3.0.0 - test - - - org.hsqldb - hsqldb - 2.3.2 - - - com.sun.jersey - jersey-client - 1.18 - - - com.sun.jersey - jersey-core - 1.18 - - - junit - junit - 4.12 - test - - - javax.websocket - javax.websocket-api - 1.1 - provided - - - com.att.nsa - cambriaClient - 0.0.1 - - - slf4j-log4j12 - org.slf4j - - - - - org.mockito - mockito-core - 1.9.5 - - - org.springframework - spring-mock - 2.0.8 - - - com.mockrunner - mockrunner - 0.3.1 - - - org.powermock - powermock-api-mockito - 1.5.6 - - - org.powermock - powermock-module-junit4 - 1.5.6 - - - org.springframework - spring-core - ${springframework.version} - - - org.springframework - spring-web - ${springframework.version} - - - org.springframework - spring-webmvc - ${springframework.version} - - - io.springfox - springfox-swagger2 - 2.5.0 - - - com.fasterxml.jackson.core - jackson-annotations - - - - - io.springfox - springfox-swagger-ui - 2.5.0 - - - org.openecomp.policy.engine - PolicyEngineAPI - ${project.version} - - - org.glassfish.tyrus - tyrus-client - - - org.glassfish.tyrus - tyrus-container-grizzly-client - - - javax.persistence - persistence-api - - - - - \ No newline at end of file diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java deleted file mode 100644 index 924c2b5ff..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/PapUrlResolver.java +++ /dev/null @@ -1,377 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest; - -import java.net.URI; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.NoSuchElementException; -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 com.att.research.xacml.util.XACMLProperties; - -public class PapUrlResolver { - private static final Logger LOGGER = FlexLogger.getLogger(PapUrlResolver.class); - //how long to keep a pap failed before making it un-failed, in milli-seconds - private static final long FAIL_TIMEOUT = 18000000; - - //thread locks - public static final Object propertyLock = new Object(); - - //keeping this here for backward compatibility - public static String extractIdFromUrl(String url){ - return extractQuery(url); - } - public static String extractQuery(String url){ - try{ - return URI.create(url).getQuery(); - } catch(Exception e){ - LOGGER.error("Exception occured while extracting query. So, empty string is returned"+e); - return ""; - } - } - public static String modifyUrl(String idUrl, String serverUrl){ - URI one = URI.create(idUrl); - String host = one.getPath()+one.getQuery(); - URI two = URI.create(serverUrl); - two.resolve(host); - return two.toString(); - } - - //get an instance of a new PapUrlResolver, using XACMLProperties to get the url lists - public static PapUrlResolver getInstance(){ - return new PapUrlResolver(null,null,null,true); - } - - //get an instance of a new PapUrlResolver, using the provides strings for the url lists - public static PapUrlResolver getInstance(String urlList, String failedList, String succeededList){ - return new PapUrlResolver(urlList, failedList, succeededList,false); - } - - //keeps track of our current location in the list of urls, allows for iterating - private int pointer; - - //should the XACML property lists be updated after anything changes or should we wait for the update - //method to be called. - private boolean autoUpdateProperties; - - //this list keeps the sorted, priority of PAP URLs - private PapUrlNode[] sortedUrlNodes; - //this list keeps the original list of nodes so that they can be entered into the property list correctly - private PapUrlNode[] originalUrlNodes; - - //private constructor to make an instance of a PapUrlResolver, called by static method getInstance. - //If the list property strings are not defined, we get the values from XACMLProperties. - //The instance acts as an iterator, with hasNext and next methods, but does not implement Iterable, - //because it is used for a difference purpose. - private PapUrlResolver(String urlList, String failedList, String succeededList, boolean autoUpdateProperties){ - this.autoUpdateProperties = autoUpdateProperties; - String papUrlLists = urlList; - String papUrlFailedList = failedList; - String papUrlSuccessList = succeededList; - if(papUrlLists == null){ - papUrlLists = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS); - if(papUrlLists == null){ - papUrlLists = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); - } - papUrlFailedList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); - papUrlSuccessList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); - } - - String[] urls = papUrlLists.split(","); - if(urls.length == 0){ - //log error - } - String[] failed = emptyOrSplit(papUrlFailedList,urls.length); - String[] succeeded = emptyOrSplit(papUrlSuccessList,urls.length); - - sortedUrlNodes = new PapUrlNode[urls.length]; - for(int i=0;i { - private String papUrl; - private Date failedTime; - private Date succeededTime; - private String userId; - private String pass; - - public PapUrlNode(String url,String userId,String pass){ - this.papUrl = url; - failedTime = null; - this.succeededTime = null; - this.userId = userId; - this.pass = pass; - - } - public String getUserId(){ - return this.userId; - } - public String getPass(){ - return this.pass; - } - - public void setFailedTime(Object time){ - Date failedTimeAsDate = setHandler(time); - if(failedTimeAsDate == null){ - this.failedTime = null; - } else { - long timeDifference = new Date().getTime() - failedTimeAsDate.getTime(); - if(timeDifference < FAIL_TIMEOUT){ - this.failedTime = failedTimeAsDate; - } else { - this.failedTime = null; - } - } - } - - //set the time that this url succeeded at - public void setSucceededTime(Object time){ - this.succeededTime = setHandler(time); - } - - //parses string into a date or a null date, if the url never failed/succeeded (since -1 will be in the property) - private Date setHandler(Object time){ - if(time instanceof String){ - if("-1".equals((String)time)){ - return null; - } - try { - DateFormat df = new SimpleDateFormat(); - return df.parse((String)time); - } catch (ParseException e) { - return null; - } - } - if(time instanceof Date){ - return (Date)time; - } - return null; - } - - - public String getFailedTime(){ - return formatTime(this.failedTime); - } - - public String getSucceededTime(){ - return formatTime(this.succeededTime); - } - - //formats a Date into a string or a -1 if there is not date (-1 is used in properties for no date) - private String formatTime(Date d){ - if(d == null){ - return "-1"; - } - DateFormat df = new SimpleDateFormat(); - return df.format(d); - } - - public String getUrl(){ - return papUrl; - } - - @Override - public int compareTo(PapUrlNode other){ - if(this.failedTime == null && other.failedTime != null){ - return -1; - } - if(this.failedTime != null && other.failedTime == null){ - return 1; - } - if(this.failedTime != null){ - return this.failedTime.compareTo(other.failedTime); - } - return 0; - } - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java deleted file mode 100644 index 5288d30aa..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpLoader.java +++ /dev/null @@ -1,645 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; -import java.net.URLConnection; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Base64; -import java.util.ConcurrentModificationException; -import java.util.HashMap; -import java.util.Properties; -import java.util.Set; - -import org.apache.commons.io.IOUtils; -import org.openecomp.policy.pdp.rest.notifications.NotificationController; -import org.openecomp.policy.rest.XACMLRest; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDPStatus; -import com.att.research.xacml.api.pap.PDPStatus.Status; -import com.att.research.xacml.api.pdp.PDPEngine; -import com.att.research.xacml.api.pdp.PDPEngineFactory; -import com.att.research.xacml.api.pip.PIPEngine; -import com.att.research.xacml.api.pip.PIPException; -import com.att.research.xacml.api.pip.PIPFinder; -import com.att.research.xacml.api.pip.PIPFinderFactory; -import org.openecomp.policy.xacml.std.pap.StdPDPPIPConfig; -import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; -import org.openecomp.policy.xacml.std.pap.StdPDPStatus; -import com.att.research.xacml.util.FactoryException; -import com.att.research.xacml.util.XACMLProperties; -import com.att.research.xacmlatt.pdp.policy.PolicyDef; -import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef; -import com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory; -import com.google.common.base.Splitter; - -/** - * Does the work for loading policy and PIP configurations sent from the PAP - * servlet. - * - * - * - */ -public class XACMLPdpLoader { - private static final Logger LOGGER = FlexLogger.getLogger(XACMLPdpLoader.class); - private static NotificationController notificationController = new NotificationController(); - private static final Long notifyDelay = (long) XACMLPdpServlet.getNotificationDelay(); - - - public static synchronized PDPEngine loadEngine(StdPDPStatus status, - Properties policyProperties, Properties pipProperties) { - LOGGER.info("loadEngine: " + policyProperties + " " + pipProperties); - // - // First load our policies - // - try { - // - // Were we given some properties? - // - if (policyProperties == null) { - // - // On init we have no incoming configuration, so just - // Load our current saved configuration - // - policyProperties = new Properties(); - try (InputStream is = Files.newInputStream(getPDPPolicyCache())) { - policyProperties.load(is); - } - } - - // - // Get our policy cache up-to-date - // - // Side effects of this include: - // - downloading of policies from remote locations, and - // - creating new ".file" properties for files existing - // local - // - XACMLPdpLoader.cachePolicies(policyProperties); - // - // Validate the policies - // - XACMLPdpLoader.validatePolicies(policyProperties, status); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Status: " + status); - } - } catch (ConcurrentModificationException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e.getMessage() + e); - } catch (Exception e) { - String error = "Failed to load Policy Cache properties file: " - + e.getMessage(); - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + error, e); - status.addLoadError(error); - status.setStatus(PDPStatus.Status.LOAD_ERRORS); - } - // - // Load our PIP configuration - // - try { - // - // Were we given some properties to use? - // - if (pipProperties == null) { - // - // Load our current saved configuration - // - pipProperties = new Properties(); - try (InputStream is = Files.newInputStream(getPIPConfig())) { - pipProperties.load(is); - } - } - // - // Validate our PIP configurations - // - XACMLPdpLoader.validatePipConfiguration(pipProperties, status); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Status: " + status); - } - } catch (Exception e) { - String error = "Failed to load/validate Pip Config properties file: " - + e.getMessage(); - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + error, e); - status.addLoadError(XACMLErrorConstants.ERROR_PROCESS_FLOW + error); - status.setStatus(PDPStatus.Status.LOAD_ERRORS); - } - // - // Were they validated? - // - if (status.getStatus() == Status.LOAD_ERRORS) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW +"there were load errors"); - return null; - } - // - // Reset our official properties the PDP factory - // uses to configure the PDP engine. - // - XACMLRest.loadXacmlProperties(policyProperties, pipProperties); - // - // Dump ALL our properties that we are trying to load - // - try { - LOGGER.info(XACMLProperties.getProperties().toString()); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to get XACML Properties", e); - } - // - // Now load the PDP engine - // - PDPEngineFactory factory = null; - PDPEngine engine = null; - try { - factory = PDPEngineFactory.newInstance(); - engine = factory.newEngine(); - LOGGER.info("Loaded new PDP engine."); - status.setStatus(Status.UP_TO_DATE); - } catch (FactoryException e) { - String error = "Failed to create new PDP Engine"; - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +error, e); - status.addLoadError(error); - } - // Notification will be Sent Here. - sendNotification(); - return engine; - } - - private static HashMap policyContainer = null; - - private static void sendNotification(){ - Thread notify = new Thread(){ - public void run(){ - try{ - Thread.sleep(notifyDelay); - NotificationController.sendNotification(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_UNKNOWN + e); - } - } - }; - notify.start(); - } - - public static synchronized void validatePolicies(Properties properties, - StdPDPStatus status) throws PAPException { - Set rootPolicies = XACMLProperties.getRootPolicyIDs(properties); - Set refPolicies = XACMLProperties - .getReferencedPolicyIDs(properties); - policyContainer = new HashMap(); - - for (String id : rootPolicies) { - loadPolicy(properties, status, id, true); - } - // remember which policies were root policies - status.addAllLoadedRootPolicies(status.getLoadedPolicies()); - - for (String id : refPolicies) { - loadPolicy(properties, status, id, false); - } - LOGGER.info("Loaded " + status.getLoadedPolicies().size() - + " policies, failed to load " - + status.getFailedPolicies().size() + " policies, " - + status.getLoadedRootPolicies().size() + " root policies"); - notificationController.check(status, policyContainer); - if (status.getLoadedRootPolicies().size() == 0) { - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW +"NO ROOT POLICIES LOADED!!! Cannot serve PEP Requests."); - status.addLoadWarning("NO ROOT POLICIES LOADED!!! Cannot serve PEP Requests."); - } - policyContainer.clear(); - } - - - public static synchronized void loadPolicy(Properties properties, - StdPDPStatus status, String id, boolean isRoot) throws PAPException { - PolicyDef policy = null; - String location = null; - URI locationURI = null; - boolean isFile = false; - boolean rougeFile = false; - try { - location = properties.getProperty(id + ".file"); - if(location != null){ - isFile = true; - locationURI = Paths.get(location).toUri(); - try (InputStream is = Files.newInputStream(Paths.get(location))) { - policy = DOMPolicyDef.load(is); - } catch (Exception e){ - // This Happens if a any issue with the error policyFile. Lets remove it. - try { - LOGGER.error("Corrupted policy file, deleting: " + location + e); - Files.delete(Paths.get(location)); - properties.remove(id + ".file"); - rougeFile = true; - } catch (IOException e1) { - LOGGER.error(e1); - } - } - } - if(location==null || rougeFile){ - if(rougeFile){ - rougeFile = false; - } - location = properties.getProperty(id + ".url"); - if (location != null) { - // - // Construct the URL - // - int errorCount=0; - boolean error= false; - do{ - error=false; - PapUrlResolver papUrls = PapUrlResolver.getInstance(); - while(papUrls.hasMoreUrls()){ - String papID = papUrls.getUserId(); - String papPass = papUrls.getPass(); - Base64.Encoder encoder = Base64.getEncoder(); - String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); - locationURI = URI.create(papUrls.getUrl(PapUrlResolver.extractIdFromUrl(location))); - URL url = locationURI.toURL(); - URLConnection urlConnection = null; - try{ - urlConnection = url.openConnection(); - } catch (IOException e){ - LOGGER.error("Exception Occured while opening connection" +e); - papUrls.failed(); - papUrls.getNext(); - break; - } - urlConnection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID, - XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID)); - urlConnection.setRequestProperty("Authorization", "Basic " + encoding); - // - // Now construct the output file name - // - Path outFile = Paths.get(getPDPConfig().toAbsolutePath() - .toString(), id); - // - // Copy it to disk - // - try (FileOutputStream fos = new FileOutputStream( - outFile.toFile())) { - IOUtils.copy(urlConnection.getInputStream(), fos); - } catch(IOException e){ - LOGGER.error("Exception Occured while Copying input stream" +e); - papUrls.failed(); - papUrls.getNext(); - break; - } - // - // Now try to load - // - isFile = true; - try (InputStream fis = Files.newInputStream(outFile)) { - policy = DOMPolicyDef.load(fis); - }catch(Exception e){ - try { - LOGGER.error("Corrupted policy file, deleting: " + location +e); - Files.delete(outFile); - error = true; - errorCount++; - break; - } catch (IOException e1) { - LOGGER.error(e1); - } - } - // - // Save it - // - properties.setProperty(id + ".file", outFile - .toAbsolutePath().toString()); - error = false; - break; - } - }while(error && errorCount>2); - } - } - if (policy != null) { - status.addLoadedPolicy(new StdPDPPolicy(id, isRoot, - locationURI, properties)); - LOGGER.info("Loaded policy: " + policy.getIdentifier() - + " version: " + policy.getVersion().stringValue()); - // Sending the policy objects to the Notification Controller. - policyContainer.put(id, policy); - } else { - String error = "Failed to load policy " + location; - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + error); - status.setStatus(PDPStatus.Status.LOAD_ERRORS); - status.addLoadError(error); - status.addFailedPolicy(new StdPDPPolicy(id, isRoot)); - } - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW +"Failed to load policy '" + id + "' from location '" - + location + "'", e); - status.setStatus(PDPStatus.Status.LOAD_ERRORS); - status.addFailedPolicy(new StdPDPPolicy(id, isRoot)); - // - // Is it a file? - // - if (isFile) { - // - // Let's remove it - // - try { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Corrupted policy file, deleting: " + location); - Files.delete(Paths.get(location)); - - } catch (IOException e1) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e1); - } - } - } - } - - public static synchronized void validatePipConfiguration( - Properties properties, StdPDPStatus status) throws PAPException { - try { - PIPFinderFactory factory = PIPFinderFactory.newInstance(properties); - if (factory == null) { - throw new FactoryException( - "Could not create PIP Finder Factory: " - + properties - .getProperty(XACMLProperties.PROP_PIPFINDERFACTORY)); - } - PIPFinder finder = factory.getFinder(properties); - // - // Check for this, although it should always return something - // - if (finder == null) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "pip finder factory returned a null engine."); - throw new PIPException("Could not create PIP Finder"); - } else { - LOGGER.info("Loaded PIP finder"); - } - for (PIPEngine engine : finder.getPIPEngines()) { - LOGGER.info("Configured PIP Engine: " + engine.getName()); - StdPDPPIPConfig config = new StdPDPPIPConfig(); - config.setName(engine.getName()); - status.addLoadedPipConfig(config); - } - } catch (FactoryException | PIPException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "validate PIP configuration failed: " - + e.getLocalizedMessage()); - status.addLoadError(e.getLocalizedMessage()); - status.setStatus(Status.LOAD_ERRORS); - throw new PAPException(e); - } - } - - /** - * Iterates the policies defined in the props object to ensure they are - * loaded locally. Policies are searched for in the following order: - see - * if the current properties has a "<PolicyID>.file" entry and that - * file exists in the local directory - if not, see if the file exists in - * the local directory; if so create a ".file" property for it. - if not, - * get the "<PolicyID>.url" property and try to GET the policy from - * that location (and set the ".file" property) - * - * If the ".file" property is created, then true is returned to tell the - * caller that the props object changed. - * - * @param props - * @return true/false if anything was changed in the props object - * @throws PAPException - */ - public static synchronized boolean cachePolicies(Properties props) - throws PAPException { - boolean changed = false; - String[] lists = new String[2]; - lists[0] = props.getProperty(XACMLProperties.PROP_ROOTPOLICIES); - lists[1] = props.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); - for (String list : lists) { - // - // Check for a null or empty parameter - // - if (list == null || list.length() == 0) { - continue; - } - Iterable policies = Splitter.on(',').trimResults() - .omitEmptyStrings().split(list); - for (String policy : policies) { - boolean policyExists = false; - - // First look for ".file" property and verify the file exists - String propLocation = props.getProperty(policy - + StdPolicyFinderFactory.PROP_FILE); - if (propLocation != null) { - // - // Does it exist? - // - policyExists = Files.exists(Paths.get(propLocation)); - if (policyExists == false) { - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy file " + policy + " expected at " - + propLocation + " does NOT exist."); - } - } - - // If ".file" property does not exist, try looking for the local - // file anyway - // (it might exist without having a ".file" property set for it) - if (policyExists == false) { - // - // Now construct the output file name - // - Path outFile = Paths.get(getPDPConfig().toAbsolutePath() - .toString(), policy); - // - // Double check to see if we pulled it at some point - // - policyExists = Files.exists(outFile); - if (policyExists) { - // - // Set the property so the PDP engine doesn't have - // to pull it from the URL but rather the FILE. - // - LOGGER.info("Policy does exist: " - + outFile.toAbsolutePath().toString()); - props.setProperty(policy - + StdPolicyFinderFactory.PROP_FILE, outFile - .toAbsolutePath().toString()); - // - // Indicate that there were changes made to the - // properties - // - changed = true; - } else { - - // File does not exist locally, so we need to get it - // from the location given in the ".url" property (which - // MUST exist) - - // - // There better be a URL to retrieve it - // - propLocation = props.getProperty(policy - + StdPolicyFinderFactory.PROP_URL); - if (propLocation != null) { - // - // Get it - // - PapUrlResolver papUrls = PapUrlResolver.getInstance(); - while(papUrls.hasMoreUrls()){ - String papID = papUrls.getUserId(); - String papPass = papUrls.getPass(); - Base64.Encoder encoder = Base64.getEncoder(); - String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); - URL url = null; - try { - // - // Create the URL - // - url = new URL(papUrls.getUrl(PapUrlResolver.extractIdFromUrl(propLocation))); - LOGGER.info("Pulling " + url.toString()); - // - // Open the connection - // - URLConnection urlConnection = url.openConnection(); - urlConnection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID, - XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID)); - urlConnection.setRequestProperty("Authorization", "Basic " + encoding); - // - // Copy it to disk - // - try (InputStream is = urlConnection - .getInputStream(); - OutputStream os = new FileOutputStream( - outFile.toFile())) { - IOUtils.copy(is, os); - } - // - // Now save it in the properties as a .file - // - LOGGER.info("Pulled policy: " - + outFile.toAbsolutePath().toString()); - props.setProperty(policy - + StdPolicyFinderFactory.PROP_FILE, - outFile.toAbsolutePath().toString()); - papUrls.succeeded(); - // - // Indicate that there were changes made to the - // properties - // - changed = true; - } catch (Exception e) { - papUrls.failed(); - if (e instanceof MalformedURLException) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy '" - + policy - + "' had bad URL in new configuration, URL='" - + propLocation + "'"); - - } else { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while retrieving policy " - + policy - + " from URL " - + url + ", e=" + e); - } - } - papUrls.getNext(); - } - } else { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy " + policy - + " does NOT exist and does NOT have a URL"); - } - } - } - } - } - return changed; - } - - public static synchronized Path getPDPPolicyCache() throws PAPException { - Path config = getPDPConfig(); - Path policyProperties = Paths.get(config.toAbsolutePath().toString(), - "xacml.policy.properties"); - if (Files.notExists(policyProperties)) { - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + policyProperties.toAbsolutePath().toString() - + " does NOT exist."); - // - // Try to create the file - // - try { - Files.createFile(policyProperties); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create policy properties file: " - + policyProperties.toAbsolutePath().toString() +e); - throw new PAPException( - "Failed to create policy properties file: " - + policyProperties.toAbsolutePath().toString()); - } - } - return policyProperties; - } - - public static synchronized Path getPIPConfig() throws PAPException { - Path config = getPDPConfig(); - Path pipConfigProperties = Paths.get( - config.toAbsolutePath().toString(), "xacml.pip.properties"); - if (Files.notExists(pipConfigProperties)) { - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + pipConfigProperties.toAbsolutePath().toString() - + " does NOT exist."); - // - // Try to create the file - // - try { - Files.createFile(pipConfigProperties); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create pip properties file: " - + pipConfigProperties.toAbsolutePath().toString() +e); - throw new PAPException("Failed to create pip properties file: " - + pipConfigProperties.toAbsolutePath().toString()); - } - } - return pipConfigProperties; - } - - public static synchronized Path getPDPConfig() throws PAPException { - Path config = Paths.get(XACMLProperties - .getProperty(XACMLRestProperties.PROP_PDP_CONFIG)); - if (Files.notExists(config)) { - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + config.toAbsolutePath().toString() + " does NOT exist."); - // - // Try to create the directory - // - try { - Files.createDirectories(config); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: " - + config.toAbsolutePath().toString(), e); - throw new PAPException("Failed to create config directory: " - + config.toAbsolutePath().toString()); - } - } - return config; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpRegisterThread.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpRegisterThread.java deleted file mode 100644 index 6bc8a6461..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpRegisterThread.java +++ /dev/null @@ -1,285 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.Base64; -import java.util.Properties; -import java.util.UUID; - -import org.apache.commons.io.IOUtils; -import org.openecomp.policy.pdp.rest.XACMLPdpServlet.PutRequest; -import org.openecomp.policy.rest.XACMLRestProperties; - -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import com.att.research.xacml.util.XACMLProperties; - -import org.openecomp.policy.common.logging.ECOMPLoggingContext; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.*; - -public class XACMLPdpRegisterThread implements Runnable { - private static final Logger LOGGER = FlexLogger.getLogger(XACMLPdpRegisterThread.class); - private static final Logger auditLogger = FlexLogger.getLogger("auditLogger"); - private ECOMPLoggingContext baseLoggingContext = null; - - - - public volatile boolean isRunning = false; - - public XACMLPdpRegisterThread(ECOMPLoggingContext baseLoggingContext) { - this.baseLoggingContext = baseLoggingContext; - } - - public synchronized boolean isRunning() { - return this.isRunning; - } - - public synchronized void terminate() { - this.isRunning = false; - } - - /** - * - * This is our thread that runs on startup to tell the PAP server we are up-and-running. - * - */ - @Override - public void run() { - synchronized(this) { - this.isRunning = true; - } - // get a new logging context for the thread - ECOMPLoggingContext loggingContext = new ECOMPLoggingContext(baseLoggingContext); - loggingContext.setServiceName("PDP:PAP.register"); - //are we registered with at least one - boolean registered = false; - boolean interrupted = false; - /* - int seconds; - try { - seconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_SLEEP)); - } catch (NumberFormatException e) { - LOGGER.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR +"REGISTER_SLEEP: ", e); - seconds = 5; - } - if (seconds < 5) { - seconds = 5; - } - int retries; - try { - retries = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_RETRIES)); - } catch (NumberFormatException e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +" REGISTER_SLEEP: ", e); - retries = -1; - } - */ - PapUrlResolver papUrls = PapUrlResolver.getInstance(); - //while (! registered && ! interrupted && this.isRunning()) { - String tempRootPoliciesProperty = XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES); - String tempReferencedPoliciesProperty = XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); - Properties tempPipConfigProperties = new Properties(); - try(InputStream pipFile = Files.newInputStream(XACMLPdpLoader.getPIPConfig())){ - tempPipConfigProperties.load(pipFile); - } catch(Exception e){ - LOGGER.error("Failed to open PIP property file", e); - } - while(papUrls.hasMoreUrls()){ - String papID = papUrls.getUserId(); - String papPass = papUrls.getPass(); - Base64.Encoder encoder = Base64.getEncoder(); - String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); - HttpURLConnection connection = null; - try { - // get a new transaction (request) ID and update the logging context. - // each time through the outer loop is considered a new transaction. - // each time through the inner loop (which handles redirects) is a - // continuation of the same transaction. - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - //PolicyLogger.info("Request Id generated in XACMLPdpRegisterThread under XACML-PDP-REST"); - loggingContext.transactionStarted(); - // - // Get the list of PAP Servlet URLs from the property file - // - //String papUrlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); - //String[] papUrls = papUrlList.split(","); - //PapUrlResolver.setPapUrls(papUrls); - URL url = new URL(papUrls.getUrl()); - LOGGER.info("Registering with " + url.toString()); - //PolicyLogger.info("new transaction (request) ID and update to logging context in XACMLPdpRegisterThread"); - boolean finished = false; - while (! finished) { - // - // Open up the connection - // - connection = (HttpURLConnection)url.openConnection(); - // - // Setup our method and headers - // - connection.setRequestMethod("POST"); - connection.setRequestProperty("Authorization", "Basic " + encoding); - connection.setRequestProperty("Accept", "text/x-java-properties"); - connection.setRequestProperty("Content-Type", "text/x-java-properties"); - connection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID, XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID)); - connection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT, XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_JMX_PORT)); - connection.setRequestProperty("X-ECOMP-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 { - // - // Send our current policy configuration - // - String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + tempRootPoliciesProperty; - lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + tempReferencedPoliciesProperty + "\n"; - try (InputStream listsInputStream = new ByteArrayInputStream(lists.getBytes()); - OutputStream os = connection.getOutputStream()) { - IOUtils.copy(listsInputStream, os); - - // - // Send our current PIP configuration - // - //IOUtils.copy(pipInputStream, os); - tempPipConfigProperties.store(os, ""); - } - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Failed to send property file", e); - } - // - // Do the connect - // - connection.connect(); - if (connection.getResponseCode() == 204) { - LOGGER.info("Success. We are configured correctly."); - loggingContext.transactionEnded(); - PolicyLogger.audit("Success. We are configured correctly."); - papUrls.registered(); - finished = true; - registered = true; - } else if (connection.getResponseCode() == 200) { - LOGGER.info("Success. We have a new configuration."); - loggingContext.transactionEnded(); - PolicyLogger.audit("Success. We have a new configuration."); - papUrls.registered(); - Properties properties = new Properties(); - properties.load(connection.getInputStream()); - LOGGER.info("New properties: " + properties.toString()); - // - // Queue it - // - // The incoming properties does NOT include urls - Properties returnedPolicyProperties = XACMLProperties.getPolicyProperties(properties, false); - tempRootPoliciesProperty = new String(returnedPolicyProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES)); - tempReferencedPoliciesProperty = new String(returnedPolicyProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)); - Properties returnedPipProperties = XACMLProperties.getPipProperties(properties); - Properties threadSafeReturnedPipProperties = new Properties(); - ByteArrayOutputStream threadSafeReturnedPipPropertiesOs = new ByteArrayOutputStream(); - returnedPipProperties.store(threadSafeReturnedPipPropertiesOs, ""); - InputStream threadSafeReturnedPipPropertiesIs = new ByteArrayInputStream(threadSafeReturnedPipPropertiesOs.toByteArray()); - threadSafeReturnedPipProperties.load(threadSafeReturnedPipPropertiesIs); - tempPipConfigProperties = threadSafeReturnedPipProperties; - - PutRequest req = new PutRequest(returnedPolicyProperties,returnedPipProperties); - XACMLPdpServlet.queue.offer(req); - // - // We are now registered - // - finished = true; - registered=true; - } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { - // - // Re-direction - // - String newLocation = connection.getHeaderField("Location"); - if (newLocation == null || newLocation.isEmpty()) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Did not receive a valid re-direction location"); - loggingContext.transactionEnded(); - auditLogger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Did not receive a valid re-direction location"); - PolicyLogger.audit("Transaction Failed - See Error.log"); - finished = true; - } else { - LOGGER.info("New Location: " + newLocation); - url = new URL(newLocation); - } - } else { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); - loggingContext.transactionEnded(); - auditLogger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); - PolicyLogger.audit("Transaction Failed - See Error.log"); - finished = true; - papUrls.failed(); - } - } - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - PolicyLogger.audit("Transaction Failed - See Error.log"); - loggingContext.transactionEnded(); - papUrls.failed(); - } 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(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to get Input Stream: " + e1); - } - if (is != null) { - is.close(); - } - - } catch (IOException ex) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to close connection: " + ex, ex); - } - connection.disconnect(); - } - } - - papUrls.getNext(); - } - synchronized(this) { - this.isRunning = false; - } - LOGGER.info("Thread exiting...(registered=" + registered + ", interrupted=" + interrupted + ", isRunning=" + this.isRunning() + ", retries=" + "0" + ")"); - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpServlet.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpServlet.java deleted file mode 100644 index bad8e6638..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/XACMLPdpServlet.java +++ /dev/null @@ -1,1266 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.lang.reflect.Constructor; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.nio.file.Files; -import java.util.Properties; -import java.util.UUID; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; - -import javax.servlet.Servlet; -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.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.entity.ContentType; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.common.im.AdministrativeStateException; -import org.openecomp.policy.common.im.ForwardProgressException; -import org.openecomp.policy.common.im.IntegrityMonitor; -import org.openecomp.policy.common.im.IntegrityMonitorProperties; -import org.openecomp.policy.common.im.StandbyStatusException; -import org.openecomp.policy.common.logging.ECOMPLoggingContext; -import org.openecomp.policy.common.logging.ECOMPLoggingUtils; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.pdp.rest.jmx.PdpRestMonitor; -import org.openecomp.policy.rest.XACMLRest; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.pdp.std.functions.PolicyList; -import org.openecomp.policy.xacml.std.pap.StdPDPStatus; - -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.Response; -import com.att.research.xacml.api.pap.PDPStatus.Status; -import com.att.research.xacml.api.pdp.PDPEngine; -import com.att.research.xacml.api.pdp.PDPException; -import com.att.research.xacml.std.dom.DOMRequest; -import com.att.research.xacml.std.dom.DOMResponse; -import com.att.research.xacml.std.json.JSONRequest; -import com.att.research.xacml.std.json.JSONResponse; -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * Servlet implementation class XacmlPdpServlet - * - * This is an implementation of the XACML 3.0 RESTful Interface with added features to support - * simple PAP RESTful API for policy publishing and PIP configuration changes. - * - * If you are running this the first time, then we recommend you look at the xacml.pdp.properties file. - * This properties file has all the default parameter settings. If you are running the servlet as is, - * then we recommend setting up you're container to run it on port 8080 with context "/pdp". Wherever - * the default working directory is set to, a "config" directory will be created that holds the policy - * and pip cache. This setting is located in the xacml.pdp.properties file. - * - * When you are ready to customize, you can create a separate xacml.pdp.properties on you're local file - * system and setup the parameters as you wish. Just set the Java VM System variable to point to that file: - * - * -Dxacml.properties=/opt/app/xacml/etc/xacml.pdp.properties - * - * Or if you only want to change one or two properties, simply set the Java VM System variable for that property. - * - * -Dxacml.rest.pdp.register=false - * - * - */ -@WebServlet( - description = "Implements the XACML PDP RESTful API and client PAP API.", - urlPatterns = { "/" }, - loadOnStartup=1, - initParams = { - @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pdp.properties", description = "The location of the PDP xacml.pdp.properties file holding configuration information.") - }) -public class XACMLPdpServlet extends HttpServlet implements Runnable { - private static final long serialVersionUID = 1L; - private static final String DEFAULT_MAX_CONTENT_LENGTH = "999999999"; //32767 - private static final String CREATE_UPDATE_POLICY_SERVICE = "org.openecomp.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl"; - // - // Our application debug log - // - private static final Log logger = LogFactory.getLog(XACMLPdpServlet.class); - // - // This logger is specifically only for Xacml requests and their corresponding response. - // It's output ideally should be sent to a separate file from the application logger. - // - private static final Log requestLogger = LogFactory.getLog("xacml.request"); - // - // audit logger - private static final Log auditLogger = LogFactory.getLog("auditLogger"); - - private static final PdpRestMonitor monitor = PdpRestMonitor.getSingleton(); - - // - // This thread may getting invoked on startup, to let the PAP know - // that we are up and running. - // - private Thread registerThread = null; - private XACMLPdpRegisterThread registerRunnable = null; - // - // This is our PDP engine pointer. There is a synchronized lock used - // for access to the pointer. In case we are servicing PEP requests while - // an update is occurring from the PAP. - // - private static PDPEngine pdpEngine = null; - private static final Object pdpEngineLock = new Object(); - // - // This is our PDP's status. What policies are loaded (or not) and - // what PIP configurations are loaded (or not). - // There is a synchronized lock used for access to the object. - // - private static volatile StdPDPStatus status = new StdPDPStatus(); - private static final Object pdpStatusLock = new Object(); - private static Constructor createUpdatePolicyConstructor; - - private static final String ENVIORNMENT_HEADER = "Environment"; - private static String environment = null; - // - // Queue of PUT requests - // - public static class PutRequest { - private Properties policyProperties = null; - private Properties pipConfigProperties = null; - - PutRequest(Properties policies, Properties pips) { - this.policyProperties = policies; - this.pipConfigProperties = pips; - } - } - protected static volatile BlockingQueue queue = null; - // For notification Delay. - private static int notificationDelay = 0; - public static int getNotificationDelay(){ - return XACMLPdpServlet.notificationDelay; - } - - private static String pdpResourceName; - private static String[] dependencyNodes = null; - - // - // This is our configuration thread that attempts to load - // a new configuration request. - // - private Thread configThread = null; - private volatile boolean configThreadTerminate = false; - private ECOMPLoggingContext baseLoggingContext = null; - private IntegrityMonitor im; - /** - * Default constructor. - */ - public XACMLPdpServlet() { - //Default constructor. - } - - /** - * @see Servlet#init(ServletConfig) - */ - @Override - public void init(ServletConfig config) throws ServletException { - String createUpdateResourceName = null; - String dependencyGroups = null; - // - // Initialize - // - XACMLRest.xacmlInit(config); - // Load the Notification Delay. - try{ - XACMLPdpServlet.notificationDelay = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY)); - }catch(Exception e){ - logger.info("Notification Delay Not set. Keeping it 0 as default."+e); - } - // Load Queue size. - int queueSize = 5; // Set default Queue Size here. - queueSize = Integer.parseInt(XACMLProperties.getProperty("REQUEST_BUFFER_SIZE",String.valueOf(queueSize))); - queue = new LinkedBlockingQueue(queueSize); - // Load our engine - this will use the latest configuration - // that was saved to disk and set our initial status object. - // - PDPEngine engine = XACMLPdpLoader.loadEngine(XACMLPdpServlet.status, null, null); - if (engine != null) { - synchronized(pdpEngineLock) { - pdpEngine = engine; - } - } - // - // Logging stuff.... - // - baseLoggingContext = new ECOMPLoggingContext(); - // fixed data that will be the same in all logging output goes here - try { - String ipaddress = InetAddress.getLocalHost().getHostAddress(); - baseLoggingContext.setServer(ipaddress); - } catch (UnknownHostException e) { - logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging"+e); - } - - Properties properties; - try { - properties = XACMLProperties.getProperties(); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, - "Error loading properties with: XACMLProperties.getProperties()"); - throw new ServletException(e.getMessage(), e.getCause()); - } - if(properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME)==null){ - XACMLProperties.reloadProperties(); - try { - properties = XACMLProperties.getProperties(); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, - "Error loading properties with: XACMLProperties.getProperties()"); - throw new ServletException(e.getMessage(), e.getCause()); - } - PolicyLogger.info("\n Properties Given : \n" + properties.toString()); - } - pdpResourceName = properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME); - if(pdpResourceName == null){ - PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, XACMLRestProperties.PDP_RESOURCE_NAME, "xacml.pdp"); - throw new ServletException("pdpResourceName is null"); - } - - dependencyGroups = properties.getProperty(IntegrityMonitorProperties.DEPENDENCY_GROUPS); - if(dependencyGroups == null){ - PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, IntegrityMonitorProperties.DEPENDENCY_GROUPS, "xacml.pdp"); - throw new ServletException("dependency_groups is null"); - } - // dependency_groups is a semicolon-delimited list of groups, and - // each group is a comma-separated list of nodes. For our purposes - // we just need a list of dependencies without regard to grouping, - // so split the list into nodes separated by either comma or semicolon. - dependencyNodes = dependencyGroups.split("[;,]"); - for (int i = 0 ; i < dependencyNodes.length ; i++){ - dependencyNodes[i] = dependencyNodes[i].trim(); - } - - // CreateUpdatePolicy ResourceName - createUpdateResourceName = properties.getProperty("createUpdatePolicy.impl.className", CREATE_UPDATE_POLICY_SERVICE); - setCreateUpdatePolicyConstructor(createUpdateResourceName); - - // Create an IntegrityMonitor - try { - logger.info("Creating IntegrityMonitor"); - im = IntegrityMonitor.getInstance(pdpResourceName, properties); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to create IntegrityMonitor" +e); - throw new ServletException(e); - } - - environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); - // - // Kick off our thread to register with the PAP servlet. - // - if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER))) { - this.registerRunnable = new XACMLPdpRegisterThread(baseLoggingContext); - this.registerThread = new Thread(this.registerRunnable); - this.registerThread.start(); - } - // - // This is our thread that manages incoming configuration - // changes. - // - this.configThread = new Thread(this); - this.configThread.start(); - } - - /** - * @see Servlet#destroy() - */ - @Override - public void destroy() { - super.destroy(); - logger.info("Destroying...."); - // - // Make sure the register thread is not running - // - if (this.registerRunnable != null) { - try { - this.registerRunnable.terminate(); - if (this.registerThread != null) { - this.registerThread.interrupt(); - this.registerThread.join(); - } - } catch (InterruptedException e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); - } - } - // - // Make sure the configure thread is not running - // - this.configThreadTerminate = true; - try { - this.configThread.interrupt(); - this.configThread.join(); - } catch (InterruptedException e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); - } - logger.info("Destroyed."); - } - - /** - * PUT - The PAP engine sends configuration information using HTTP PUT request. - * - * One parameter is expected: - * - * config=[policy|pip|all] - * - * policy - Expect a properties file that contains updated lists of the root and referenced policies that the PDP should - * be using for PEP requests. - * - * Specifically should AT LEAST contain the following properties: - * xacml.rootPolicies - * xacml.referencedPolicies - * - * In addition, any relevant information needed by the PDP to load or retrieve the policies to store in its cache. - * - * EXAMPLE: - * xacml.rootPolicies=PolicyA.1, PolicyB.1 - * - * PolicyA.1.url=http://localhost:9090/PAP?id=b2d7b86d-d8f1-4adf-ba9d-b68b2a90bee1&version=1 - * PolicyB.1.url=http://localhost:9090/PAP/id=be962404-27f6-41d8-9521-5acb7f0238be&version=1 - * - * xacml.referencedPolicies=RefPolicyC.1, RefPolicyD.1 - * - * RefPolicyC.1.url=http://localhost:9090/PAP?id=foobar&version=1 - * RefPolicyD.1.url=http://localhost:9090/PAP/id=example&version=1 - * - * pip - Expect a properties file that contain PIP engine configuration properties. - * - * Specifically should AT LEAST the following property: - * xacml.pip.engines - * - * In addition, any relevant information needed by the PDP to load and configure the PIPs. - * - * EXAMPLE: - * xacml.pip.engines=foo,bar - * - * foo.classname=com.foo - * foo.sample=abc - * foo.example=xyz - * ...... - * - * bar.classname=com.bar - * ...... - * - * all - Expect ALL new configuration properties for the PDP - * - * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response) - */ - @Override - protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); - loggingContext.transactionStarted(); - if ((loggingContext.getRequestID() == null) || "".equals(loggingContext.getRequestID())){ - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPut) so we generated one"); - } else { - PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPut)"); - } - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 1 of 2"); - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 2 of 2"); - // - // Dump our request out - // - if (logger.isDebugEnabled()) { - XACMLRest.dumpRequest(request); - } - - try { - im.startTransaction(); - } - catch (AdministrativeStateException | StandbyStatusException e) { - String message = e.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + e); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - } - // - // What is being PUT? - // - String cache = request.getParameter("cache"); - // - // Should be a list of policy and pip configurations in Java properties format - // - if (cache != null && request.getContentType().equals("text/x-java-properties")) { - loggingContext.setServiceName("PDP.putConfig"); - try{ - if (request.getContentLength() > Integer.parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", DEFAULT_MAX_CONTENT_LENGTH))) { - String message = "Content-Length larger than server will accept."; - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - loggingContext.transactionEnded(); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); - im.endTransaction(); - return; - } - this.doPutConfig(cache, request, response, loggingContext); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction ended"); - - im.endTransaction(); - }catch(Exception e){ - logger.error("Exception Occured while getting Max Content lenght"+e); - } - } else { - String message = "Invalid cache: '" + cache + "' or content-type: '" + request.getContentType() + "'"; - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - } - - protected void doPutConfig(String config, HttpServletRequest request, HttpServletResponse response, ECOMPLoggingContext loggingContext) throws ServletException, IOException { - try { - // prevent multiple configuration changes from stacking up - if (XACMLPdpServlet.queue.remainingCapacity() <= 0) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Queue capacity reached"); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Queue capacity reached"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_CONFLICT, "Multiple configuration changes waiting processing."); - return; - } - // - // Read the properties data into an object. - // - Properties newProperties = new Properties(); - newProperties.load(request.getInputStream()); - // should have something in the request - if (newProperties.size() == 0) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No properties in PUT"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No properties in PUT"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT must contain at least one property"); - return; - } - // - // Which set of properties are they sending us? Whatever they send gets - // put on the queue (if there is room). - // For audit logging purposes, we consider the transaction done once the - // the request gets put on the queue. - // - if (config.equals("policies")) { - newProperties = XACMLProperties.getPolicyProperties(newProperties, true); - if (newProperties.size() == 0) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policy properties in PUT"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No policy properties in PUT"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=policies must contain at least one policy property"); - return; - } - XACMLPdpServlet.queue.offer(new PutRequest(newProperties, null)); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Success"); - } else if (config.equals("pips")) { - newProperties = XACMLProperties.getPipProperties(newProperties); - if (newProperties.size() == 0) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No pips properties in PUT"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No pips properties in PUT"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=pips must contain at least one pip property"); - return; - } - XACMLPdpServlet.queue.offer(new PutRequest(null, newProperties)); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Success"); - } else if (config.equals("all")) { - Properties newPolicyProperties = XACMLProperties.getPolicyProperties(newProperties, true); - if (newPolicyProperties.size() == 0) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policy properties in PUT"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No policy properties in PUT"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one policy property"); - return; - } - Properties newPipProperties = XACMLProperties.getPipProperties(newProperties); - if (newPipProperties.size() == 0) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No pips properties in PUT"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No pips properties in PUT"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one pip property"); - return; - } - XACMLPdpServlet.queue.offer(new PutRequest(newPolicyProperties, newPipProperties)); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Success"); - } else { - // - // Invalid value - // - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid config value: " + config); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Invalid config value: " + config); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Config must be one of 'policies', 'pips', 'all'"); - return; - } - } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to process new configuration.", e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to process new configuration"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - } - - } - - /** - * Parameters: type=hb|config|Status - * - * 1. HeartBeat Status - * HeartBeat - * OK - All Policies are Loaded, All PIPs are Loaded - * LOADING_IN_PROGRESS - Currently loading a new policy set/pip configuration - * LAST_UPDATE_FAILED - Need to track the items that failed during last update - * LOAD_FAILURE - ??? Need to determine what information is sent and how - * 2. Configuration - * 3. Status - * return the StdPDPStatus object in the Response content - * - * - * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) - */ - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); - loggingContext.transactionStarted(); - if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doGet) so we generated one"); - } else { - PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doGet)"); - } - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 1 of 2"); - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 2 of 2"); - - XACMLRest.dumpRequest(request); - - String pathInfo = request.getRequestURI(); - if (pathInfo != null){ - // health check from Global Site Selector (iDNS). - // DO NOT do a im.startTransaction for the test request - if (pathInfo.equals("/pdp/test")) { - loggingContext.setServiceName("iDNS:PDP.test"); - try { - im.evaluateSanity(); - //If we make it this far, all is well - String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is OK"; - PolicyLogger.debug(message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Success"); - response.setStatus(HttpServletResponse.SC_OK); - return; - } catch (ForwardProgressException fpe){ - //No forward progress is being made - String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is not making forward progress." - + " Exception Message: " + fpe.getMessage(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + fpe); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - }catch (AdministrativeStateException ase){ - //Administrative State is locked - String message = "GET:/pdp/test called and PDP " + pdpResourceName + " Administrative State is LOCKED " - + " Exception Message: " + ase.getMessage(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + ase); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - }catch (StandbyStatusException sse){ - //Administrative State is locked - String message = "GET:/pdp/test called and PDP " + pdpResourceName + " Standby Status is NOT PROVIDING SERVICE " - + " Exception Message: " + sse.getMessage(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + sse); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - } catch (Exception e) { - //A subsystem is not making progress or is not responding - String eMsg = e.getMessage(); - if(eMsg == null){ - eMsg = "No Exception Message"; - } - String message = "GET:/pdp/test called and PDP " + pdpResourceName + " has had a subsystem failure." - + " Exception Message: " + eMsg; - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message ); - //Get the specific list of subsystems that failed - String failedNodeList = null; - for(String node : dependencyNodes){ - if(eMsg.contains(node)){ - if(failedNodeList == null){ - failedNodeList = node; - }else{ - failedNodeList = failedNodeList.concat(","+node); - } - } - } - if(failedNodeList == null){ - failedNodeList = "UnknownSubSystem"; - } - response.addHeader("X-ECOMP-SubsystemFailure", failedNodeList); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log" + e); - return; - } - } - } - - try { - im.startTransaction(); - } - catch (AdministrativeStateException | StandbyStatusException e) { - String message = e.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log" +e); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - } - // - // What are they requesting? - // - boolean returnHB = false; - response.setHeader("Cache-Control", "no-cache"); - String type = request.getParameter("type"); - // type might be null, so use equals on string constants - if ("config".equals(type)) { - loggingContext.setServiceName("PDP.getConfig"); - response.setContentType("text/x-java-properties"); - try { - String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES, ""); - lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "") + "\n"; - try (InputStream listInputStream = new ByteArrayInputStream(lists.getBytes()); - InputStream pipInputStream = Files.newInputStream(XACMLPdpLoader.getPIPConfig()); - OutputStream os = response.getOutputStream()) { - IOUtils.copy(listInputStream, os); - IOUtils.copy(pipInputStream, os); - } - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Success"); - response.setStatus(HttpServletResponse.SC_OK); - } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to copy property file", e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to copy property file"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(400, "Failed to copy Property file"); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - } - - } else if ("hb".equals(type)) { - returnHB = true; - response.setStatus(HttpServletResponse.SC_NO_CONTENT); - - } else if ("Status".equals(type)) { - loggingContext.setServiceName("PDP.getStatus"); - // convert response object to JSON and include in the response - synchronized(pdpStatusLock) { - ObjectMapper mapper = new ObjectMapper(); - try{ - mapper.writeValue(response.getOutputStream(), status); - }catch(Exception e1){ - logger.error("Exception occured while writing output stream" +e1); - } - } - response.setStatus(HttpServletResponse.SC_OK); - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Success"); - - } else { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid type value: " + type); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Invalid type value: " + type); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "type not 'config' or 'hb'"); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - } - if (returnHB) { - synchronized(pdpStatusLock) { - response.addHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString()); - } - } - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Ended"); - im.endTransaction(); - - } - - /** - * POST - We expect XACML requests to be posted by PEP applications. They can be in the form of XML or JSON according - * to the XACML 3.0 Specifications for both. - * - * - * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) - */ - @Override - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - ECOMPLoggingContext loggingContext = ECOMPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); - loggingContext.transactionStarted(); - loggingContext.setServiceName("PDP.decide"); - if ((loggingContext.getRequestID() == null) || ("".equals(loggingContext.getRequestID()))){ - UUID requestID = UUID.randomUUID(); - loggingContext.setRequestID(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPost) so we generated one"); - } else { - PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPost)"); - } - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 1 of 2"); - loggingContext.metricStarted(); - loggingContext.metricEnded(); - PolicyLogger.metrics("Metric example posted here - 2 of 2"); - monitor.pdpEvaluationAttempts(); - - try { - im.startTransaction(); - } - catch (AdministrativeStateException | StandbyStatusException e) { - String message = e.toString(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + e); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - } - // - // no point in doing any work if we know from the get-go that we cannot do anything with the request - // - if (status.getLoadedRootPolicies().isEmpty()) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Request from PEP at " + request.getRequestURI() + " for service when PDP has No Root Policies loaded"); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "Request from PEP at " + request.getRequestURI() + " for service when PDP has No Root Policies loaded"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - - XACMLRest.dumpRequest(request); - // - // Set our no-cache header - // - response.setHeader("Cache-Control", "no-cache"); - // - // They must send a Content-Type - // - if (request.getContentType() == null) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Must specify a Content-Type"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Must specify a Content-Type"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, "no content-type given"); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - // - // Limit the Content-Length to something reasonable - // - try{ - if (request.getContentLength() > Integer.parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", "32767"))) { - String message = "Content-Length larger than server will accept."; - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); - im.endTransaction(); - return; - } - }catch(Exception e){ - logger.error("Exception occured while getting max content length"+e); - } - - if (request.getContentLength() <= 0) { - String message = "Content-Length is negative"; - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - ContentType contentType = null; - try { - contentType = ContentType.parse(request.getContentType()); - } - catch (Exception e) { - String message = "Parsing Content-Type: " + request.getContentType() + ", error=" + e.getMessage(); - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message, e); - loggingContext.transactionEnded(); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, message); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - // - // What exactly did they send us? - // - String incomingRequestString = null; - Request pdpRequest = null; - if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType()) || - contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || - contentType.getMimeType().equalsIgnoreCase("application/xacml+xml") ) { - // - // Read in the string - // - StringBuilder buffer = new StringBuilder(); - BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); - String line; - try{ - while((line = reader.readLine()) != null){ - buffer.append(line); - } - }catch(Exception e){ - logger.error("Exception Occured while reading line"+e); - } - - incomingRequestString = buffer.toString(); - logger.info(incomingRequestString); - // - // Parse into a request - // - try { - if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { - pdpRequest = JSONRequest.load(incomingRequestString); - } else if ( contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || - contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { - pdpRequest = DOMRequest.load(incomingRequestString); - } - } - catch(Exception e) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not parse request", e); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "Could not parse request"); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - } else { - String message = "unsupported content type" + request.getContentType(); - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - // - // Did we successfully get and parse a request? - // - if (pdpRequest == null || pdpRequest.getRequestAttributes() == null || pdpRequest.getRequestAttributes().size() <= 0) { - String message = "Zero Attributes found in the request"; - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - // - // Run it - // - try { - // - // Authenticating the Request here. - // - if(!authorizeRequest(request)){ - String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; - logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + message ); - PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_FORBIDDEN, message); - im.endTransaction(); - return; - } - // - // Get the pointer to the PDP Engine - // - PDPEngine myEngine = null; - synchronized(pdpEngineLock) { - myEngine = XACMLPdpServlet.pdpEngine; - } - if (myEngine == null) { - String message = "No engine loaded."; - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - im.endTransaction(); - return; - } - // - // Send the request and save the response - // - long lTimeStart; - long lTimeEnd; - Response pdpResponse = null; - - synchronized(pdpEngineLock) { - myEngine = XACMLPdpServlet.pdpEngine; - try { - PolicyList.clearPolicyList(); - lTimeStart = System.currentTimeMillis(); - pdpResponse = myEngine.decide(pdpRequest); - lTimeEnd = System.currentTimeMillis(); - } catch (PDPException e) { - String message = "Exception during decide: " + e.getMessage(); - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message +e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - im.endTransaction(); - return; - } - } - monitor.computeLatency(lTimeEnd - lTimeStart); - requestLogger.info(lTimeStart + "=" + incomingRequestString); - for(String policy : PolicyList.getpolicyList()){ - monitor.policyCountAdd(policy, 1); - } - - - logger.info("PolicyID triggered in Request: " + PolicyList.getpolicyList()); - - //need to go through the list and find out if the value is unique and then add it other wise - // monitor.policyCountAdd(PolicyList.getpolicyList(), 1); - - if (logger.isDebugEnabled()) { - logger.debug("Request time: " + (lTimeEnd - lTimeStart) + "ms"); - } - // - // Convert Response to appropriate Content-Type - // - if (pdpResponse == null) { - requestLogger.info(lTimeStart + "=" + "{}"); - try{ - throw new PDPException("Failed to get response from PDP engine."); - }catch(Exception e1){ - logger.error("Exception occured while throwing Exception" +e1); - } - } - // - // Set our content-type - // - response.setContentType(contentType.getMimeType()); - // - // Convert the PDP response object to a String to - // return to our caller as well as dump to our loggers. - // - String outgoingResponseString = ""; - try{ - if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { - // - // Get it as a String. This is not very efficient but we need to log our - // results for auditing. - // - outgoingResponseString = JSONResponse.toString(pdpResponse, logger.isDebugEnabled()); - if (logger.isDebugEnabled()) { - logger.debug(outgoingResponseString); - // - // Get rid of whitespace - // - outgoingResponseString = JSONResponse.toString(pdpResponse, false); - } - } else if ( contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || - contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { - // - // Get it as a String. This is not very efficient but we need to log our - // results for auditing. - // - outgoingResponseString = DOMResponse.toString(pdpResponse, logger.isDebugEnabled()); - if (logger.isDebugEnabled()) { - logger.debug(outgoingResponseString); - // - // Get rid of whitespace - // - outgoingResponseString = DOMResponse.toString(pdpResponse, false); - } - } - // adding the jmx values for NA, Permit and Deny - // - if (outgoingResponseString.contains("NotApplicable") || outgoingResponseString.contains("Decision not a Permit")){ - monitor.pdpEvaluationNA(); - } - - if (outgoingResponseString.contains("Permit") && !outgoingResponseString.contains("Decision not a Permit")){ - monitor.pdpEvaluationPermit(); - } - - if (outgoingResponseString.contains("Deny")){ - monitor.pdpEvaluationDeny(); - } - // - // lTimeStart is used as an ID within the requestLogger to match up - // request's with responses. - // - requestLogger.info(lTimeStart + "=" + outgoingResponseString); - response.getWriter().print(outgoingResponseString); - }catch(Exception e){ - logger.error("Exception Occured"+e ); - } - } - catch (Exception e) { - String message = "Exception executing request: " + e; - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message, e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, message); - loggingContext.transactionEnded(); - PolicyLogger.audit("Transaction Failed - See Error.log"); - try{ - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); - }catch(Exception e1){ - logger.error("Exception occured while sending error in response" +e1); - } - return; - } - - monitor.pdpEvaluationSuccess(); - response.setStatus(HttpServletResponse.SC_OK); - - loggingContext.transactionEnded(); - auditLogger.info("Success"); - PolicyLogger.audit("Success"); - - } - - /* - * Added for Authorizing the PEP Requests for Environment check. - */ - private boolean authorizeRequest(HttpServletRequest request) { - // Get the client Credentials from the Request header. - HttpServletRequest httpServletRequest = request; - String clientCredentials = httpServletRequest.getHeader(ENVIORNMENT_HEADER); - if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){ - return true; - }else{ - return false; - } - } - - @Override - public void run() { - // - // Keep running until we are told to terminate - // - try { - // variable not used, but constructor has needed side-effects so don't remove: - while (! this.configThreadTerminate) { - PutRequest request = XACMLPdpServlet.queue.take(); - StdPDPStatus newStatus = new StdPDPStatus(); - - PDPEngine newEngine = null; - synchronized(pdpStatusLock) { - XACMLPdpServlet.status.setStatus(Status.UPDATING_CONFIGURATION); - newEngine = XACMLPdpLoader.loadEngine(newStatus, request.policyProperties, request.pipConfigProperties); - } - if (newEngine != null) { - synchronized(XACMLPdpServlet.pdpEngineLock) { - XACMLPdpServlet.pdpEngine = newEngine; - try { - logger.info("Saving configuration."); - if (request.policyProperties != null) { - try (OutputStream os = Files.newOutputStream(XACMLPdpLoader.getPDPPolicyCache())) { - request.policyProperties.store(os, ""); - } - } - if (request.pipConfigProperties != null) { - try (OutputStream os = Files.newOutputStream(XACMLPdpLoader.getPIPConfig())) { - request.pipConfigProperties.store(os, ""); - } - } - newStatus.setStatus(Status.UP_TO_DATE); - } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to store new properties."+e); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Failed to store new properties"); - newStatus.setStatus(Status.LOAD_ERRORS); - newStatus.addLoadWarning("Unable to save configuration: " + e.getMessage()); - } - } - } else { - newStatus.setStatus(Status.LAST_UPDATE_FAILED); - } - synchronized(pdpStatusLock) { - XACMLPdpServlet.status.set(newStatus); - } - } - } catch (InterruptedException e) { - logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "interrupted"+e); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "interrupted"); - Thread.currentThread().interrupt(); - } - } - - public static PDPEngine getPDPEngine(){ - PDPEngine myEngine = null; - synchronized(pdpEngineLock) { - myEngine = XACMLPdpServlet.pdpEngine; - } - return myEngine; - } - - public static Constructor getCreateUpdatePolicyConstructor(){ - return createUpdatePolicyConstructor; - } - - private static void setCreateUpdatePolicyConstructor(String createUpdateResourceName) throws ServletException{ - try{ - Class createUpdateclass = Class.forName(createUpdateResourceName); - createUpdatePolicyConstructor = createUpdateclass.getConstructor(PolicyParameters.class, String.class, boolean.class); - }catch(Exception e){ - PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, "createUpdatePolicy.impl.className", "xacml.pdp.init" +e); - throw new ServletException("Could not find the Class name : " +createUpdateResourceName + "\n" +e.getMessage()); - } - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/controller/PolicyEngineServices.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/controller/PolicyEngineServices.java deleted file mode 100644 index 48539ad83..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/controller/PolicyEngineServices.java +++ /dev/null @@ -1,658 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.controller; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiImplicitParam; -import io.swagger.annotations.ApiImplicitParams; -import io.swagger.annotations.ApiOperation; - -import java.lang.reflect.InvocationTargetException; -import java.util.Collection; -import java.util.concurrent.atomic.AtomicLong; - -import javax.servlet.http.HttpServletRequest; - -import org.openecomp.policy.api.ConfigRequestParameters; -import org.openecomp.policy.api.DecisionRequestParameters; -import org.openecomp.policy.api.DecisionResponse; -import org.openecomp.policy.api.DeletePolicyParameters; -import org.openecomp.policy.api.DictionaryParameters; -import org.openecomp.policy.api.DictionaryResponse; -import org.openecomp.policy.api.EventRequestParameters; -import org.openecomp.policy.api.MetricsResponse; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.api.PolicyResponse; -import org.openecomp.policy.api.PushPolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.XACMLPdpServlet; -import org.openecomp.policy.pdp.rest.api.models.ConfigFirewallPolicyAPIRequest; -import org.openecomp.policy.pdp.rest.api.models.ConfigNameRequest; -import org.openecomp.policy.pdp.rest.api.models.ConfigPolicyAPIRequest; -import org.openecomp.policy.pdp.rest.api.models.PolicyConfig; -import org.openecomp.policy.pdp.rest.api.services.CreateUpdateConfigPolicyService; -import org.openecomp.policy.pdp.rest.api.services.CreateUpdateDictionaryService; -import org.openecomp.policy.pdp.rest.api.services.CreateUpdateFirewallPolicyService; -import org.openecomp.policy.pdp.rest.api.services.CreateUpdatePolicyService; -import org.openecomp.policy.pdp.rest.api.services.DeletePolicyService; -import org.openecomp.policy.pdp.rest.api.services.GetConfigService; -import org.openecomp.policy.pdp.rest.api.services.GetDecisionService; -import org.openecomp.policy.pdp.rest.api.services.GetDictionaryService; -import org.openecomp.policy.pdp.rest.api.services.GetMetricsService; -import org.openecomp.policy.pdp.rest.api.services.ListConfigService; -import org.openecomp.policy.pdp.rest.api.services.NotificationService; -import org.openecomp.policy.pdp.rest.api.services.NotificationService.NotificationServiceType; -import org.openecomp.policy.pdp.rest.api.services.PolicyEngineImportService; -import org.openecomp.policy.pdp.rest.api.services.PushPolicyService; -import org.openecomp.policy.pdp.rest.api.services.SendEventService; -import org.openecomp.policy.pdp.rest.config.PDPApiAuth; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.http.converter.HttpMessageNotReadableException; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.ResponseBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - -import springfox.documentation.annotations.ApiIgnore; - -@RestController -@Api(value = "Policy Engine Services") -@RequestMapping("/") -public class PolicyEngineServices { - private static Logger logger = FlexLogger.getLogger(PolicyEngineServices.class.getName()); - private static final String NOTIFICATIONPERM = "notification"; - - private final AtomicLong configCounter = new AtomicLong(); - private final AtomicLong configNameCounter = new AtomicLong(); - private final AtomicLong eventCounter = new AtomicLong(); - private final AtomicLong decisionCounter = new AtomicLong(); - private final AtomicLong pushCounter = new AtomicLong(); - private final AtomicLong deleteCounter = new AtomicLong(); - private final AtomicLong createPolicyCounter = new AtomicLong(); - private final AtomicLong updatePolicyCounter = new AtomicLong(); - private final AtomicLong createDictionaryCounter = new AtomicLong(); - private final AtomicLong updateDictionaryCounter = new AtomicLong(); - private final AtomicLong getDictionaryCounter = new AtomicLong(); - private final AtomicLong policyEngineImportCounter = new AtomicLong(); - private final AtomicLong deprecatedCounter = new AtomicLong(); - private final AtomicLong metricCounter = new AtomicLong(); - private final AtomicLong notificationCounter = new AtomicLong(); - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Gets the configuration from the PolicyDecisionPoint(PDP)") - @RequestMapping(value = "/getConfig", method = RequestMethod.POST) - @ResponseBody - public ResponseEntity> getConfig( - @RequestBody ConfigRequestParameters configRequestParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - Collection policyConfig = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "getConfig")) { - GetConfigService getConfigService = new GetConfigService( - configRequestParameters, requestID); - policyConfig = getConfigService.getResult(); - status = getConfigService.getResponseCode(); - } - configCounter.incrementAndGet(); - return new ResponseEntity<>(policyConfig, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Gets the configuration from the PolicyDecisionPoint(PDP) using PolicyName") - @RequestMapping(value = "/getConfigByPolicyName", method = RequestMethod.POST) - @ResponseBody - @Deprecated - public ResponseEntity> getConfigByPolicyName( - @RequestBody ConfigNameRequest configNameRequest, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - Collection policyConfig = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID,"getConfigByPolicyName")) { - ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); - configRequestParameters.setPolicyName(configNameRequest - .getPolicyName()); - GetConfigService getConfigService = new GetConfigService( - configRequestParameters, requestID); - policyConfig = getConfigService.getResult(); - status = getConfigService.getResponseCode(); - } - configNameCounter.incrementAndGet(); - return new ResponseEntity<>(policyConfig, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Gets the list of configuration policies from the PDP") - @RequestMapping(value = "/listConfig", method = RequestMethod.POST) - @ResponseBody - public ResponseEntity> listConfig( - @RequestBody ConfigRequestParameters configRequestParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - Collection results = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth - .checkPermissions(clientEncoding, requestID, "listConfig")) { - ListConfigService listConfigService = new ListConfigService( - configRequestParameters, requestID); - results = listConfigService.getResult(); - status = listConfigService.getResponseCode(); - } - configCounter.incrementAndGet(); - return new ResponseEntity<>(results, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name ="Environment", required = true, paramType = "Header") - }) - @ApiOperation(value= "Gets the policy metrics from the PolicyAccessPoint(PAP)") - @RequestMapping(value="/getMetrics", method=RequestMethod.GET) - @ResponseBody - public ResponseEntity getMetrics( - @RequestHeader(value="ClientAuth", required=true)String clientEncoding, - @RequestHeader(value="X-ECOMP-RequestID", required=false)String requestID) { - MetricsResponse response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if(PDPApiAuth.checkPermissions(clientEncoding, requestID, "getMetrics")){ - GetMetricsService getMetricsService = new GetMetricsService(requestID); - response = getMetricsService.getResult(); - status = getMetricsService.getResponseCode(); - } - metricCounter.incrementAndGet(); - return new ResponseEntity<>(response, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Registers DMaaP Topic to recieve notification from Policy Engine") - @RequestMapping(value = "/getNotification", method = RequestMethod.POST) - @ResponseBody - public ResponseEntity getNotification( - @RequestBody String notificationTopic, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String policyResponse = "Error Unauthorized to use Notification Service."; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, NOTIFICATIONPERM)) { - NotificationService notificationService = new NotificationService(notificationTopic, requestID, NotificationServiceType.ADD); - policyResponse = notificationService.getResult(); - status = notificationService.getResponseCode(); - } - notificationCounter.incrementAndGet(); - return new ResponseEntity<>(policyResponse, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "De-Registers DMaaP Topic to stop recieving notifications from Policy Engine") - @RequestMapping(value = "/stopNotification", method = RequestMethod.POST) - @ResponseBody - public ResponseEntity stopNotification( - @RequestBody String notificationTopic, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String policyResponse = "Error Unauthorized to use Notification Service."; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, NOTIFICATIONPERM)) { - NotificationService notificationService = new NotificationService(notificationTopic, requestID, NotificationServiceType.REMOVE); - policyResponse = notificationService.getResult(); - status = notificationService.getResponseCode(); - } - notificationCounter.incrementAndGet(); - return new ResponseEntity<>(policyResponse, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Sends Heartbeat to DMaaP Topic Registry to continue recieving notifications from Policy Engine") - @RequestMapping(value = "/sendHeartbeat", method = RequestMethod.POST) - @ResponseBody - public ResponseEntity sendHeartbeat( - @RequestBody String notificationTopic, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String policyResponse = "Error Unauthorized to use Heartbeat Service."; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, NOTIFICATIONPERM)) { - NotificationService notificationService = new NotificationService(notificationTopic, requestID, NotificationServiceType.HB); - policyResponse = notificationService.getResult(); - status = notificationService.getResponseCode(); - } - return new ResponseEntity<>(policyResponse, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Sends the Events specified to the Policy Engine") - @RequestMapping(value = "/sendEvent", method = RequestMethod.POST) - @ResponseBody - public ResponseEntity> sendEvent( - @RequestBody EventRequestParameters eventRequestParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - Collection policyResponse = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "sendEvent")) { - SendEventService sendEventService = new SendEventService( - eventRequestParameters, requestID); - policyResponse = sendEventService.getResult(); - status = sendEventService.getResponseCode(); - } - eventCounter.incrementAndGet(); - return new ResponseEntity<>(policyResponse, - status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Gets the Decision using specified decision parameters") - @RequestMapping(value = "/getDecision", method = RequestMethod.POST) - @ResponseBody - public ResponseEntity getDecision( - @RequestBody DecisionRequestParameters decisionRequestParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - DecisionResponse decisionResponse = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, - "getDecision")) { - GetDecisionService getDecisionService = new GetDecisionService( - decisionRequestParameters, requestID); - decisionResponse = getDecisionService.getResult(); - status = getDecisionService.getResponseCode(); - } - decisionCounter.incrementAndGet(); - return new ResponseEntity<>(decisionResponse, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Pushes the specified policy to the PDP Group.") - @RequestMapping(value = "/pushPolicy", method = RequestMethod.PUT) - @ResponseBody - public ResponseEntity pushPolicy( - @RequestBody PushPolicyParameters pushPolicyParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth - .checkPermissions(clientEncoding, requestID, "pushPolicy")) { - PushPolicyService pushPolicyService = new PushPolicyService( - pushPolicyParameters, requestID); - response = pushPolicyService.getResult(); - status = pushPolicyService.getResponseCode(); - } - pushCounter.incrementAndGet(); - return new ResponseEntity<>(response, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Deletes the specified policy from the PDP Group or PAP.") - @RequestMapping(value = "/deletePolicy", method = RequestMethod.DELETE) - @ResponseBody - public ResponseEntity deletePolicy( - @RequestBody DeletePolicyParameters deletePolicyParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, - "deletePolicy")) { - DeletePolicyService deletePolicyService = new DeletePolicyService( - deletePolicyParameters, requestID); - response = deletePolicyService.getResult(); - status = deletePolicyService.getResponseCode(); - } - deleteCounter.incrementAndGet(); - return new ResponseEntity<>(response, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Creates a Policy based on given Policy Parameters.") - @RequestMapping(value = "/createPolicy", method = RequestMethod.PUT) - @ResponseBody - public ResponseEntity createPolicy( - @RequestBody PolicyParameters policyParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, - "createPolicy")) { - CreateUpdatePolicyService createPolicyService; - try { - createPolicyService = (CreateUpdatePolicyService) XACMLPdpServlet.getCreateUpdatePolicyConstructor().newInstance( - policyParameters, requestID, false); - response = createPolicyService.getResult(); - status = createPolicyService.getResponseCode(); - } catch (InstantiationException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException e) { - logger.error(e.getMessage(), e); - response = "Problem with CreateUpdate Policy Service. "; - status = HttpStatus.INTERNAL_SERVER_ERROR; - } - } - createPolicyCounter.incrementAndGet(); - return new ResponseEntity<>(response, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Updates a Policy based on given Policy Parameters.") - @RequestMapping(value = "/updatePolicy", method = RequestMethod.PUT) - @ResponseBody - public ResponseEntity updatePolicy( - @RequestBody PolicyParameters policyParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, - "updatePolicy")) { - CreateUpdatePolicyService updatePolicyService; - try { - updatePolicyService = (CreateUpdatePolicyService) XACMLPdpServlet.getCreateUpdatePolicyConstructor().newInstance( - policyParameters, requestID, true); - response = updatePolicyService.getResult(); - status = updatePolicyService.getResponseCode(); - } catch (InstantiationException | IllegalAccessException - | IllegalArgumentException | InvocationTargetException e) { - logger.error(e.getMessage(), e); - response = "Problem with CreateUpdate Policy Service. "; - status = HttpStatus.INTERNAL_SERVER_ERROR; - } - } - updatePolicyCounter.incrementAndGet(); - return new ResponseEntity<>(response, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Creates a Dictionary Item for a specific dictionary based on given Parameters.") - @RequestMapping(value = "/createDictionaryItem", method = RequestMethod.PUT) - @ResponseBody - public ResponseEntity createDictionaryItem( - @RequestBody DictionaryParameters dictionaryParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, - "createDictionary")) { - CreateUpdateDictionaryService createDictionaryService = new CreateUpdateDictionaryService( - dictionaryParameters, requestID, false); - response = createDictionaryService.getResult(); - status = createDictionaryService.getResponseCode(); - } - createDictionaryCounter.incrementAndGet(); - return new ResponseEntity<>(response, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Updates a Dictionary Item for a specific dictionary based on given Parameters.") - @RequestMapping(value = "/updateDictionaryItem", method = RequestMethod.PUT) - @ResponseBody - public ResponseEntity updateDictionaryItem( - @RequestBody DictionaryParameters dictionaryParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, - "updateDictionary")) { - CreateUpdateDictionaryService updateDictionaryService = new CreateUpdateDictionaryService( - dictionaryParameters, requestID, true); - response = updateDictionaryService.getResult(); - status = updateDictionaryService.getResponseCode(); - } - updateDictionaryCounter.incrementAndGet(); - return new ResponseEntity<>(response, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Gets the dictionary items from the PAP") - @RequestMapping(value = "/getDictionaryItems", method = RequestMethod.POST) - @ResponseBody - public ResponseEntity getDictionaryItems( - @RequestBody DictionaryParameters dictionaryParameters, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - DictionaryResponse dictionaryResponse = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, - "getDictionary")) { - GetDictionaryService getDictionaryService = new GetDictionaryService( - dictionaryParameters, requestID); - dictionaryResponse = getDictionaryService.getResult(); - status = getDictionaryService.getResponseCode(); - } - getDictionaryCounter.incrementAndGet(); - return new ResponseEntity<>(dictionaryResponse, - status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Imports Policy based on the parameters which represent the service used to create a policy Service.") - @RequestMapping(value = "/policyEngineImport", method = RequestMethod.POST) - @ResponseBody - public ResponseEntity policyEngineImport( - @RequestParam("importParametersJson") String importParametersJson, - @RequestParam("file") MultipartFile file, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, - "policyEngineImport")) { - PolicyEngineImportService policyEngineImportService = new PolicyEngineImportService( - importParametersJson, file, requestID); - response = policyEngineImportService.getResult(); - status = policyEngineImportService.getResponseCode(); - } - policyEngineImportCounter.incrementAndGet(); - return new ResponseEntity<>(response, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Creates a Config Policy based on given Policy Parameters.") - @RequestMapping(value = "/createConfig", method = RequestMethod.PUT) - @ResponseBody - @Deprecated - public ResponseEntity createConfig( - @RequestBody ConfigPolicyAPIRequest configPolicyAPIRequest, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, - "createPolicy")) { - CreateUpdateConfigPolicyService createPolicyService = new CreateUpdateConfigPolicyService( - configPolicyAPIRequest, requestID, false); - response = createPolicyService.getResult(); - status = createPolicyService.getResponseCode(); - } - deprecatedCounter.incrementAndGet(); - return new ResponseEntity<>(response, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Updates a Config Policy based on given Policy Parameters.") - @RequestMapping(value = "/updateConfig", method = RequestMethod.PUT) - @ResponseBody - @Deprecated - public ResponseEntity updateConfig( - @RequestBody ConfigPolicyAPIRequest configPolicyAPIRequest, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, - "updatePolicy")) { - CreateUpdateConfigPolicyService updatePolicyService = new CreateUpdateConfigPolicyService( - configPolicyAPIRequest, requestID, true); - response = updatePolicyService.getResult(); - status = updatePolicyService.getResponseCode(); - } - deprecatedCounter.incrementAndGet(); - return new ResponseEntity<>(response, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Creates a Config Firewall Policy") - @RequestMapping(value = "/createFirewallConfig", method = RequestMethod.PUT) - @ResponseBody - @Deprecated - public ResponseEntity createFirewallConfig( - @RequestBody ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, - "createPolicy")) { - CreateUpdateFirewallPolicyService createFirewallPolicyService = new CreateUpdateFirewallPolicyService( - configFirewallPolicyAPIRequest, requestID, false); - response = createFirewallPolicyService.getResult(); - status = createFirewallPolicyService.getResponseCode(); - } - deprecatedCounter.incrementAndGet(); - return new ResponseEntity<>(response, status); - } - - @ApiImplicitParams({ - @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), - @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) - @ApiOperation(value = "Updates a Config Firewall Policy") - @RequestMapping(value = "/updateFirewallConfig", method = RequestMethod.PUT) - @ResponseBody - @Deprecated - public ResponseEntity updateFirewallConfig( - @RequestBody ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest, - @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, - @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { - String response = null; - HttpStatus status = HttpStatus.UNAUTHORIZED; - // Check Permissions. - if (PDPApiAuth.checkPermissions(clientEncoding, requestID, - "updatePolicy")) { - CreateUpdateFirewallPolicyService updateFirewallPolicyService = new CreateUpdateFirewallPolicyService( - configFirewallPolicyAPIRequest, requestID, true); - response = updateFirewallPolicyService.getResult(); - status = updateFirewallPolicyService.getResponseCode(); - } - deprecatedCounter.incrementAndGet(); - return new ResponseEntity<>(response, status); - } - - @ApiOperation(value = "Gets the API Services usage Information") - @ApiIgnore - @RequestMapping(value = "/count", method = RequestMethod.GET) - public String getCount() { - return "Total Config Calls : " + configCounter + "\n" - + "Total Config calls made using Policy File Name: " - + configNameCounter + "\n" + "Total Event Calls : " - + eventCounter + "\nTotal Decision Calls: " + decisionCounter - + "\nTotal Push policy Calls: " + pushCounter - + "\nTotal Delete Policy Calls: " + deleteCounter - + "\nTotal Create Policy Calls: " + createPolicyCounter - + "\nTotal Update Policy Calls: " + updatePolicyCounter - + "\nTotal Create Dictionary Calls: " + createDictionaryCounter - + "\nTotal Update Dictionary Calls: " + updateDictionaryCounter - + "\nTotal Get Dictionary Calls: " + getDictionaryCounter - + "\nTotal PolicyEngine Import Calls: " - + policyEngineImportCounter - + "\nTotal Deprecated Policy Calls: " + deprecatedCounter - + "\nTotal Metrics Calls:" + metricCounter - + "\nTotal Notification Calls:" + notificationCounter; - } - - @ExceptionHandler({ HttpMessageNotReadableException.class }) - public ResponseEntity messageNotReadableExceptionHandler( - HttpServletRequest req, HttpMessageNotReadableException exception) { - logger.error("Request not readable: {}", exception); - StringBuilder message = new StringBuilder(); - message.append(exception.getMessage()); - if (exception.getCause() != null) { - message.append(" Reason Caused: " - + exception.getCause().getMessage()); - } - return new ResponseEntity<>(message.toString(), HttpStatus.BAD_REQUEST); - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigFirewallPolicyAPIRequest.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigFirewallPolicyAPIRequest.java deleted file mode 100644 index 4ae368ae7..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigFirewallPolicyAPIRequest.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.models; - -import io.swagger.annotations.ApiModel; - -import java.io.Serializable; - -@ApiModel -public class ConfigFirewallPolicyAPIRequest implements Serializable{ - private static final long serialVersionUID = -7460640390070215401L; - - private String policyName = null; - private String policyScope = null; - private String firewallJson = null; - private String riskType = "default"; - private String riskLevel = "5"; - private String guard = "false"; - private String ttlDate = null; - - public String getPolicyName() { - return policyName; - } - public String getPolicyScope() { - return policyScope; - } - public String getFirewallJson() { - return firewallJson; - } - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - public void setPolicyScope(String policyScope) { - this.policyScope = policyScope; - } - public void setFirewallJson(String firewallJson) { - this.firewallJson = firewallJson; - } - 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 getGuard() { - return guard; - } - public void setGuard(String guard) { - this.guard = guard; - } - public String getTtlDate() { - return ttlDate; - } - public void setTtlDate(String ttlDate) { - this.ttlDate = ttlDate; - } -} \ No newline at end of file diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigNameRequest.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigNameRequest.java deleted file mode 100644 index 91881a3b2..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigNameRequest.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.models; - -import io.swagger.annotations.ApiModel; - -import java.io.Serializable; - -@ApiModel -public class ConfigNameRequest implements Serializable{ - private static final long serialVersionUID = 4487978240532425305L; - - private String policyName = null; - - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - - public String getPolicyName() { - return policyName; - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigPolicyAPIRequest.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigPolicyAPIRequest.java deleted file mode 100644 index ed5d0ccaf..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/ConfigPolicyAPIRequest.java +++ /dev/null @@ -1,188 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.models; - -import io.swagger.annotations.ApiModel; - -import java.io.Serializable; -import java.util.Map; - -@ApiModel -public class ConfigPolicyAPIRequest implements Serializable{ - private static final long serialVersionUID = -4103391389984557025L; - - private String policyScope = null; - private String policyName = null; - private String policyDescription = null; - private String ecompName = null; - private String configName = null; - private Map configAttributes = null; - private String configType = null; - private String body = null; - private String riskType = "default"; - private String riskLevel = "5"; - private String guard = "false"; - private String ttlDate = null; - - /** - * @return the policyScope - */ - public String getPolicyScope() { - return policyScope; - } - /** - * @return the policyName - */ - public String getPolicyName() { - return policyName; - } - /** - * @return the policyDescription - */ - public String getPolicyDescription() { - return policyDescription; - } - /** - * @return the ecompName - */ - public String getEcompName() { - return ecompName; - } - /** - * @return the configName - */ - public String getConfigName() { - return configName; - } - /** - * @return the configAttributes - */ - public Map getConfigAttributes() { - return configAttributes; - } - /** - * @return the configType - */ - public String getConfigType() { - return configType; - } - /** - * @return the body - */ - public String getBody() { - return body; - } - /** - * @param policyScope the policyScope to set - */ - public void setPolicyScope(String policyScope) { - this.policyScope = policyScope; - } - /** - * @param policyName the policyName to set - */ - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - /** - * @param policyDescription the policyDescription to set - */ - public void setPolicyDescription(String policyDescription) { - this.policyDescription = policyDescription; - } - /** - * @param ecompName the ecompName to set - */ - public void setEcompName(String ecompName) { - this.ecompName = ecompName; - } - /** - * @param configName the configName to set - */ - public void setConfigName(String configName) { - this.configName = configName; - } - /** - * @param configAttributes the configAttributes to set - */ - public void setConfigAttributes(Map configAttributes) { - this.configAttributes = configAttributes; - } - /** - * @param configType the configType to set - */ - public void setConfigType(String configType) { - this.configType = configType; - } - /** - * @param body the body to set - */ - public void setBody(String body) { - this.body = body; - } - /** - * @return the guard - */ - public String getGuard() { - return guard; - } - /** - * @param guard the guard to set - */ - public void setGuard(String guard) { - this.guard = guard; - } - /** - * @return the riskLevel - */ - public String getRiskLevel() { - return riskLevel; - } - /** - * @param riskLevel the riskLevel to set - */ - public void setRiskLevel(String riskLevel) { - this.riskLevel = riskLevel; - } - /** - * @return the ttlDate - */ - public String getTtlDate() { - return ttlDate; - } - /** - * @param ttlDate the ttlDate to set - */ - public void setTtlDate(String ttlDate) { - this.ttlDate = ttlDate; - } - /** - * @return the riskType - */ - public String getRiskType() { - return riskType; - } - /** - * @param riskType the riskType to set - */ - public void setRiskType(String riskType) { - this.riskType = riskType; - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PDPResponse.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PDPResponse.java deleted file mode 100644 index 2301d003c..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PDPResponse.java +++ /dev/null @@ -1,159 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.models; - -import java.util.Map; - -import org.openecomp.policy.api.DecisionResponse; -import org.openecomp.policy.api.PolicyConfigStatus; -import org.openecomp.policy.api.PolicyDecision; -import org.openecomp.policy.api.PolicyResponse; -import org.openecomp.policy.api.PolicyResponseStatus; -import org.openecomp.policy.api.PolicyType; -import org.openecomp.policy.models.APIConfigResponse; - -public class PDPResponse implements APIConfigResponse, PolicyResponse, DecisionResponse{ - private String policyConfigMessage; - private PolicyConfigStatus policyConfigStatus; - private PolicyType type; - private String config; - private String policyName; - private String policyVersion; - private Map matchingConditions; - private Map responseAttributes; - private Map property; - private PolicyResponseStatus policyResponseStatus; - private String policyResponseMessage; - private Map actionAdvised; - private Map actionTaken; - private Map requestAttributes; - private PolicyDecision policyDecision; - private String details; - - public void setStatus(String message, PolicyResponseStatus policyResponseStatus, PolicyConfigStatus policyConfigStatus) { - this.policyConfigMessage = message; - this.policyResponseMessage = message; - this.policyResponseStatus = policyResponseStatus; - this.policyConfigStatus = policyConfigStatus; - } - public String getConfig() { - return config; - } - public void setConfig(String config) { - this.config = config; - } - public PolicyType getType() { - return type; - } - public void setType(PolicyType type) { - this.type = type; - } - public PolicyConfigStatus getPolicyConfigStatus() { - return policyConfigStatus; - } - public void setPolicyConfigStatus(PolicyConfigStatus policyConfigStatus) { - this.policyConfigStatus = policyConfigStatus; - } - public String getPolicyConfigMessage() { - return policyConfigMessage; - } - public void setPolicyConfigMessage(String policyConfigMessage) { - this.policyConfigMessage = policyConfigMessage; - } - public Map getProperty() { - return property; - } - public void setProperty(Map property) { - this.property = property; - } - public String getPolicyName(){ - return policyName; - } - public void setPolicyName(String policyName){ - this.policyName = policyName; - } - public String getPolicyVersion(){ - return policyVersion; - } - public void setPolicyVersion(String policyVersion){ - this.policyVersion = policyVersion; - } - public Map getMatchingConditions(){ - return matchingConditions; - } - public void setMatchingConditions(Map matchingConditions){ - this.matchingConditions = matchingConditions; - } - public void setResponseAttributes(Map responseAttributes){ - this.responseAttributes = responseAttributes; - } - public Map getResponseAttributes(){ - return responseAttributes; - } - public void setPolicyResponseStatus(PolicyResponseStatus policyResponseStatus) { - this.policyResponseStatus = policyResponseStatus; - } - @Override - public PolicyResponseStatus getPolicyResponseStatus() { - return policyResponseStatus; - } - public void setDecision(PolicyDecision policyDecision){ - this.policyDecision = policyDecision; - } - @Override - public PolicyDecision getDecision() { - return policyDecision; - } - public void setDetails(String details){ - this.details = details; - } - @Override - public String getDetails() { - return details; - } - public void setActionAdvised(Map actionAdvised) { - this.actionAdvised = actionAdvised; - } - @Override - public Map getActionAdvised() { - return actionAdvised; - } - public void setActionTaken(Map actionTaken) { - this.actionTaken = actionTaken; - } - @Override - public Map getActionTaken() { - return actionTaken; - } - public void setRequestAttributes(Map requestAttributes) { - this.requestAttributes = requestAttributes; - } - @Override - public Map getRequestAttributes() { - return requestAttributes; - } - public void setPolicyResponseMessage(String policyResponseMessage) { - this.policyResponseMessage = policyResponseMessage; - } - @Override - public String getPolicyResponseMessage() { - return policyResponseMessage; - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PolicyConfig.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PolicyConfig.java deleted file mode 100644 index 729ffbb6f..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/models/PolicyConfig.java +++ /dev/null @@ -1,95 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.models; - -import io.swagger.annotations.ApiModel; - -import java.util.Map; - -import org.openecomp.policy.api.PolicyConfigStatus; -import org.openecomp.policy.api.PolicyType; -import org.openecomp.policy.models.APIConfigResponse; - -@ApiModel -public class PolicyConfig implements APIConfigResponse{ - private String policyConfigMessage; - private PolicyConfigStatus policyConfigStatus; - private PolicyType type; - private String config; - private String policyName; - private String policyVersion; - private Map matchingConditions; - private Map responseAttributes; - private Map property; - public String getConfig() { - return config; - } - public void setConfig(String config) { - this.config = config; - } - public PolicyType getType() { - return type; - } - public void setType(PolicyType type) { - this.type = type; - } - public PolicyConfigStatus getPolicyConfigStatus() { - return policyConfigStatus; - } - public void setPolicyConfigStatus(PolicyConfigStatus policyConfigStatus) { - this.policyConfigStatus = policyConfigStatus; - } - public String getPolicyConfigMessage() { - return policyConfigMessage; - } - public void setPolicyConfigMessage(String policyConfigMessage) { - this.policyConfigMessage = policyConfigMessage; - } - public Map getProperty() { - return property; - } - public void setProperty(Map property) { - this.property = property; - } - public String getPolicyName(){ - return policyName; - } - public void setPolicyName(String policyName){ - this.policyName = policyName; - } - public String getPolicyVersion(){ - return policyVersion; - } - public void setPolicyVersion(String policyVersion){ - this.policyVersion = policyVersion; - } - public Map getMatchingConditions(){ - return matchingConditions; - } - public void setMatchingConditions(Map matchingConditions){ - this.matchingConditions = matchingConditions; - } - public void setResponseAttributes(Map responseAttributes){ - this.responseAttributes = responseAttributes; - } - public Map getResponseAttributes(){ - return responseAttributes; - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ActionPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ActionPolicyService.java deleted file mode 100644 index 7640cad0e..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ActionPolicyService.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.util.Map; - -import org.openecomp.policy.api.AttributeType; -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; - -/** - * Action Policy Implementation. - * - * @version 0.1 - */ -public class ActionPolicyService { - private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyService.class.getName()); - private PAPServices papServices = null; - - private PolicyParameters policyParameters = null; - private String message = null; - private String policyName = null; - private String policyScope = null; - private Map componentAttributes = null; - private String actionAttribute = null; - private String actionPerformer = null; - - public ActionPolicyService(String policyScope, String policyName, - PolicyParameters policyParameters) { - this.policyParameters = policyParameters; - this.policyName = policyName; - this.policyScope = policyScope; - papServices = new PAPServices(); - } - - public Boolean getValidation() { - if(policyParameters.getAttributes()==null || policyParameters.getAttributes().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Component Attributes given."; - return false; - } - componentAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING); - if (componentAttributes==null||componentAttributes.isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Component Attributes given."; - return false; - } - actionAttribute = policyParameters.getActionAttribute(); - if (actionAttribute==null||actionAttribute.trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Attribute given."; - return false; - } - actionPerformer = policyParameters.getActionPerformer(); - if (actionPerformer==null||actionPerformer.trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Performer given."; - return false; - } - if(!"PEP".equalsIgnoreCase(actionPerformer)&& !"PDP".equalsIgnoreCase(actionPerformer)){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Performer given."; - return false; - } - return true; - } - - public String getMessage() { - return message; - } - - public String getResult(boolean updateFlag) throws PolicyException { - String response = null; - String operation = null; - if (updateFlag){ - operation = "update"; - } else { - operation = "create"; - } - // Create Policy - StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyName, policyParameters.getPolicyDescription(), - componentAttributes, policyParameters.getDynamicRuleAlgorithmLabels(), policyParameters.getDynamicRuleAlgorithmFunctions(), - policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmField2(), actionPerformer, actionAttribute, updateFlag, policyScope, 0); - // send Json to PAP - response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Action"}, policyParameters.getRequestID(), "Action"); - LOGGER.info(response); - return response; - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSParamPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSParamPolicyService.java deleted file mode 100644 index 37d07660d..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSParamPolicyService.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.util.Map; - -import org.openecomp.policy.api.AttributeType; -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; - -/** - * BRMS Param Policy Implementation. - * - * @version 0.1 - */ -public class BRMSParamPolicyService{ - private static final Logger LOGGER = FlexLogger.getLogger(BRMSParamPolicyService.class.getName()); - private PAPServices papServices = null; - - private PolicyParameters policyParameters = null; - private String message = null; - private String policyName = null; - private String policyScope = null; - private String date = null; - private Map> drlRuleAndUIParams = null; - - public BRMSParamPolicyService(String policyName, String policyScope, - PolicyParameters policyParameters, String date) { - this.policyParameters = policyParameters; - this.policyName = policyName; - this.policyScope = policyScope; - this.date = date; - papServices = new PAPServices(); - } - - public Boolean getValidation() { - boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); - if(!levelCheck){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; - return false; - } - drlRuleAndUIParams = policyParameters.getAttributes(); - if(drlRuleAndUIParams==null || drlRuleAndUIParams.isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Rule Attributes given."; - return false; - } - return true; - } - - public String getMessage() { - return message; - } - - public String getResult(boolean updateFlag) throws PolicyException { - String response = null; - String operation = null; - if (updateFlag){ - operation = "update"; - } else { - operation = "create"; - } - // Create Policy - StdPAPPolicy newPAPPolicy = new StdPAPPolicy("BRMS_Param",policyName, policyParameters.getPolicyDescription(), - "BRMS_PARAM_RULE",updateFlag,policyScope, - drlRuleAndUIParams.get(AttributeType.MATCHING), 0, "DROOLS", - null, drlRuleAndUIParams.get(AttributeType.RULE), policyParameters.getRiskLevel(), - policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date, policyParameters.getControllerName(), policyParameters.getDependencyNames()); - // Send JSON to PAP - response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigBrmsParam"); - LOGGER.info(response); - return response; - } - -} \ No newline at end of file diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSRawPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSRawPolicyService.java deleted file mode 100644 index c68b1695b..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/BRMSRawPolicyService.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.util.Map; - -import org.openecomp.policy.api.AttributeType; -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; -import org.openecomp.policy.utils.PolicyUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; - -/** - * BRMS RAW Policy Implementation. - * - * @version 0.1 - */ -public class BRMSRawPolicyService{ - private static Logger LOGGER = FlexLogger.getLogger(BRMSRawPolicyService.class.getName()); - private static PAPServices papServices = null; - - private PolicyParameters policyParameters = null; - private String message = null; - private String policyName = null; - private String policyScope = null; - private String date = null; - private boolean levelCheck = false; - private String brmsRawBody = null; - - public BRMSRawPolicyService(String policyName, String policyScope, - PolicyParameters policyParameters, String date) { - this.policyParameters = policyParameters; - this.policyName = policyName; - this.policyScope = policyScope; - this.date = date; - papServices = new PAPServices(); - } - - public Boolean getValidation() { - brmsRawBody = policyParameters.getConfigBody(); - if(brmsRawBody==null || brmsRawBody.trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Rule Body given"; - return false; - } - message = PolicyUtils.brmsRawValidate(brmsRawBody); - if(message.contains("[ERR")){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Raw rule given is invalid" +message; - return false; - } - levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); - if(!levelCheck){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; - return false; - } - return true; - } - - public String getMessage() { - return message; - } - - public String getResult(boolean updateFlag) throws PolicyException { - String response = null; - String operation = null; - if (updateFlag){ - operation = "update"; - } else { - operation = "create"; - } - Map ruleAttributes = null; - if(policyParameters.getAttributes()!=null){ - ruleAttributes = policyParameters.getAttributes().get(AttributeType.RULE); - } - // Create Policy - StdPAPPolicy newPAPPolicy = new StdPAPPolicy("BRMS_Raw",policyName,policyParameters.getPolicyDescription(), - "BRMS_RAW_RULE",updateFlag,policyScope, ruleAttributes, 0, "DROOLS", - brmsRawBody, policyParameters.getRiskLevel(), - policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date, policyParameters.getControllerName(), policyParameters.getDependencyNames()); - // Send JSON to PAP - response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigBrmsRaw"); - LOGGER.info(response); - return response; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java deleted file mode 100644 index b2ff00ed5..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java +++ /dev/null @@ -1,121 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import javax.json.JsonException; -import javax.json.JsonObject; - -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; - -/** - * Closed Loop Fault Policy Implementation. - * - * @version 0.1 - */ -public class ClosedLoopFaultPolicyService{ - private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopFaultPolicyService.class.getName()); - private PAPServices papServices = null; - - private PolicyParameters policyParameters = null; - private String message = null; - private String policyName = null; - private String policyScope = null; - private String date = null; - private JsonObject configBody = null; - - public ClosedLoopFaultPolicyService(String policyName, String policyScope, - PolicyParameters policyParameters, String date) { - this.policyParameters = policyParameters; - this.policyName = policyName; - this.policyScope = policyScope; - this.date = date; - papServices = new PAPServices(); - } - - public Boolean getValidation() { - if(policyParameters.getConfigBody()==null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present"; - return false; - } - if(!PolicyApiUtils.validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); - return false; - } - try{ - configBody = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); - } catch(JsonException| IllegalStateException e){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); - LOGGER.error("Json Parse Exception.", e); - return false; - } - return true; - } - - public String getMessage() { - return message; - } - - public String getResult(boolean updateFlag) throws PolicyException { - String response = null; - String operation = null; - String oldPolicyName = null; - if (updateFlag){ - operation = "update"; - if (policyName.endsWith("_Draft")) { - oldPolicyName = policyName + "_Draft.1"; - } - } else { - operation = "create"; - } - // get values and attributes from the JsonObject - if(!configBody.containsKey("ecompname")){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given."; - LOGGER.error(message); - return message; - } - String ecompName = configBody.get("ecompname").toString().trim().replace("\"", ""); - if (ecompName==null||ecompName.trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given."; - LOGGER.error(message); - return message; - } - boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); - if (!levelCheck){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; - LOGGER.error(message); - return message; - } - String jsonBody = configBody.toString(); - // Create Policy. - StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_Fault", policyName, policyParameters.getPolicyDescription(), ecompName, - jsonBody, false, oldPolicyName, null, updateFlag, policyScope, 0, policyParameters.getRiskLevel(), - policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date); - //send JSON object to PAP - response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigClosedLoop"); - return response; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java deleted file mode 100644 index 3fb8f461c..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import javax.json.JsonException; -import javax.json.JsonObject; - -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; - -/** - * Closed Loop PM policy Implementation. - * - * @version 0.1 - */ -public class ClosedLoopPMPolicyService{ - private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopPMPolicyService.class.getName()); - - private PAPServices papServices = null; - private PolicyParameters policyParameters = null; - private String message = null; - private String policyName = null; - private String policyScope = null; - private String date = null; - private JsonObject configBody = null; - - public ClosedLoopPMPolicyService(String policyName, String policyScope, - PolicyParameters policyParameters, String date) { - this.policyParameters = policyParameters; - this.policyName = policyName; - this.policyScope = policyScope; - this.date = date; - papServices = new PAPServices(); - } - - public Boolean getValidation() { - if(policyParameters.getConfigBody()==null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present"; - return false; - } - if(!PolicyApiUtils.validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); - return false; - } - try{ - configBody = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); - } catch(JsonException| IllegalStateException e){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); - LOGGER.error("Error during parsing JSON config body for Closed loop PM policy " , e); - return false; - } - return true; - } - - public String getMessage() { - return message; - } - - public String getResult(boolean updateFlag) throws PolicyException{ - String response = null; - String operation = null; - if (updateFlag){ - operation = "update"; - } else { - operation = "create"; - } - // get values and attributes from the JsonObject - if(!configBody.containsKey("ecompname")){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given."; - LOGGER.error(message); - return message; - } - if(!configBody.containsKey("serviceTypePolicyName")){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Service Type Policy Name given."; - LOGGER.error(message); - return message; - } - String ecompName = configBody.get("ecompname").toString().trim().replace("\"", ""); - if (ecompName==null||ecompName.trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given."; - LOGGER.error(message); - return message; - } - boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); - if (!levelCheck){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; - LOGGER.error(message); - return message; - } - String jsonBody = configBody.toString(); - String serviceType = configBody.get("serviceTypePolicyName").toString().replace("\"", ""); - // Create Policy. - StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_PM", policyName, policyParameters.getPolicyDescription(), ecompName, - jsonBody, false, null, serviceType, updateFlag, policyScope, 0, policyParameters.getRiskLevel(), - policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date); - //send JSON object to PAP - response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigClosedLoop"); - return response; - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ConfigPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ConfigPolicyService.java deleted file mode 100644 index 3401d55b9..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ConfigPolicyService.java +++ /dev/null @@ -1,136 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.util.Map; - -import org.openecomp.policy.api.AttributeType; -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; -import org.openecomp.policy.utils.PolicyUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; - -/** - * Config Base Policy Implementation. - * - * @version 0.1 - */ -public class ConfigPolicyService { - private static final Logger LOGGER = FlexLogger.getLogger(ConfigPolicyService.class.getName()); - private PAPServices papServices = null; - - private PolicyParameters policyParameters = null; - private String message = null; - private String policyName = null; - private String policyScope = null; - private String date = null; - private String ecompName = null; - private String configName = null; - - public ConfigPolicyService(String policyName, String policyScope, - PolicyParameters policyParameters, String date) { - this.policyParameters = policyParameters; - this.policyName = policyName; - this.policyScope = policyScope; - this.date = date; - papServices = new PAPServices(); - } - - public Boolean getValidation() { - if(policyParameters.getConfigBody()==null || policyParameters.getConfigBody().trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given."; - return false; - } - if(policyParameters.getConfigBodyType()==null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body Type given."; - return false; - } - boolean levelCheck = false; - levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); - if (!levelCheck){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; - return false; - } - ecompName = policyParameters.getEcompName(); - configName = policyParameters.getConfigName(); - if(ecompName==null || ecompName.trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given."; - return false; - } - if(configName==null || configName.trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config Name given."; - return false; - } - message = PolicyUtils.emptyPolicyValidator(ecompName); - if(!message.contains("success")){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; - return false; - } - message = PolicyUtils.emptyPolicyValidator(configName); - if(!message.contains("success")){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; - return false; - } - return true; - } - - public String getMessage() { - return message; - } - - public String getResult(boolean updateFlag) throws PolicyException { - String response = null; - String operation = null; - if (updateFlag){ - operation = "update"; - } else { - operation = "create"; - } - String configType = policyParameters.getConfigBodyType().toString(); - String body = policyParameters.getConfigBody(); - String configBody = null; - //check body for JSON form and remove single quotes if present - if ("JSON".equalsIgnoreCase(configType)) { - if (body.contains("'")) { - configBody = body.replace("'", "\""); - } else { - configBody = body; - } - } else { - configBody = body; - } - Map configAttributes = null; - if(policyParameters.getAttributes()!=null){ - configAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING); - } - // create Policy. - StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Base", policyName, policyParameters.getPolicyDescription(), ecompName, configName, configAttributes, configType, - configBody, updateFlag, policyScope,0, policyParameters.getRiskLevel(),policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date); - // Send Json to PAP. - response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "Config"); - LOGGER.info(response); - return response; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java deleted file mode 100644 index 6dde8a276..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java +++ /dev/null @@ -1,118 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.HashMap; -import java.util.Map; - -import org.openecomp.policy.api.AttributeType; -import org.openecomp.policy.api.PolicyClass; -import org.openecomp.policy.api.PolicyConfigType; -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.api.PolicyType; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.models.ConfigPolicyAPIRequest; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.http.HttpStatus; - -public class CreateUpdateConfigPolicyService { - private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdateConfigPolicyService.class.getName()); - - private String response = null; - private HttpStatus status = HttpStatus.BAD_REQUEST; - - public CreateUpdateConfigPolicyService( - ConfigPolicyAPIRequest configPolicyAPIRequest, String requestID, - boolean updateFlag) { - try{ - run(configPolicyAPIRequest, requestID, updateFlag); - }catch(PolicyException e){ - response = XACMLErrorConstants.ERROR_DATA_ISSUE + e; - status = HttpStatus.BAD_REQUEST; - } - } - - private void run(ConfigPolicyAPIRequest configPolicyAPIRequest, - String requestID, boolean updateFlag) throws PolicyException{ - PolicyParameters policyParameters = new PolicyParameters(); - policyParameters.setPolicyClass(PolicyClass.Config); - policyParameters.setPolicyConfigType(PolicyConfigType.Base); - if(configPolicyAPIRequest.getPolicyScope()==null|| configPolicyAPIRequest.getPolicyScope().trim().isEmpty()){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; - LOGGER.error(message); - throw new PolicyException(message); - } - if(configPolicyAPIRequest.getPolicyName()==null|| configPolicyAPIRequest.getPolicyName().trim().isEmpty()){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - LOGGER.error(message); - throw new PolicyException(message); - } - policyParameters.setPolicyName(configPolicyAPIRequest.getPolicyScope()+"."+configPolicyAPIRequest.getPolicyName()); - policyParameters.setPolicyDescription(configPolicyAPIRequest.getPolicyDescription()); - policyParameters.setEcompName(configPolicyAPIRequest.getEcompName()); - policyParameters.setConfigName(configPolicyAPIRequest.getConfigName()); - Map> attributes = new HashMap<>(); - attributes.put(AttributeType.MATCHING, configPolicyAPIRequest.getConfigAttributes()); - policyParameters.setAttributes(attributes); - if(configPolicyAPIRequest.getConfigType()==null){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy ConfigType given."; - LOGGER.error(message); - throw new PolicyException(message); - } - try{ - policyParameters.setConfigBodyType(PolicyType.valueOf(configPolicyAPIRequest.getConfigType())); - }catch(IllegalArgumentException e){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Improper ConfigType given."; - LOGGER.error(message, e); - throw new PolicyException(message); - } - policyParameters.setConfigBody(configPolicyAPIRequest.getBody()); - policyParameters.setRiskLevel(configPolicyAPIRequest.getRiskLevel()); - policyParameters.setRiskType(configPolicyAPIRequest.getRiskType()); - policyParameters.setGuard(Boolean.parseBoolean(configPolicyAPIRequest.getGuard())); - if(configPolicyAPIRequest.getTtlDate()==null){ - LOGGER.warn("No TTL date given "); - policyParameters.setTtlDate(null); - }else{ - try { - policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(configPolicyAPIRequest.getTtlDate())); - } catch (ParseException e) { - LOGGER.warn("Error Parsing date given " + configPolicyAPIRequest.getTtlDate(), e); - policyParameters.setTtlDate(null); - } - } - CreateUpdatePolicyService createUpdatePolicyService = new CreateUpdatePolicyServiceImpl(policyParameters, requestID, updateFlag); - status = createUpdatePolicyService.getResponseCode(); - response = createUpdatePolicyService.getResult(); - } - - public String getResult() { - return response; - } - - public HttpStatus getResponseCode() { - return status; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java deleted file mode 100644 index 3c102fa68..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java +++ /dev/null @@ -1,153 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.io.ByteArrayInputStream; -import java.util.UUID; - -import javax.json.JsonException; -import javax.json.JsonObject; - -import org.openecomp.policy.api.DictionaryParameters; -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.http.HttpStatus; - -public class CreateUpdateDictionaryService { - private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdateDictionaryService.class.getName()); - - private String dictionaryResult = null; - private HttpStatus status = HttpStatus.BAD_REQUEST; - private String message = null; - private Boolean updateFlag = false; - private DictionaryParameters dictionaryParameters = null; - - public CreateUpdateDictionaryService( - DictionaryParameters dictionaryParameters, String requestID, - boolean updateFlag) { - this.updateFlag = updateFlag; - this.dictionaryParameters = dictionaryParameters; - if(dictionaryParameters.getRequestID()==null){ - UUID requestUUID = null; - if (requestID != null && !requestID.isEmpty()) { - try { - requestUUID = UUID.fromString(requestID); - } catch (IllegalArgumentException e) { - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString(),e); - } - }else{ - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); - } - this.dictionaryParameters.setRequestID(requestUUID); - } - try{ - run(); - specialCheck(); - }catch(PolicyException e){ - dictionaryResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e; - status = HttpStatus.BAD_REQUEST; - } - } - - private void specialCheck() { - if(dictionaryResult== null || dictionaryResult.contains("BAD REQUEST")||dictionaryResult.contains("PE300")){ - status = HttpStatus.BAD_REQUEST; - } else if (dictionaryResult.contains("Policy Exist Error")) { - status = HttpStatus.CONFLICT; - } else if (dictionaryResult.contains("PE200")){ - status = HttpStatus.INTERNAL_SERVER_ERROR; - } - } - - private void run() throws PolicyException{ - // Check Validation. - if(!getValidation()){ - LOGGER.error(message); - throw new PolicyException(message); - } - // Get Result. - try{ - status = HttpStatus.OK; - dictionaryResult = processResult(); - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - status = HttpStatus.BAD_REQUEST; - throw new PolicyException(e); - } - } - - private String processResult() throws PolicyException{ - String operation = null; - if (updateFlag){ - operation = "update"; - } else { - operation = "create"; - } - JsonObject json = null; - try{ - json = PolicyApiUtils.stringToJsonObject(dictionaryParameters.getDictionaryJson()); - } catch(JsonException| IllegalStateException e){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper Dictionary JSON object : " + dictionaryParameters.getDictionaryJson(); - LOGGER.error(message, e); - return message; - } - String dictionaryFields = json.toString(); - PAPServices papServices = new PAPServices(); - return (String) papServices.callPAP(new ByteArrayInputStream(dictionaryFields.getBytes()), new String[] {"operation="+operation, "apiflag=api", "dictionaryType="+dictionaryParameters.getDictionary()}, dictionaryParameters.getRequestID(), "dictionaryItem"); - } - - private boolean getValidation() { - if(dictionaryParameters==null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Dictionary Parameters are not given."; - return false; - } - if(dictionaryParameters.getDictionaryType()==null || dictionaryParameters.getDictionaryType().toString().trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Type given."; - return false; - } - if(dictionaryParameters.getDictionary()==null || dictionaryParameters.getDictionary().trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary given."; - return false; - } - if(dictionaryParameters.getDictionaryJson()==null || dictionaryParameters.getDictionaryJson().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary JSON given."; - return false; - } - if (updateFlag && "MicroServiceDictionary".equalsIgnoreCase(dictionaryParameters.getDictionary())&& !dictionaryParameters.getDictionaryJson().contains("initialFields")){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Mising the required field initialFields."; - return false; - } - return true; - } - - public String getResult() { - return dictionaryResult; - } - - public HttpStatus getResponseCode() { - return status; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java deleted file mode 100644 index 3e5dce15b..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.text.ParseException; -import java.text.SimpleDateFormat; - -import org.openecomp.policy.api.PolicyClass; -import org.openecomp.policy.api.PolicyConfigType; -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.models.ConfigFirewallPolicyAPIRequest; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.http.HttpStatus; - -public class CreateUpdateFirewallPolicyService { - private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdateFirewallPolicyService.class.getName()); - - private String response = null; - private HttpStatus status = HttpStatus.BAD_REQUEST; - - public CreateUpdateFirewallPolicyService( - ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest, - String requestID, boolean updateFlag) { - try{ - run(configFirewallPolicyAPIRequest, requestID, updateFlag); - }catch(PolicyException e){ - response = XACMLErrorConstants.ERROR_DATA_ISSUE + e; - status = HttpStatus.BAD_REQUEST; - } - } - - private void run( - ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest, - String requestID, boolean updateFlag) throws PolicyException{ - PolicyParameters policyParameters = new PolicyParameters(); - policyParameters.setPolicyClass(PolicyClass.Config); - policyParameters.setPolicyConfigType(PolicyConfigType.Firewall); - if(configFirewallPolicyAPIRequest.getPolicyScope()==null|| configFirewallPolicyAPIRequest.getPolicyScope().trim().isEmpty()){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; - LOGGER.error(message); - throw new PolicyException(message); - } - if(configFirewallPolicyAPIRequest.getPolicyName()==null|| configFirewallPolicyAPIRequest.getPolicyName().trim().isEmpty()){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - LOGGER.error(message); - throw new PolicyException(message); - } - policyParameters.setPolicyName(configFirewallPolicyAPIRequest.getPolicyScope()+"."+configFirewallPolicyAPIRequest.getPolicyName()); - policyParameters.setConfigBody(configFirewallPolicyAPIRequest.getFirewallJson()); - policyParameters.setRiskLevel(configFirewallPolicyAPIRequest.getRiskLevel()); - policyParameters.setRiskType(configFirewallPolicyAPIRequest.getRiskType()); - policyParameters.setGuard(Boolean.parseBoolean(configFirewallPolicyAPIRequest.getGuard())); - try { - policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(configFirewallPolicyAPIRequest.getTtlDate())); - } catch (NullPointerException | ParseException e) { - LOGGER.warn("Error Parsing date given " + configFirewallPolicyAPIRequest.getTtlDate(), e); - policyParameters.setTtlDate(null); - } - CreateUpdatePolicyService createUpdatePolicyService = new CreateUpdatePolicyServiceImpl(policyParameters, requestID, updateFlag); - status = createUpdatePolicyService.getResponseCode(); - response = createUpdatePolicyService.getResult(); - } - - public String getResult() { - return response; - } - - public HttpStatus getResponseCode() { - return status; - } - -} \ No newline at end of file diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyService.java deleted file mode 100644 index 73f9e7448..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyService.java +++ /dev/null @@ -1,35 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import org.openecomp.policy.api.PolicyException; -import org.springframework.http.HttpStatus; - -public interface CreateUpdatePolicyService { - - public void run() throws PolicyException; - - public String processResult() throws PolicyException; - - public String getResult(); - - public HttpStatus getResponseCode(); - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java deleted file mode 100644 index cf2171137..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java +++ /dev/null @@ -1,293 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.UUID; - -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; -import org.openecomp.policy.utils.PolicyUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.http.HttpStatus; - -public class CreateUpdatePolicyServiceImpl implements CreateUpdatePolicyService { - private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdatePolicyServiceImpl.class.getName()); - - private String policyResult = null; - private HttpStatus status = HttpStatus.BAD_REQUEST; - private Boolean updateFlag = false; - private String message = null; - private PolicyParameters policyParameters = new PolicyParameters(); - private String policyName = null; - private String policyScope = null; - private String date = null; - - public CreateUpdatePolicyServiceImpl(PolicyParameters policyParameters, - String requestID, boolean updateFlag) { - this.updateFlag = updateFlag; - this.policyParameters = policyParameters; - if(policyParameters.getRequestID()==null){ - UUID requestUUID = null; - if (requestID != null && !requestID.isEmpty()) { - try { - requestUUID = UUID.fromString(requestID); - } catch (IllegalArgumentException e) { - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); - } - }else{ - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); - } - this.policyParameters.setRequestID(requestUUID); - } - try{ - run(); - specialCheck(); - }catch(PolicyException e){ - policyResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e; - status = HttpStatus.BAD_REQUEST; - } - } - - public void run() throws PolicyException{ - // Check Validation. - if(!getValidation()){ - LOGGER.error(message); - throw new PolicyException(message); - } - // Get Result. - try{ - status = HttpStatus.OK; - policyResult = processResult(); - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - status = HttpStatus.BAD_REQUEST; - throw new PolicyException(e); - } - } - - @SuppressWarnings("incomplete-switch") - public String processResult() throws PolicyException{ - String response = null; - if(policyParameters.getPolicyConfigType()!=null){ - // This is a Config Type Policy. - switch(policyParameters.getPolicyConfigType()){ - case BRMS_PARAM: - BRMSParamPolicyService bRMSParamPolicyService = new BRMSParamPolicyService(policyName, policyScope, policyParameters, date); - // Check Validation. - if(!bRMSParamPolicyService.getValidation()){ - LOGGER.error(bRMSParamPolicyService.getMessage()); - status = HttpStatus.BAD_REQUEST; - return bRMSParamPolicyService.getMessage(); - } - // Get Result. - response = bRMSParamPolicyService.getResult(updateFlag); - break; - case BRMS_RAW: - BRMSRawPolicyService bRMSRawPolicyService = new BRMSRawPolicyService(policyName, policyScope, policyParameters, date); - // Check Validation. - if(!bRMSRawPolicyService.getValidation()){ - LOGGER.error(bRMSRawPolicyService.getMessage()); - status = HttpStatus.BAD_REQUEST; - return bRMSRawPolicyService.getMessage(); - } - // Get Result. - response = bRMSRawPolicyService.getResult(updateFlag); - break; - case Base: - ConfigPolicyService configPolicyService = new ConfigPolicyService(policyName, policyScope, policyParameters, date); - // Check Validation. - if(!configPolicyService.getValidation()){ - LOGGER.error(configPolicyService.getMessage()); - status = HttpStatus.BAD_REQUEST; - return configPolicyService.getMessage(); - } - // Get Result. - response = configPolicyService.getResult(updateFlag); - break; - case ClosedLoop_Fault: - ClosedLoopFaultPolicyService closedLoopFaultPolicyService = new ClosedLoopFaultPolicyService(policyName, policyScope, policyParameters, date); - // Check Validation. - if(!closedLoopFaultPolicyService.getValidation()){ - LOGGER.error(closedLoopFaultPolicyService.getMessage()); - status = HttpStatus.BAD_REQUEST; - return closedLoopFaultPolicyService.getMessage(); - } - // Get Result. - response = closedLoopFaultPolicyService.getResult(updateFlag); - break; - case ClosedLoop_PM: - ClosedLoopPMPolicyService closedLoopPMPolicyService = new ClosedLoopPMPolicyService(policyName, policyScope, policyParameters, date); - // Check Validation. - if(!closedLoopPMPolicyService.getValidation()){ - LOGGER.error(closedLoopPMPolicyService.getMessage()); - status = HttpStatus.BAD_REQUEST; - return closedLoopPMPolicyService.getMessage(); - } - // Get Result. - response = closedLoopPMPolicyService.getResult(updateFlag); - break; - case Firewall: - FirewallPolicyService firewallPolicyService = new FirewallPolicyService(policyName, policyScope, policyParameters, date); - // Check Validation. - if(!firewallPolicyService.getValidation()){ - LOGGER.error(firewallPolicyService.getMessage()); - status = HttpStatus.BAD_REQUEST; - return firewallPolicyService.getMessage(); - } - // Get Result. - response = firewallPolicyService.getResult(updateFlag); - break; - case MicroService: - MicroServicesPolicyService microServicesPolicyService = new MicroServicesPolicyService(policyName, policyScope, policyParameters, date); - // Check Validation. - if(!microServicesPolicyService.getValidation()){ - LOGGER.error(microServicesPolicyService.getMessage()); - status = HttpStatus.BAD_REQUEST; - return microServicesPolicyService.getMessage(); - } - // Get Result. - response = microServicesPolicyService.getResult(updateFlag); - break; - default: - String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " Invalid Config Type Present"; - LOGGER.error(message); - status = HttpStatus.BAD_REQUEST; - return message; - } - }else if (policyParameters.getPolicyClass()!=null){ - switch (policyParameters.getPolicyClass()){ - case Action: - ActionPolicyService actionPolicyService = new ActionPolicyService(policyScope, policyName, policyParameters); - // Check Validation. - if(!actionPolicyService.getValidation()){ - LOGGER.error(actionPolicyService.getMessage()); - status = HttpStatus.BAD_REQUEST; - return actionPolicyService.getMessage(); - } - // Get Result. - response = actionPolicyService.getResult(updateFlag); - break; - case Decision: - DecisionPolicyService decisionPolicyService = new DecisionPolicyService(policyScope, policyName, policyParameters); - // Check Validation. - if(!decisionPolicyService.getValidation()){ - LOGGER.error(decisionPolicyService.getMessage()); - status = HttpStatus.BAD_REQUEST; - return decisionPolicyService.getMessage(); - } - // Get Result. - response = decisionPolicyService.getResult(updateFlag); - break; - } - }else { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Class found."; - LOGGER.error(message); - status = HttpStatus.BAD_REQUEST; - response = message; - } - return response; - } - - protected boolean getValidation() { - if(policyParameters == null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy parameters given. "; - return false; - } - if(policyParameters.getPolicyName() == null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - return false; - } - if (policyParameters.getPolicyName().contains(".")) { - policyName = policyParameters.getPolicyName().substring(policyParameters.getPolicyName().lastIndexOf('.') + 1, - policyParameters.getPolicyName().length()); - policyScope = policyParameters.getPolicyName().substring(0,policyParameters.getPolicyName().lastIndexOf('.')); - LOGGER.info("Name is " + policyName + " scope is " + policyScope); - } else { - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; - return false; - } - if (policyName==null||policyName.trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - return false; - } - message = PolicyUtils.emptyPolicyValidator(policyScope); - if(!message.contains("success")){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; - return false; - } - message = PolicyUtils.emptyPolicyValidator(policyName); - if(!message.contains("success")){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; - return false; - } - if(policyParameters.getPolicyDescription()!=null){ - message = PolicyUtils.descriptionValidator(policyParameters.getPolicyDescription()); - if(!message.contains("success")){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; - return false; - } - } - if(!PolicyApiUtils.validateNONASCIICharactersAndAllowSpaces(policyParameters.toString())){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "This requests contains Non ASCII Characters. Please review your input parameter" - + " values and correct the illegal characters."; - return false; - } - // Set some default Values. - if (policyParameters.getTtlDate()!=null){ - date = convertDate(policyParameters.getTtlDate()); - } - return true; - } - - protected String convertDate(Date date) { - String strDate = null; - if (date!=null) { - SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy"); - strDate = dateformatJava.format(date); - } - return (strDate==null) ? "NA": strDate; - } - - protected void specialCheck() { - if(policyResult== null || policyResult.contains("BAD REQUEST")||policyResult.contains("PE300")){ - status = HttpStatus.BAD_REQUEST; - } else if (policyResult.contains("Policy Exist Error")) { - status = HttpStatus.CONFLICT; - } else if (policyResult.contains("PE200")||policyResult.contains("PE900")){ - status = HttpStatus.INTERNAL_SERVER_ERROR; - } - } - - public String getResult() { - return policyResult; - } - - public HttpStatus getResponseCode() { - return status; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DecisionPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DecisionPolicyService.java deleted file mode 100644 index c6789a0b8..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DecisionPolicyService.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.util.Map; - -import org.openecomp.policy.api.AttributeType; -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.api.RuleProvider; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; - -/** - * Decision Policy Implementation - * - * @version 0.1 - */ -public class DecisionPolicyService{ - private static Logger LOGGER = FlexLogger.getLogger(DecisionPolicyService.class.getName()); - private static PAPServices papServices = null; - - private String message = null; - private String policyScope = null; - private String policyName = null; - private PolicyParameters policyParameters = null; - private String ecompName = null; - - public DecisionPolicyService(String policyScope, String policyName, - PolicyParameters policyParameters) { - this.policyScope = policyScope; - this.policyName = policyName; - this.policyParameters = policyParameters; - papServices = new PAPServices(); - } - - public Boolean getValidation() { - ecompName = policyParameters.getEcompName(); - if (ecompName==null||ecompName.trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given."; - return false; - } - return true; - } - - public String getMessage() { - return message; - } - - public String getResult(boolean updateFlag) throws PolicyException { - String response = null; - String operation = null; - if (updateFlag){ - operation = "update"; - } else { - operation = "create"; - } - RuleProvider ruleProvider = policyParameters.getRuleProvider(); - if (ruleProvider==null) { - ruleProvider = RuleProvider.CUSTOM ; - } - Map matchingAttributes = null; - Map settingsAttributes = null; - if (policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)) { - matchingAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING); - settingsAttributes = policyParameters.getAttributes().get(AttributeType.SETTINGS); - }else if(policyParameters.getAttributes()!=null && !policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){ - settingsAttributes = policyParameters.getAttributes().get(AttributeType.SETTINGS); - }else if(policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && !policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){ - matchingAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING); - } - // Create Policy. - StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyName, policyParameters.getPolicyDescription(), ecompName, ruleProvider.toString(), matchingAttributes, settingsAttributes, policyParameters.getDynamicRuleAlgorithmLabels(), - policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmField2(), null, null, null, updateFlag, policyScope, 0); - // Send JSON to PAP. - response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Decision"}, policyParameters.getRequestID(), "Decision"); - LOGGER.info(message); - return response; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DeletePolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DeletePolicyService.java deleted file mode 100644 index 3b1ea23fb..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/DeletePolicyService.java +++ /dev/null @@ -1,258 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.io.File; -import java.util.UUID; - -import org.openecomp.policy.api.DeletePolicyParameters; -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; -import org.springframework.http.HttpStatus; - -public class DeletePolicyService { - private static final Logger LOGGER = FlexLogger.getLogger(DeletePolicyService.class.getName()); - - private String deleteResult = null; - private HttpStatus status = HttpStatus.BAD_REQUEST; - private DeletePolicyParameters deletePolicyParameters = null; - private String message = null; - private String filePrefix = null; - private String clientScope = null; - private String policyType = null; - private String policyName = null; - private String policyScope = null; - - public DeletePolicyService(DeletePolicyParameters deletePolicyParameters, - String requestID) { - this.deletePolicyParameters = deletePolicyParameters; - if(deletePolicyParameters.getRequestID()==null){ - UUID requestUUID = null; - if (requestID != null && !requestID.isEmpty()) { - try { - requestUUID = UUID.fromString(requestID); - } catch (IllegalArgumentException e) { - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); - } - }else{ - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); - } - this.deletePolicyParameters.setRequestID(requestUUID); - } - try{ - run(); - specialCheck(); - }catch(PolicyException e){ - deleteResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e; - status = HttpStatus.BAD_REQUEST; - } - } - - private void specialCheck() { - if(deleteResult==null){ - return; - } - if (deleteResult.contains("BAD REQUEST")||deleteResult.contains("PE300")||deleteResult.contains("PE200")||deleteResult.contains("not exist")||deleteResult.contains("Invalid policyName")) { - status = HttpStatus.BAD_REQUEST; - } else if (deleteResult.contains("locked down")){ - status = HttpStatus.ACCEPTED; - } else if (deleteResult.contains("not Authorized")) { - status = HttpStatus.FORBIDDEN; - } else if (deleteResult.contains("groupId")) { - status = HttpStatus.NOT_FOUND; - } else if (deleteResult.contains("JPAUtils")||deleteResult.contains("database")||deleteResult.contains("policy file")|| - deleteResult.contains("unknown")||deleteResult.contains("configuration")) { - status = HttpStatus.INTERNAL_SERVER_ERROR; - } - } - - private void run() throws PolicyException{ - // Check Validation. - if(!getValidation()){ - LOGGER.error(message); - throw new PolicyException(message); - } - // Get Result. - try{ - status = HttpStatus.OK; - deleteResult = processResult(); - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - status = HttpStatus.BAD_REQUEST; - throw new PolicyException(e); - } - } - - private String processResult() throws PolicyException{ - String response = null; - String fullPolicyName = null; - String pdpGroup = deletePolicyParameters.getPdpGroup(); - // PDP Group Check. - if (pdpGroup==null){ - pdpGroup="NA"; - } - PAPServices papServices = new PAPServices(); - if (!deletePolicyParameters.getPolicyName().contains("xml")) { - - String activeVersion = papServices.getActiveVersion(policyScope, filePrefix, policyName, clientScope, deletePolicyParameters.getRequestID()); - LOGGER.debug("The active version of " + policyScope + File.separator + filePrefix + policyName + " is " + activeVersion); - String id = null; - if ("pe100".equalsIgnoreCase(activeVersion)) { - response = XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is 403. PEP is not Authorized for making this Request!! " - + "Contact Administrator for this Scope. "; - LOGGER.error(response); - return response; - } else if ("pe300".equalsIgnoreCase(activeVersion)) { - response = XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404. " - + "This indicates a problem with getting the version from the PAP or the policy does not exist."; - LOGGER.error(response); - return response; - } - if (!activeVersion.equalsIgnoreCase("0")) { - id = policyScope + "." + filePrefix + policyName + "." + activeVersion + ".xml"; - LOGGER.debug("The policyId is " + id); - } else { - response = XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the activeVersion for this policy. could not retrieve the activeVersion for this policy. " - + "This indicates the policy does not exist, please verify the policy exists."; - LOGGER.error(response); - return response; - } - - fullPolicyName = policyScope + "." + filePrefix + policyName + "." + activeVersion + ".xml"; - - } else { - fullPolicyName = policyName; - } - - if ("PAP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())) { - if (deletePolicyParameters.getDeleteCondition()==null||deletePolicyParameters.getDeleteCondition().toString().trim().isEmpty()){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Delete Condition given."; - LOGGER.error(message); - return message; - } - - StdPAPPolicy deletePapPolicy = new StdPAPPolicy(fullPolicyName, deletePolicyParameters.getDeleteCondition().toString()); - //send JSON object to PAP - response = (String) papServices.callPAP(deletePapPolicy, new String[] {"groupId="+pdpGroup, "apiflag=deletePapApi", "operation=delete" }, deletePolicyParameters.getRequestID(), clientScope); - } else if ("PDP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())) { - if (deletePolicyParameters.getPdpGroup()==null||deletePolicyParameters.getPdpGroup().trim().isEmpty()){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PDP Group given."; - LOGGER.error(message); - return message; - } - //send JSON object to PAP - response = (String) papServices.callPAP(null, new String[] {"policyName="+fullPolicyName, "groupId="+pdpGroup, "apiflag=deletePdpApi", "operation=delete" }, deletePolicyParameters.getRequestID(), clientScope); - } else { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Component does not exist. Please enter either PAP or PDP to delete the policy from a specified Policy Component."; - LOGGER.error(message); - response = message; - } - return response; - } - - private boolean getValidation() { - // While Validating, extract the required values. - if (deletePolicyParameters.getPolicyName()==null||deletePolicyParameters.getPolicyName().trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - return false; - } - if (!deletePolicyParameters.getPolicyName().contains("xml")) { - if (deletePolicyParameters.getPolicyName() != null - && deletePolicyParameters.getPolicyName().contains(".")) { - policyName = deletePolicyParameters.getPolicyName().substring(deletePolicyParameters.getPolicyName().lastIndexOf(".") + 1, - deletePolicyParameters.getPolicyName().length()); - policyScope = deletePolicyParameters.getPolicyName().substring(0,deletePolicyParameters.getPolicyName().lastIndexOf(".")); - LOGGER.info("Name is " + policyName + " scope is " + policyScope); - } else { - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; - return false; - } - } else { - policyName = deletePolicyParameters.getPolicyName(); - } - policyType = deletePolicyParameters.getPolicyType(); - if(policyType== null || policyType.trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PolicyType given."; - return false; - } - setClientScope(); - if (clientScope==null||clientScope.trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + deletePolicyParameters.getPolicyType() + " is not a valid Policy Type."; - LOGGER.error(message); - return false; - } - LOGGER.debug("clientScope is " + clientScope); - LOGGER.debug("filePrefix is " + filePrefix); - if(deletePolicyParameters.getPolicyComponent()==null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Component given."; - return false; - } - return true; - } - - private void setClientScope() { - if ("Firewall".equalsIgnoreCase(policyType)) { - clientScope = "ConfigFirewall"; - filePrefix = "Config_FW_"; - } else if ("Action".equalsIgnoreCase(policyType)) { - clientScope = "Action"; - filePrefix = "Action_"; - } else if ("Decision".equalsIgnoreCase(policyType)) { - clientScope = "Decision"; - filePrefix = "Decision_"; - } else if ("Base".equalsIgnoreCase(policyType)) { - clientScope = "Config"; - filePrefix = "Config_"; - } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyType)) { - clientScope = "ConfigClosedLoop"; - filePrefix = "Config_Fault_"; - } else if ("ClosedLoop_PM".equalsIgnoreCase(policyType)) { - clientScope = "ConfigClosedLoop"; - filePrefix = "Config_PM_"; - } else if ("MicroService".equalsIgnoreCase(policyType)) { - clientScope = "ConfigMS"; - filePrefix = "Config_MS_"; - }else if ("BRMS_RAW".equalsIgnoreCase(policyType)) { - clientScope = "ConfigBrmsRaw"; - filePrefix = "Config_BRMS_Raw_"; - } else if ("BRMS_PARAM".equalsIgnoreCase(policyType)) { - clientScope = "ConfigBrmsParam"; - filePrefix = "Config_BRMS_Param_"; - } else { - clientScope = null; - message = XACMLErrorConstants.ERROR_DATA_ISSUE + policyType - + " is not a valid Policy Type."; - } - } - - public String getResult() { - return deleteResult; - } - - public HttpStatus getResponseCode() { - return status; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/FirewallPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/FirewallPolicyService.java deleted file mode 100644 index f301bf05d..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/FirewallPolicyService.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import javax.json.JsonException; -import javax.json.JsonObject; - -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; - -/** - * Firewall Policy Implementation. - * - * @version 0.1 - */ -public class FirewallPolicyService { - private static final Logger LOGGER = FlexLogger.getLogger(FirewallPolicyService.class.getName()); - - private PAPServices papServices = null; - private PolicyParameters policyParameters = null; - private String message = null; - private String policyName = null; - private String policyScope = null; - private String date = null; - private JsonObject firewallJson = null; - - public FirewallPolicyService(String policyName, String policyScope, - PolicyParameters policyParameters, String date) { - this.policyParameters = policyParameters; - this.policyName = policyName; - this.policyScope = policyScope; - this.date = date; - papServices = new PAPServices(); - } - - public Boolean getValidation() { - if(policyParameters.getConfigBody()==null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given."; - return false; - } - try{ - firewallJson = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); - } catch(JsonException| IllegalStateException e){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); - LOGGER.error("Error while parsing JSON body for creating Firewall Policy " , e); - return false; - } - if(firewallJson==null|| firewallJson.isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config-Body given."; - return false; - } - boolean levelCheck = false; - levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); - if (!levelCheck){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; - return false; - } - return true; - } - - public String getMessage() { - return message; - } - - public String getResult(boolean updateFlag) throws PolicyException { - String response = null; - String operation = null; - if (updateFlag){ - operation = "update"; - } else { - operation = "create"; - } - //set values for basic policy information - if(!firewallJson.containsKey("configName")){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No configName given in firwall JSON."; - LOGGER.error(message); - return message; - } - String configName = firewallJson.get("configName").toString(); - String configDescription = ""; - String json = firewallJson.toString(); - // Create Policy. - StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Firewall Config", policyName, configDescription, configName, updateFlag, policyScope, json, 0, - policyParameters.getRiskLevel(),policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date); - // Send Json to PAP. - response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigFirewall"); - LOGGER.info(response); - return response; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetConfigService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetConfigService.java deleted file mode 100644 index 2363877b2..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetConfigService.java +++ /dev/null @@ -1,318 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.json.Json; -import javax.json.JsonArrayBuilder; -import javax.json.JsonObject; -import javax.json.JsonObjectBuilder; - -import org.openecomp.policy.api.ConfigRequestParameters; -import org.openecomp.policy.api.PolicyConfigException; -import org.openecomp.policy.api.PolicyConfigStatus; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.models.PDPResponse; -import org.openecomp.policy.pdp.rest.api.models.PolicyConfig; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.http.HttpStatus; - -public class GetConfigService { - private static final Logger LOGGER = FlexLogger.getLogger(GetConfigService.class.getName()); - - private ConfigRequestParameters configRequestParameters = null; - private String message = null; - private HttpStatus responseCode = HttpStatus.BAD_REQUEST; - private Collection policyConfigs = null; - private boolean unique = false; - - public GetConfigService(ConfigRequestParameters configRequestParameters, - String requestID){ - this.configRequestParameters = configRequestParameters; - if(configRequestParameters.getRequestID()==null){ - UUID requestUUID = null; - if (requestID != null && !requestID.isEmpty()) { - try { - requestUUID = UUID.fromString(requestID); - } catch (IllegalArgumentException e) { - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString(),e); - } - }else{ - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); - } - this.configRequestParameters.setRequestID(requestUUID); - } - policyConfigs = new ArrayList<>(); - try{ - run(); - specialCheck(); - }catch(PolicyConfigException e){ - LOGGER.error(e); - PolicyConfig policyConfig = new PolicyConfig(); - policyConfig.setPolicyConfigMessage(e.getMessage()); - policyConfig.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); - policyConfigs.add(policyConfig); - responseCode = HttpStatus.BAD_REQUEST; - } - } - - private void specialCheck() { - if(policyConfigs==null || policyConfigs.isEmpty()){ - responseCode = HttpStatus.BAD_REQUEST; - }else if(policyConfigs.size()==1){ - for(PolicyConfig policyConfig: policyConfigs){ - if(policyConfig.getPolicyConfigMessage()!=null && policyConfig.getPolicyConfigMessage().contains("PE300")){ - responseCode = HttpStatus.BAD_REQUEST; - } - } - }else{ - responseCode = HttpStatus.OK; - } - } - - private void run() throws PolicyConfigException{ - // getValidation. - if(!getValidation()){ - LOGGER.error(message); - throw new PolicyConfigException(message); - } - // Generate Request. - String modelString = getModel().toString(); - LOGGER.debug("Generated JSON Request is: " + modelString); - if(configRequestParameters.getUnique()){ - LOGGER.info("Requested for Unique Result only. "); - unique = true; - } - // Process Result. - try { - PDPServices pdpServices = new PDPServices(); - responseCode = HttpStatus.OK; - policyConfigs = configResult(pdpServices.generateRequest(modelString, configRequestParameters.getRequestID(), unique, false)); - // Filter addition. - policyConfigs = filterResults(policyConfigs, configRequestParameters); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - responseCode = HttpStatus.BAD_REQUEST; - throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e); - } - } - - private Collection configResult( - Collection generateRequest) { - Collection result = new HashSet<>(); - if (generateRequest == null) { - return null; - } - if (!generateRequest.isEmpty()) { - for (PDPResponse stdStatus : generateRequest) { - PolicyConfig policyConfig = new PolicyConfig(); - policyConfig.setConfig(stdStatus.getConfig()); - policyConfig.setMatchingConditions(stdStatus.getMatchingConditions()); - policyConfig.setPolicyConfigMessage(stdStatus.getPolicyConfigMessage()); - policyConfig.setPolicyConfigStatus(stdStatus.getPolicyConfigStatus()); - policyConfig.setPolicyName(stdStatus.getPolicyName()); - policyConfig.setPolicyVersion(stdStatus.getPolicyVersion()); - policyConfig.setProperty(stdStatus.getProperty()); - policyConfig.setResponseAttributes(stdStatus.getResponseAttributes()); - policyConfig.setType(stdStatus.getType()); - result.add(policyConfig); - } - } - return result; - } - - // Filter logic required for results comparing with requests. - private Collection filterResults( - Collection policyConfigs, - ConfigRequestParameters configRequestParameters) { - List policyConfig = new ArrayList<>(); - for(PolicyConfig config: policyConfigs){ - if(config.getPolicyName()!=null && configRequestParameters.getPolicyName()!=null && configRequestParameters.getPolicyName().trim().length()>0){ - if(!config.getPolicyName().matches(configRequestParameters.getPolicyName())){ - continue; - } - } - if(config.getMatchingConditions()!=null && config.getMatchingConditions().size()>0){ - if(configRequestParameters.getEcompName()!=null && configRequestParameters.getEcompName().trim().length()>0 && config.getMatchingConditions().containsKey("ECOMPName")){ - if(!config.getMatchingConditions().get("ECOMPName").matches(configRequestParameters.getEcompName())){ - continue; - } - } - if(configRequestParameters.getConfigName()!=null && configRequestParameters.getConfigName().trim().length()>0 && config.getMatchingConditions().containsKey("ConfigName")){ - if(!config.getMatchingConditions().get("ConfigName").matches(configRequestParameters.getConfigName())){ - continue; - } - } - if(configRequestParameters.getConfigAttributes()!=null && configRequestParameters.getConfigAttributes().size()>0){ - boolean flag = false; - for(String key: configRequestParameters.getConfigAttributes().keySet()){ - if(key.equals("RiskType")||key.equals("RiskLevel")||key.equals("guard")||key.equals("TTLDate")){ - continue; - } - if(config.getMatchingConditions().containsKey(key)){ - if(config.getMatchingConditions().get(key).contains(",")){ - List elements = Arrays.asList(config.getMatchingConditions().get(key).split(",")); - if(!elements.contains(configRequestParameters.getConfigAttributes().get(key))){ - flag=true; - } - }else if(!config.getMatchingConditions().get(key).matches(configRequestParameters.getConfigAttributes().get(key))){ - flag = true; - } - }else{ - flag = true; - } - if(flag){ - break; - } - } - if(flag){ - continue; - } - } - } - policyConfig.add(config); - } - if(policyConfig.isEmpty()){ - PolicyConfig pConfig = new PolicyConfig(); - pConfig.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); - pConfig.setPolicyConfigMessage(XACMLErrorConstants.ERROR_DATA_ISSUE+"No Match Found, for the parameters sent."); - policyConfig.add(pConfig); - } - return policyConfig; - } - - private JsonObject getModel() throws PolicyConfigException{ - String policyName = configRequestParameters.getPolicyName(); - if(policyName!= null && !policyName.trim().isEmpty() && !policyName.endsWith("xml")){ - policyName = policyName + ".[\\d].*"; - configRequestParameters.setPolicyName(policyName); - } - JsonArrayBuilder subjectArray = Json.createArrayBuilder(); - JsonArrayBuilder resourceArray = Json.createArrayBuilder(); - if(configRequestParameters.getPolicyName()!=null){ - JsonObjectBuilder subjectBuilder = Json.createObjectBuilder(); - subjectBuilder.add("Value", policyName); - subjectBuilder.add("AttributeId", "PolicyName"); - subjectArray.add(subjectBuilder); - }else{ - LOGGER.info("PolicyName values are not given. "); - } - if(configRequestParameters.getEcompName()!=null){ - JsonObjectBuilder subjectBuilder = Json.createObjectBuilder(); - subjectBuilder.add("Value", configRequestParameters.getEcompName()); - subjectBuilder.add("AttributeId", "ECOMPName"); - subjectArray.add(subjectBuilder); - if(configRequestParameters.getConfigName()!=null){ - subjectBuilder = Json.createObjectBuilder(); - subjectBuilder.add("Value", configRequestParameters.getConfigName()); - subjectBuilder.add("AttributeId", "ConfigName"); - subjectArray.add(subjectBuilder); - resourceArray = getResourceArray(configRequestParameters.getConfigAttributes()); - }else{ - LOGGER.info("Config Name is not given. "); - } - }else{ - LOGGER.info("Ecomp Name is not given. "); - } - return Json.createObjectBuilder() - .add("Request",Json.createObjectBuilder() - .add("AccessSubject",Json.createObjectBuilder() - .add("Attribute",subjectArray)) - .add("Action",Json.createObjectBuilder() - .add("Attribute",Json.createObjectBuilder() - .add("Value","ACCESS") - .add("AttributeId","urn:oasis:names:tc:xacml:1.0:action:action-id"))) - .add("Resource",Json.createObjectBuilder() - .add("Attribute",resourceArray - .add(Json.createObjectBuilder() - .add("Value","Config") - .add("AttributeId","urn:oasis:names:tc:xacml:1.0:resource:resource-id"))))) - .build(); - } - - private JsonArrayBuilder getResourceArray(Map configAttributes) throws PolicyConfigException{ - JsonArrayBuilder resourceArray = Json.createArrayBuilder(); - configAttributes = configRequestParameters.getConfigAttributes(); - if (configAttributes != null && !configAttributes.isEmpty()) { - if(!configAttributes.containsKey("RiskType")){ - configAttributes.put("RiskType", ".*"); - } - if(!configAttributes.containsKey("RiskLevel")){ - configAttributes.put("RiskLevel", ".*"); - } - if(!configAttributes.containsKey("guard")){ - configAttributes.put("guard", ".*"); - } - if(!configAttributes.containsKey("TTLDate")){ - configAttributes.put("TTLDate", ".*"); - } - }else{ - // ConfigAttributes is Null. So add basic values. - configAttributes = new HashMap<>(); - configAttributes.put("RiskType", ".*"); - configAttributes.put("RiskLevel", ".*"); - configAttributes.put("guard", ".*"); - configAttributes.put("TTLDate", ".*"); - } - for (String key : configAttributes.keySet()) { - if (key.isEmpty()) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key"; - LOGGER.error(message); - throw new PolicyConfigException(message); - } - JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); - resourceBuilder.add("Value", configAttributes.get(key)); - resourceBuilder.add("AttributeId", key); - resourceArray.add(resourceBuilder); - } - return resourceArray; - } - - private Boolean getValidation(){ - if(configRequestParameters==null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No config Request Parameters given."; - return false; - } - if(configRequestParameters.getEcompName()==null && configRequestParameters.getPolicyName()==null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot proceed without eCOMPComponentName or PolicyName"; - return false; - } - return true; - } - - public Collection getResult() { - return policyConfigs; - } - - public HttpStatus getResponseCode() { - return responseCode; - } -} \ No newline at end of file diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDecisionService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDecisionService.java deleted file mode 100644 index 1ef5e53cf..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDecisionService.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.util.Collection; -import java.util.Map; -import java.util.Map.Entry; -import java.util.UUID; - -import javax.json.Json; -import javax.json.JsonArrayBuilder; -import javax.json.JsonObject; -import javax.json.JsonObjectBuilder; - -import org.openecomp.policy.api.DecisionRequestParameters; -import org.openecomp.policy.api.DecisionResponse; -import org.openecomp.policy.api.PolicyDecision; -import org.openecomp.policy.api.PolicyDecisionException; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.models.PDPResponse; -import org.openecomp.policy.std.StdDecisionResponse; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.http.HttpStatus; - -public class GetDecisionService { - private static final Logger LOGGER = FlexLogger.getLogger(GetDecisionService.class.getName()); - - private DecisionResponse decisionResponse = null; - private HttpStatus status = HttpStatus.BAD_REQUEST; - private DecisionRequestParameters decisionRequestParameters = null; - private String message = null; - private String eCOMPComponentName = null; - private Map decisionAttributes = null; - - public GetDecisionService( - DecisionRequestParameters decisionRequestParameters, - String requestID) { - this.decisionRequestParameters = decisionRequestParameters; - if(decisionRequestParameters.getRequestID()==null){ - UUID requestUUID = null; - if (requestID != null && !requestID.isEmpty()) { - try { - requestUUID = UUID.fromString(requestID); - } catch (IllegalArgumentException e) { - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString(),e); - } - }else{ - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); - } - this.decisionRequestParameters.setRequestID(requestUUID); - } - try{ - run(); - }catch(PolicyDecisionException e){ - StdDecisionResponse decisionResponse = new StdDecisionResponse(); - decisionResponse.setDecision(PolicyDecision.ERROR); - decisionResponse.setDetails(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - this.decisionResponse = decisionResponse; - status = HttpStatus.BAD_REQUEST; - } - } - - private void run() throws PolicyDecisionException{ - // Get Validation. - if(!getValidation()){ - LOGGER.error(message); - throw new PolicyDecisionException(message); - } - // Generate Request. - String modelString = getModel().toString(); - LOGGER.debug("Generated JSON Request is: " + modelString); - // Process Result. - try { - PDPServices pdpServices = new PDPServices(); - status = HttpStatus.OK; - decisionResponse = decisionResult(pdpServices.generateRequest(modelString, decisionRequestParameters.getRequestID(), false, true)); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - status = HttpStatus.BAD_REQUEST; - throw new PolicyDecisionException(e); - } - } - - private DecisionResponse decisionResult( - Collection generateRequest) { - StdDecisionResponse policyDecision = new StdDecisionResponse(); - if (generateRequest == null) { - return policyDecision; - } - if (!generateRequest.isEmpty()) { - for (PDPResponse stdStatus : generateRequest) { - policyDecision.setDecision(stdStatus.getDecision()); - policyDecision.setDetails(stdStatus.getDetails()); - } - } - return policyDecision; - } - - private JsonObject getModel() throws PolicyDecisionException{ - JsonArrayBuilder resourceArray = Json.createArrayBuilder(); - for (Entry key : decisionAttributes.entrySet()) { - if (key.getKey().isEmpty()) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key"; - LOGGER.error(message); - throw new PolicyDecisionException(message); - } - JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); - if (key.getValue().matches("[0-9]+")) { - - if ((key.getKey().equals("ErrorCode")) || (key.getKey().equals("WorkStep"))) { - - resourceBuilder.add("Value", key.getValue()); - - } else { - - int val = Integer.parseInt(key.getValue()); - resourceBuilder.add("Value", val); - - } - - } else { - resourceBuilder.add("Value", key.getValue()); - } - resourceBuilder.add("AttributeId", key.getKey()); - resourceArray.add(resourceBuilder); - } - return Json.createObjectBuilder() - .add("Request", Json.createObjectBuilder() - .add("AccessSubject", Json.createObjectBuilder() - .add("Attribute", Json.createObjectBuilder() - .add("Value", eCOMPComponentName) - .add("AttributeId", "ECOMPName"))) - .add("Resource", Json.createObjectBuilder() - .add("Attribute", resourceArray)) - .add("Action", Json.createObjectBuilder() - .add("Attribute", Json.createObjectBuilder() - .add("Value", "DECIDE") - .add("AttributeId", "urn:oasis:names:tc:xacml:1.0:action:action-id")))) - .build(); - } - - private boolean getValidation() { - if(decisionRequestParameters==null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Paramaters"; - return false; - } - eCOMPComponentName = decisionRequestParameters.getECOMPComponentName(); - decisionAttributes = decisionRequestParameters.getDecisionAttributes(); - if (eCOMPComponentName == null || eCOMPComponentName.isEmpty()) { - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given : " + eCOMPComponentName; - return false; - } - if (decisionAttributes == null || decisionAttributes.isEmpty()) { - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Attributes Given. "; - return false; - } - return true; - } - - public DecisionResponse getResult() { - return decisionResponse; - } - - public HttpStatus getResponseCode() { - return status; - } - -} - diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDictionaryService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDictionaryService.java deleted file mode 100644 index 04567e2e1..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetDictionaryService.java +++ /dev/null @@ -1,276 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.util.UUID; - -import javax.json.JsonException; -import javax.json.JsonObject; - -import org.openecomp.policy.api.DictionaryParameters; -import org.openecomp.policy.api.DictionaryResponse; -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; -import org.openecomp.policy.std.StdDictionaryResponse; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.http.HttpStatus; - -public class GetDictionaryService { - private static final Logger LOGGER = FlexLogger.getLogger(GetDictionaryService.class.getName()); - - private DictionaryResponse dictionaryResponse = null; - private HttpStatus status = HttpStatus.BAD_REQUEST; - private String message = null; - private DictionaryParameters dictionaryParameters = null; - - public GetDictionaryService(DictionaryParameters dictionaryParameters, - String requestID) { - this.dictionaryParameters = dictionaryParameters; - if(dictionaryParameters.getRequestID()==null){ - UUID requestUUID = null; - if (requestID != null && !requestID.isEmpty()) { - try { - requestUUID = UUID.fromString(requestID); - } catch (IllegalArgumentException e) { - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); - } - }else{ - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); - } - this.dictionaryParameters.setRequestID(requestUUID); - } - try{ - run(); - specialCheck(); - }catch(PolicyException e){ - StdDictionaryResponse dictionaryResponse = new StdDictionaryResponse(); - dictionaryResponse.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - this.dictionaryResponse = dictionaryResponse; - status = HttpStatus.BAD_REQUEST; - } - } - - private void specialCheck() { - if(dictionaryResponse!=null && (dictionaryResponse.getResponseMessage()!=null && dictionaryResponse.getResponseMessage().contains("PE300"))){ - status = HttpStatus.BAD_REQUEST; - } - } - - private void run() throws PolicyException{ - // Check Validation. - if(!getValidation()){ - LOGGER.error(message); - throw new PolicyException(message); - } - // Get Result. - try{ - status = HttpStatus.OK; - dictionaryResponse = processResult(); - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - status = HttpStatus.BAD_REQUEST; - throw new PolicyException(e); - } - } - - private DictionaryResponse processResult() throws PolicyException{ - StdDictionaryResponse response = new StdDictionaryResponse(); - PAPServices papServices = new PAPServices(); - String result = (String) papServices.callPAP(null, new String[] {"operation=get", "apiflag=api", "dictionaryType="+dictionaryParameters.getDictionary()}, dictionaryParameters.getRequestID(), "dictionaryItem"); - - if (result!=null && result.contains("data")) { - String jsonString = formatDictionaryJson(result); - String responseMessage = result.substring(0, 82); - JsonObject json = null; - try{ - json = PolicyApiUtils.stringToJsonObject(jsonString.replace("\\\\\\", "\\")); - String datas = json.getString("data").replaceFirst("\"\\[", "["); - int i = datas.lastIndexOf("]"); - if( i>=0 ) { - datas = new StringBuilder(datas).replace(i, i+2,"]").toString(); - } - json = PolicyApiUtils.stringToJsonObject(datas); - } catch(JsonException| IllegalStateException e){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper Dictionary JSON object : " + dictionaryParameters.getDictionaryJson(); - LOGGER.error(message, e); - response.setResponseMessage(message); - response.setResponseCode(400); - return response; - } - response.setResponseCode(papServices.getResponseCode()); - response.setDictionaryJson(json); - response.setResponseMessage(responseMessage); - } else { - response.setResponseCode(400); - response.setResponseMessage(result); - if(result!=null && result.contains("PE200")){ - status=HttpStatus.INTERNAL_SERVER_ERROR; - }else{ - status=HttpStatus.BAD_REQUEST; - } - } - return response; - } - - private String formatDictionaryJson(String result) { - String jsonString = result.substring(82); - String dictionary = dictionaryParameters.getDictionary(); - - switch (dictionary) { - case "EcompName": - jsonString = jsonString.replace("ecompNameDictionaryDatas", "DictionaryDatas"); - break; - case "Attribute": - jsonString = jsonString.replace("attributeDictionaryDatas", "DictionaryDatas"); - break; - case "Action": - jsonString = jsonString.replace("actionPolicyDictionaryDatas", "DictionaryDatas"); - break; - case "BRMSParamTemplate": - jsonString = jsonString.replace("brmsParamDictionaryDatas", "DictionaryDatas"); - break; - case "VSCLAction": - jsonString = jsonString.replace("vsclActionDictionaryDatas", "DictionaryDatas"); - break; - case "VNFType": - jsonString = jsonString.replace("vnfTypeDictionaryDatas", "DictionaryDatas"); - break; - case "PEPOptions": - jsonString = jsonString.replace("pepOptionsDictionaryDatas", "DictionaryDatas"); - break; - case "Varbind": - jsonString = jsonString.replace("varbindDictionaryDatas", "DictionaryDatas"); - break; - case "Service": - jsonString = jsonString.replace("closedLoopServiceDictionaryDatas", "DictionaryDatas"); - break; - case "Site": - jsonString = jsonString.replace("closedLoopSiteDictionaryDatas", "DictionaryDatas"); - break; - case "Settings": - jsonString = jsonString.replace("settingsDictionaryDatas", "DictionaryDatas"); - break; - case "DescriptiveScope": - jsonString = jsonString.replace("descriptiveScopeDictionaryDatas", "DictionaryDatas"); - break; - case "Enforcer": - jsonString = jsonString.replace("enforcerDictionaryDatas", "DictionaryDatas"); - break; - case "ActionList": - jsonString = jsonString.replace("actionListDictionaryDatas", "DictionaryDatas"); - break; - case "ProtocolList": - jsonString = jsonString.replace("protocolListDictionaryDatas", "DictionaryDatas"); - break; - case "Zone": - jsonString = jsonString.replace("zoneDictionaryDatas", "DictionaryDatas"); - break; - case "SecurityZone": - jsonString = jsonString.replace("securityZoneDictionaryDatas", "DictionaryDatas"); - break; - case "PrefixList": - jsonString = jsonString.replace("prefixListDictionaryDatas", "DictionaryDatas"); - break; - case "AddressGroup": - jsonString = jsonString.replace("addressGroupDictionaryDatas", "DictionaryDatas"); - break; - case "ServiceGroup": - jsonString = jsonString.replace("serviceGroupDictionaryDatas", "DictionaryDatas"); - break; - case "ServiceList": - jsonString = jsonString.replace("serviceListDictionaryDatas", "DictionaryDatas"); - break; - case "TermList": - case "RuleList": - case "FirewallRuleList": - case "Term": - jsonString = jsonString.replace("termListDictionaryDatas", "DictionaryDatas"); - break; - case "MicroServiceLocation": - jsonString = jsonString.replace("microServiceLocationDictionaryDatas", "DictionaryDatas"); - break; - case "MicroServiceConfigName": - jsonString = jsonString.replace("microServiceCongigNameDictionaryDatas", "DictionaryDatas"); - break; - case "DCAEUUID": - jsonString = jsonString.replace("dcaeUUIDDictionaryDatas", "DictionaryDatas"); - break; - case "MicroServiceModels": - jsonString = jsonString.replace("microServiceModelsDictionaryDatas", "DictionaryDatas"); - break; - case "PolicyScopeService": - jsonString = jsonString.replace("psServiceDictionaryDatas", "DictionaryDatas"); - break; - case "PolicyScopeResource": - jsonString = jsonString.replace("psResourceDictionaryDatas", "DictionaryDatas"); - break; - case "PolicyScopeType": - jsonString = jsonString.replace("psTypeDictionaryDatas", "DictionaryDatas"); - break; - case "PolicyScopeClosedLoop": - jsonString = jsonString.replace("psClosedLoopDictionaryDatas", "DictionaryDatas"); - break; - case "GroupPolicyScopeList": - jsonString = jsonString.replace("groupPolicyScopeListDatas", "DictionaryDatas"); - break; - case "RiskType": - jsonString = jsonString.replace("riskTypeDictionaryDatas", "DictionaryDatas"); - break; - case "SafePolicyWarning": - jsonString = jsonString.replace("safePolicyWarningDatas", "DictionaryDatas"); - break; - case "MicroServiceDictionary": - jsonString = jsonString.replace("microServiceDictionaryDatas", "DictionaryDatas"); - break; - default: - return null; - } - return jsonString; - } - - private boolean getValidation() { - if(dictionaryParameters==null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Dictionary Parameters are not given."; - return false; - } - if(dictionaryParameters.getDictionaryType()==null || dictionaryParameters.getDictionaryType().toString().trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Type given."; - return false; - } - if(dictionaryParameters.getDictionary()==null || dictionaryParameters.getDictionary().trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary given."; - return false; - } - return true; - } - - public DictionaryResponse getResult() { - return dictionaryResponse; - } - - public HttpStatus getResponseCode() { - return status; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetMetricsService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetMetricsService.java deleted file mode 100644 index 5a90bfac9..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/GetMetricsService.java +++ /dev/null @@ -1,157 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.util.UUID; - -import javax.json.JsonException; - -import org.json.JSONObject; -import org.openecomp.policy.api.MetricsRequestParameters; -import org.openecomp.policy.api.MetricsResponse; -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.std.StdMetricsResponse; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.http.HttpStatus; - -public class GetMetricsService { - private static final Logger LOGGER = FlexLogger - .getLogger(GetMetricsService.class.getName()); - - private MetricsResponse response = null; - private HttpStatus status = HttpStatus.BAD_REQUEST; - private MetricsRequestParameters metricsParameters = null; - - public GetMetricsService(String requestID) { - UUID requestUUID = null; - if (requestID != null && !requestID.isEmpty()) { - try { - requestUUID = UUID.fromString(requestID); - } catch (IllegalArgumentException e) { - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); - } - } else { - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); - } - metricsParameters = new MetricsRequestParameters(); - this.metricsParameters.setRequestID(requestUUID); - - try { - run(); - specialCheck(); - } catch (PolicyException e) { - StdMetricsResponse metricsResponse = new StdMetricsResponse(); - metricsResponse - .setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE - + e); - this.response = metricsResponse; - status = HttpStatus.BAD_REQUEST; - } - } - - private void specialCheck() { - if (response != null && (response.getResponseMessage() != null - && response.getResponseMessage().contains("PE300"))) { - status = HttpStatus.BAD_REQUEST; - } - } - - private void run() throws PolicyException { - // Get Result. - try { - status = HttpStatus.OK; - response = processResult(); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - status = HttpStatus.BAD_REQUEST; - throw new PolicyException(e); - } - } - - private MetricsResponse processResult() throws PolicyException { - StdMetricsResponse metricsResponse = new StdMetricsResponse(); - PAPServices papServices = new PAPServices(); - String result = (String) papServices.callPAP(null, new String[] { - "operation=get", "apiflag=getMetrics" }, - metricsParameters.getRequestID(), "metrics"); - - JSONObject json = null; - String message = null; - if (result != null) { - if (result.length() > 81 && result.contains("{")) { - try { - String responseMessage = result.substring(0, 82); - String jsonString = result.substring(result.indexOf('{'), - result.length()); - json = new JSONObject(jsonString); - - int papCount = (int) json.get("papCount"); - int pdpCount = (int) json.get("pdpCount"); - - metricsResponse.setResponseCode(papServices - .getResponseCode()); - metricsResponse.setResponseMessage(responseMessage); - metricsResponse.setPapMetrics(papCount); - metricsResponse.setPdpMetrics(pdpCount); - - } catch (JsonException | IllegalStateException e) { - String jsonString = null; - if(json != null){ - jsonString = json.toString(); - } - message = XACMLErrorConstants.ERROR_DATA_ISSUE - + " improper JSON object : " + jsonString; - LOGGER.error(message + e); - metricsResponse.setResponseMessage(message); - metricsResponse.setResponseCode(400); - return metricsResponse; - } - } else { - message = result; - metricsResponse.setResponseCode(400); - metricsResponse.setResponseMessage(message); - return metricsResponse; - } - - } else { - message = XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "There was an issue with connecting to the PAP, " - + "review the logs for further debugging."; - metricsResponse.setResponseCode(500); - metricsResponse.setResponseMessage(message); - return metricsResponse; - } - - return metricsResponse; - } - - public MetricsResponse getResult() { - return response; - } - - public HttpStatus getResponseCode() { - return status; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ListConfigService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ListConfigService.java deleted file mode 100644 index 9aca4c049..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/ListConfigService.java +++ /dev/null @@ -1,64 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.util.ArrayList; -import java.util.Collection; - -import org.openecomp.policy.api.ConfigRequestParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.models.PolicyConfig; -import org.springframework.http.HttpStatus; - -public class ListConfigService { - private static Logger LOGGER = FlexLogger.getLogger(ListConfigService.class.getName()); - - private Collection results = null; - private HttpStatus status = HttpStatus.BAD_REQUEST; - - public ListConfigService(ConfigRequestParameters configRequestParameters, - String requestID) { - GetConfigService getConfigService = new GetConfigService(configRequestParameters,requestID); - Collection policyConfigs = getConfigService.getResult(); - LOGGER.info("Transferring Config Results to List. "); - if(policyConfigs!=null){ - results = new ArrayList(); - status = HttpStatus.OK; - for(PolicyConfig policyConfig : policyConfigs){ - if(policyConfig.getPolicyConfigMessage()!=null && policyConfig.getPolicyConfigMessage().contains("PE300")){ - results.add(policyConfig.getPolicyConfigMessage()); - status = HttpStatus.BAD_REQUEST; - } else { - results.add("Policy Name: " + policyConfig.getPolicyName()); - } - } - } - } - - public Collection getResult() { - return results; - } - - public HttpStatus getResponseCode() { - return status; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/MicroServicesPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/MicroServicesPolicyService.java deleted file mode 100644 index 3188292d7..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/MicroServicesPolicyService.java +++ /dev/null @@ -1,135 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import javax.json.JsonException; -import javax.json.JsonObject; - -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.utils.PolicyApiUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; - -/** - * MicroServices Policy implementation. - * - * @version 0.1 - */ -public class MicroServicesPolicyService{ - private static final Logger LOGGER = FlexLogger.getLogger(MicroServicesPolicyService.class.getName()); - - private PAPServices papServices = null; - private PolicyParameters policyParameters = null; - private String message = null; - private String policyName = null; - private String policyScope = null; - private String date = null; - private String ecompName = null; - private JsonObject microServiceAttributes = null; - - public MicroServicesPolicyService(String policyName, String policyScope, PolicyParameters policyParameters, String date) { - this.policyParameters = policyParameters; - this.policyName = policyName; - this.policyScope = policyScope; - this.date = date; - papServices = new PAPServices(); - } - - public Boolean getValidation() { - if(policyParameters.getConfigBody()==null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Micro Service or Attributes Config Body Present"; - return false; - } - try{ - microServiceAttributes = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); - } catch(JsonException| IllegalStateException e){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); - LOGGER.error("Error while parsing JSON body for MicroService Policy creation. ", e); - return false; - } - ecompName = policyParameters.getEcompName(); - if (ecompName==null||ecompName.trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given."; - return false; - } - boolean levelCheck = false; - levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); - if (!levelCheck){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; - return false; - } - return true; - } - - public String getMessage() { - return message; - } - - public String getResult(boolean updateFlag) throws PolicyException{ - String response = null; - String operation = null; - if (updateFlag){ - operation = "update"; - } else { - operation = "create"; - } - // get values and attributes from the JsonObject - String uuid = null; - String msLocation = null; - String configName = null; - String microService = null; - String policyDescription=null; - String priority=null; - String version=null; - if (microServiceAttributes.get("service")!=null){ - microService = microServiceAttributes.get("service").toString().replace("\"", ""); - } - if (microServiceAttributes.get("uuid")!=null){ - uuid = microServiceAttributes.get("uuid").toString().replace("\"", ""); - } - if (microServiceAttributes.get("location")!=null){ - msLocation = microServiceAttributes.get("location").toString().replace("\"", ""); - } - if (microServiceAttributes.get("configName")!=null){ - configName = microServiceAttributes.get("configName").toString().replace("\"", ""); - } - if(microServiceAttributes.containsKey("description")){ - policyDescription = microServiceAttributes.get("description").toString().replace("\"", ""); - } - if(microServiceAttributes.containsKey("priority")){ - priority = microServiceAttributes.get("priority").toString().replace("\"", ""); - } - if(microServiceAttributes.containsKey("version")){ - version = microServiceAttributes.get("version").toString().replace("\"", ""); - } - // Create Policy. - StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Micro Service", policyName, policyDescription, ecompName, - configName, microService, uuid, msLocation, microServiceAttributes.toString(), priority, - version, updateFlag, policyScope, 0, policyParameters.getRiskLevel(), - policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date); - // Send JSON Object to PAP. - response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigMS"); - LOGGER.info("Policy MS created Response: " + response); - return response; - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/NotificationService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/NotificationService.java deleted file mode 100644 index 4b453fa87..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/NotificationService.java +++ /dev/null @@ -1,314 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.io.File; -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import org.openecomp.policy.api.PolicyException; -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.utils.BusPublisher; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.http.HttpStatus; - -import com.att.research.xacml.util.XACMLProperties; - -public class NotificationService { - public static final String BACKUPFILE = "topicBackup.txt"; - private static Logger logger = FlexLogger.getLogger(GetDictionaryService.class.getName()); - private static ConcurrentHashMap topicQueue = new ConcurrentHashMap<>(); - private static int interval = 15000; - private static Thread backUpthread = null; - private static Object resourceLock = new Object(); - private static List dmaapList = null; - private static String dmaapServers = null; - private static String aafLogin = null; - private static String aafPassword = null; - - private String notificationResponse = null; - private HttpStatus status = HttpStatus.BAD_REQUEST; - - /** - * NotificationService Constructor. - * - * @param notificationTopic Topic Name in String format. - * @param requestID Request ID in String format. - * @param serviceType Needs to be NotificationServiceType based enumeration value. - */ - public NotificationService(String notificationTopic, String requestID, NotificationServiceType serviceType) { - init(); - if(dmaapServers==null || aafLogin==null || aafPassword==null){ - notificationResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file"; - return; - } - UUID requestUUID = null; - if (requestID != null && !requestID.isEmpty()) { - try { - requestUUID = UUID.fromString(requestID); - } catch (IllegalArgumentException e) { - requestUUID = UUID.randomUUID(); - logger.info("Generated Random UUID: " + requestUUID.toString(), e); - } - }else{ - requestUUID = UUID.randomUUID(); - logger.info("Generated Random UUID: " + requestUUID.toString()); - } - try{ - run(notificationTopic, serviceType); - }catch(PolicyException e){ - notificationResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e; - status = HttpStatus.BAD_REQUEST; - } - } - - private static void init() { - if(dmaapServers==null || aafLogin==null || aafPassword==null){ - dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); - aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN"); - aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD"); - interval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY, Integer.toString(interval))); - if(dmaapServers==null || aafLogin==null || aafPassword==null){ - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); - return; - } - // Cleanup Values. - dmaapServers= dmaapServers.trim(); - aafLogin = aafLogin.trim(); - aafPassword = aafPassword.trim(); - // Get servers to List. - if(dmaapServers.contains(",")) { - dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*"))); - } else { - dmaapList = new ArrayList<>(); - dmaapList.add(dmaapServers); - } - callThread(); - } - } - - private void run(String notificationTopic, NotificationServiceType serviceType) throws PolicyException{ - // Check Validation - if(notificationTopic==null){ - String message = "Notification Topic is null"; - logger.error(message); - throw new PolicyException(message); - } - notificationTopic = notificationTopic.trim(); - if(notificationTopic.isEmpty()){ - String message = "Notification Topic is not valid. "; - logger.error(message); - throw new PolicyException(message); - } - // if already exists give error.Saying already registered. - // Get Result. - try{ - status = HttpStatus.OK; - switch (serviceType) { - case ADD: - addTopic(notificationTopic); - notificationResponse = "Success!! Please give permissions to " + aafLogin + " that PDP will use to publish on given topic :" + notificationTopic + - "\n Start calling /sendHeartbeat API at an interval less than " + Integer.toString(interval) + "ms"; - break; - case REMOVE: - removeTopic(notificationTopic); - notificationResponse = "Notification Topic :" + notificationTopic + " has been removed and PDP will not publish notifications to this Topic."; - break; - case HB: - heartBeat(notificationTopic); - notificationResponse = "Success!! HeartBeat registered."; - break; - } - }catch (Exception e){ - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - status = HttpStatus.BAD_REQUEST; - throw new PolicyException(e); - } - } - - // Used to register Heart beat. - private void heartBeat(String notificationTopic) throws PolicyException{ - if(!topicQueue.isEmpty()&& topicQueue.containsKey(notificationTopic)){ - topicQueue.put(notificationTopic, new Date()); - }else{ - logger.info("Failed HeartBeat, Topic " + notificationTopic + "is not registered."); - throw new PolicyException("Failed HeartBeat, Topic " + notificationTopic + "is not registered."); - } - } - - // Used to remove Topic. - private static void removeTopic(String notificationTopic) throws PolicyException{ - if(topicQueue.containsKey(notificationTopic)){ - topicQueue.remove(notificationTopic); - removeTopicFromBackup(notificationTopic); - }else{ - logger.info("Failed Removal, Topic " + notificationTopic + " is not registered."); - throw new PolicyException("Failed Removal, Topic " + notificationTopic + " is not registered."); - } - } - - private static void removeTopicFromBackup(String notificationTopic) { - synchronized (resourceLock) { - try (Stream lines = Files.lines(Paths.get(BACKUPFILE))) { - List replaced = lines.map(line-> (line.split("=")[0].equals(notificationTopic)?"":line)).collect(Collectors.toList()); - try (PrintWriter pw = new PrintWriter( BACKUPFILE, "UTF-8")) { - replaced.forEach(line-> { - if(line.trim().isEmpty()){ - return; - } - pw.println(line); - }); - } - lines.close(); - } catch (IOException e) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + " Could not remove/recreate the backup. ", e); - } - } - } - - // Used to add Topic. - private void addTopic(String notificationTopic) throws PolicyException{ - // validate if topic exists. - if(!topicQueue.isEmpty()&& topicQueue.containsKey(notificationTopic)){ - topicQueue.put(notificationTopic, new Date()); - logger.info("Topic " + notificationTopic + " is already registered."); - throw new PolicyException("Topic " + notificationTopic + " is already registered."); - } - topicQueue.put(notificationTopic, new Date()); - addTopictoBackUp(notificationTopic); - } - - private void addTopictoBackUp(String notificationTopic) { - synchronized (resourceLock) { - try { - Files.write(Paths.get(BACKUPFILE),( notificationTopic+"="+new Date().toString()+"\n").getBytes() , StandardOpenOption.APPEND); - } catch (IOException e) { - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + " Could not add to the backup. ", e); - } - } - } - - // Maintains BackUp and Queue Topic. - private static void callThread() { - // Create the backup file if it not exists. - backup(); - if(backUpthread==null){ - Runnable task = () -> { - logger.info("BackUpThread not set. Starting now !"); - threadTask(); - }; - backUpthread = new Thread(task); - backUpthread.start(); - } - } - - private static void backup(){ - synchronized (resourceLock) { - try{ - File backUpFile = new File(BACKUPFILE); - if(!backUpFile.exists() && backUpFile.createNewFile()){ - logger.info(" BackUp File for topic's has been created !"); - }else{ - // File Already exists. Process file and load the Memory. - Stream stream = Files.lines(Paths.get(BACKUPFILE)); - Map data = stream.map(line -> line.split(",")).collect(Collectors.toMap(e->e[0],e-> new Date())); - stream.close(); - data.forEach((key, value)->logger.debug("Topic retrieved from backUp : " + key + " with Time : " + value)); - topicQueue.putAll(data); - } - }catch(IOException e){ - logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + " Could not process the backup. ", e); - } - } - } - - private static void threadTask() { - while(true){ - try { - TimeUnit.MILLISECONDS.sleep(interval); - for(Map.Entry map : topicQueue.entrySet()){ - Date currentTime = new Date(); - long timeDiff = 0; - timeDiff = currentTime.getTime()-map.getValue().getTime(); - if(timeDiff < (interval+1500)){ - removeTopic(map.getKey()); - } - } - } catch (InterruptedException | PolicyException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error during thread execution ", e); - } - } - } - - public String getResult() { - return notificationResponse; - } - - public HttpStatus getResponseCode() { - return status; - } - - /** - * Entry point for sending Notifications from Notification Server. - * @param notification String JSON format of notification message which needs to be sent. - */ - public static void sendNotification(String notification) { - init(); - for (String topic: topicQueue.keySet()){ - sendDmaapMessage(topic, notification); - } - } - - private static void sendDmaapMessage(String topic, String notification) { - BusPublisher publisher = new BusPublisher.DmaapPublisherWrapper(dmaapList, - topic, - aafLogin, - aafPassword); - // Sending notification through DMaaP Message Router - publisher.send( "MyPartitionKey", notification); - logger.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + topic); - publisher.close(); - } - - /** - * Notification service Type Enumeration - */ - public enum NotificationServiceType{ - ADD, - REMOVE, - HB - } - -} \ No newline at end of file diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java deleted file mode 100644 index aea058d37..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PAPServices.java +++ /dev/null @@ -1,656 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Base64; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.apache.commons.io.IOUtils; -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.config.PDPApiAuth; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; - -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class PAPServices { - private static final String SUCCESS = "success"; - private static Logger LOGGER = FlexLogger.getLogger(PAPServices.class - .getName()); - - private int responseCode = 0; - private static String environment = "DEVL"; - private static Boolean junit = false; - private static List paps = null; - private static final Object papResourceLock = new Object(); - private String operation = null; - private String requestMethod = null; - private String encoding = null; - - public PAPServices() { - environment = PDPApiAuth.getEnvironment(); - if(paps == null){ - synchronized (papResourceLock) { - String urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS); - if(urlList == null){ - urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); - } - paps = Arrays.asList(urlList.split(",")); - } - } - } - - private String getPAPEncoding(){ - if(encoding == null){ - String userID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); - String pass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); - Base64.Encoder encoder = Base64.getEncoder(); - encoding = encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8)); - } - return encoding; - } - - private void rotatePAPList(){ - synchronized (papResourceLock) { - Collections.rotate(paps, -1); - } - } - - private String getPAP(){ - String result; - synchronized (papResourceLock) { - result = paps.get(0); - } - return result; - } - - public int getResponseCode() { - return responseCode; - } - - public Object callPAP(Object content, String[] parameters, UUID requestID, - String clientScope) throws PolicyException { - String response = null; - HttpURLConnection connection = null; - responseCode = 0; - // Checking for the available PAPs is done during the first Request and - // the List is going to have the connected PAP as first element. - // This makes it Real-Time to change the list depending on their - // availability. - if (paps == null || paps.isEmpty()) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty."; - LOGGER.error(message); - throw new PolicyException(message); - } - int papsCount = 0; - boolean connected = false; - while (papsCount < paps.size()) { - try { - String fullURL = getPAP(); - fullURL = checkParameter(parameters, fullURL); - URL url = new URL(fullURL); - LOGGER.debug("--- Sending Request to PAP : "+ url.toString() + " ---"); - // Open the connection - connection = (HttpURLConnection) url.openConnection(); - // Setting Content-Type - connection.setRequestProperty("Content-Type","application/json"); - // Adding Authorization - connection.setRequestProperty("Authorization", "Basic "+ getPAPEncoding()); - connection.setRequestProperty("Environment", environment); - connection.setRequestProperty("ClientScope", clientScope); - // set the method and headers - connection.setRequestMethod(requestMethod); - connection.setUseCaches(false); - connection.setInstanceFollowRedirects(false); - connection.setDoOutput(true); - connection.setDoInput(true); - // Adding RequestID - if (requestID == null) { - requestID = UUID.randomUUID(); - LOGGER.info("No request ID provided, sending generated ID: " - + requestID.toString()); - } else { - LOGGER.info("Using provided request ID: " - + requestID.toString()); - } - connection.setRequestProperty("X-ECOMP-RequestID", - requestID.toString()); - if (content != null && (content instanceof InputStream)) { - // send current configuration - try (OutputStream os = connection.getOutputStream()) { - int count = IOUtils.copy((InputStream) content, os); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("copied to output, bytes=" + count); - } - } - } else if(content != null){ - // the content is an object to be encoded in JSON - ObjectMapper mapper = new ObjectMapper(); - if (!junit) { - mapper.writeValue(connection.getOutputStream(), - content); - } - } - // DO the connect - connection.connect(); - responseCode = connection.getResponseCode(); - // If Connected to PAP then break from the loop and continue - // with the Request - if (connection.getResponseCode() > 0 || junit) { - connected = true; - break; - } else { - LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : " + connection.getResponseCode()); - rotatePAPList(); - } - } catch (Exception e) { - // This means that the PAP is not working - if (junit) { - connected = true; - break; - } - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "PAP connection Error : " + e); - rotatePAPList(); - } - papsCount++; - } - if (connected) { - // Read the Response - LOGGER.debug("connected to the PAP : " + getPAP()); - LOGGER.debug("--- Response: ---"); - if(connection != null){ - Map> headers = connection.getHeaderFields(); - for (String key : headers.keySet()) { - LOGGER.debug("Header :" + key + " Value: " + headers.get(key)); - } - - try { - response = checkResponse(connection, requestID); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + e; - throw new PolicyException( - XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "Decoding the result ", e); - } - if (junit) { - response = SUCCESS; - } - }else{ - response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "connection is null"; - } - return response; - } else { - response = XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "Unable to get valid response from PAP(s) " + paps; - return response; - } - } - - public String getActiveVersion(String policyScope, String filePrefix, String policyName, String clientScope, UUID requestID) { - String version = null; - HttpURLConnection connection = null; - String [] parameters = {"apiflag=version","policyScope="+policyScope, "filePrefix="+filePrefix, "policyName="+policyName}; - if (paps == null || paps.isEmpty()) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty."); - try { - throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty."); - } catch (Exception e) { - LOGGER.error(e.getMessage() + e); - } - }else { - int papsCount = 0; - boolean connected = false; - while (papsCount < paps.size()) { - try { - String fullURL = getPAP(); - if (parameters != null && parameters.length > 0) { - String queryString = ""; - for (String p : parameters) { - queryString += "&" + p; - } - fullURL += "?" + queryString.substring(1); - } - - URL url = new URL (fullURL); - - //Open the connection - connection = (HttpURLConnection)url.openConnection(); - - // Setting Content-Type - connection.setRequestProperty("Content-Type", - "application/json"); - - // Adding Authorization - connection.setRequestProperty("Authorization", "Basic " - + getPAPEncoding()); - - connection.setRequestProperty("Environment", environment); - connection.setRequestProperty("ClientScope", clientScope); - - - //set the method and headers - connection.setRequestMethod("GET"); - connection.setUseCaches(false); - connection.setInstanceFollowRedirects(false); - connection.setDoOutput(true); - connection.setDoInput(true); - connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString()); - - //DO the connect - connection.connect(); - - // If Connected to PAP then break from the loop and continue with the Request - if (connection.getResponseCode() > 0) { - connected = true; - break; - - } else { - LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error"); - } - } catch (Exception e) { - // This means that the PAP is not working - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e); - rotatePAPList(); - } - papsCount++; - } - - if (connected) { - //Read the Response - LOGGER.debug("connected to the PAP : " + getPAP()); - LOGGER.debug("--- Response: ---"); - Map> headers = connection.getHeaderFields(); - for (String key : headers.keySet()) { - LOGGER.debug("Header :" + key + " Value: " + headers.get(key)); - } - try { - if (connection.getResponseCode() == 200) { - // Check for successful creation of policy - version = connection.getHeaderField("version"); - LOGGER.debug("ActiveVersion from the Header: " + version); - } else if (connection.getResponseCode() == 403) { - LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is " - + connection.getResponseCode() + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. "); - version = "pe100"; - } else if (connection.getResponseCode() == 404) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is " - + connection.getResponseCode() + ". This indicates a problem with getting the version from the PAP"); - version = "pe300"; - } else { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: Error occured while getting the version from the PAP. The request may be incorrect."); - } - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - try { - throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e); - } catch (Exception e1) { - LOGGER.error(e1.getMessage() + e1); - } - } - - } else { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps); - try { - throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP "); - } catch (Exception e) { - LOGGER.error(e.getMessage() + e); - } - } - } - return version; - } - - private String checkResponse(HttpURLConnection connection, UUID requestID) throws IOException { - String response = null; - if (responseCode == 200 || junit) { - // Check for successful creation of policy - String isSuccess = null; - if (!junit) { // is this a junit test? - isSuccess = connection.getHeaderField("successMapKey"); - operation = connection.getHeaderField("operation"); - } else { - isSuccess = SUCCESS; - } - if (SUCCESS.equals(isSuccess)) { - if ("update".equals(operation)) { - response = "Transaction ID: " + requestID + " --Policy with the name "+ connection.getHeaderField("policyName") - + " was successfully updated. "; - if (connection.getHeaderField("safetyChecker")!=null) { - response = response - + "\n\nPolicy Safety Checker Warning: This closedLoopControlName " - + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") - + " that already exists." + " See detailed information on ClosedLoop Pairs below: " - +"\n\n"+connection.getHeaderField("safetyChecker"); - } - } else if ("create".equals(operation)) { - response = "Transaction ID: " + requestID + " --Policy with the name "+ connection.getHeaderField("policyName") - + " was successfully created."; - if (connection.getHeaderField("safetyChecker")!=null) { - response = response - + "\n\nPolicy Safety Checker Warning: This closedLoopControlName " - + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") - + " that already exists. " + "See detailed information on ClosedLoop Pairs below: " - +"\n\n"+connection.getHeaderField("safetyChecker"); - } - } else if ("delete".equals(operation)) { - response = "Transaction ID: " + requestID + " --The policy was successfully deleted."; - } else if ("import".equals(operation)) { - response = "Transaction ID: " + requestID + " --The policy engine import for "+ connection.getHeaderField("service") - + " was successfull."; - } else if ("createDictionary".equals(operation)) { - response = "Transaction ID: " + requestID + " --Dictionary Item was added successfully!"; - } else if ("updateDictionary".equals(operation)) { - response = "Transaction ID: " + requestID + " --Dictionary Item was updated successfully!"; - } else if ("getDictionary".equals(operation)) { - String json = null; - try { - - //get the json string from the response - InputStream is = connection.getInputStream(); - - // 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(is); - scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; - scanner.close(); - - } catch (IOException e1) { - LOGGER.error(e1.getMessage() + e1); - } - response = "Transaction ID: " + requestID + " --Dictionary Items Retrieved " + json; - } else if ("getMetrics".equals(operation)) { - response = "Transaction ID: " + requestID + " --Policy Metrics Retrieved " + connection.getHeaderField("metrics"); - } - LOGGER.info(response); - } else { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Operation unsuccessful, unable to complete the request!"; - LOGGER.error(message); - response = message; - } - } else if (connection.getResponseCode() == 202) { - if ("delete".equalsIgnoreCase(connection.getHeaderField("operation")) && - "true".equals(connection.getHeaderField("lockdown"))) { - response = "Transaction ID: " - + requestID - + " --Policies are locked down, please try again later."; - LOGGER.warn(response); - } - } else if (connection.getResponseCode() == 204) { - if ("push".equals(connection.getHeaderField("operation"))) { - response = "Transaction ID: " - + requestID - + " --Policy '" - + connection.getHeaderField("policyId") - + "' was successfully pushed to the PDP group '" - + connection.getHeaderField("groupId") + "'."; - LOGGER.info(response); - } - } else if (connection.getResponseCode() == 400 && connection.getHeaderField("error") != null) { - response = connection.getHeaderField("error"); - LOGGER.error(response); - } else if (connection.getResponseCode() == 403) { - response = XACMLErrorConstants.ERROR_PERMISSIONS - + "response code of the URL is " - + connection.getResponseCode() - + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. "; - LOGGER.error(response); - } else if (connection.getResponseCode() == 404 && connection.getHeaderField("error") != null) { - if ("unknownGroupId".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + connection.getHeaderField("message") - + " Please check the pdpGroup you are requesting to move the policy to."; - LOGGER.error(response); - } - } else if (connection.getResponseCode() == 409 && connection.getHeaderField("error") != null) { - if ("modelExistsDB".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Import Value Exist Error: The import value " - + connection.getHeaderField("service") - + " already exist on the PAP. " - + "Please create a new import value."; - } else if ("policyExists".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Policy Exist Error: The Policy " - + connection.getHeaderField("policyName") - + " already exist on the PAP. " - + "Please create a new policy or use the update API to modify the existing one."; - } else if ("dictionaryItemExists".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Dictionary Item Exist Error: The Dictionary Item already exist in the database. " - + "Please create a new Dictionary Item or use the update API to modify the existing one."; - } else if ("duplicateGroup".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Group Policy Scope List Exist Error: The Group Policy Scope List for this Dictionary Item already exist in the database. " - + "Duplicate Group Policy Scope Lists for multiple groupNames is not allowed. " - + "Please review the request and verify that the groupPolicyScopeListData1 is unique compared to existing groups."; - } else if("PolicyInPDP".equals(connection.getHeaderField("error"))){ - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Policy Exist Error: The Policy trying to be deleted is active in PDP. " - + "Active PDP Polcies are not allowed to be deleted from PAP. " - + "Please First remove the policy from PDP in order to successfully delete the Policy from PAP."; - } - LOGGER.error(response); - } else if (connection.getResponseCode() == 500 && connection.getHeaderField("error") != null) { - if ("jpautils".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "Could not create JPAUtils instance on the PAP"; - } else if ("deleteDB".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "Failed to delete Policy from database."; - } else if ("deleteFile".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Cannot delete the policy file"; - } else if ("groupUpdate".equals(connection.getHeaderField("error"))) { - response = connection.getHeaderField("message"); - } else if ("unknown".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_UNKNOWN - + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."; - } else if ("deleteConfig".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Cannot delete the configuration or action body file in specified location."; - } else if ("missing".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Failed to create value in database because service does match a value in file"; - } else if ("importDB".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Database errors during policy engine import"; - } else if ("policyCopyError".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_PROCESS_FLOW - + connection.getHeaderField("message"); - } else if ("addGroupError".equals(connection.getHeaderField("error"))) { - response = connection.getHeaderField("message"); - } else if ("validation".equals(connection.getHeaderField("error"))){ - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Validation errors during policy engine " + connection.getHeaderField("operation") + - " for " + connection.getHeaderField("service"); - } else if ("error".equals(connection.getHeaderField("error"))) { - response = XACMLErrorConstants.ERROR_UNKNOWN - + "Could not create or update the policy for and unknown reason"; - }else{ - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + "BAD REQUEST: Error occured while attempting perform this operation.. the request may be incorrect. " + connection.getHeaderField("error"); - } - LOGGER.error(response); - } else { - response = XACMLErrorConstants.ERROR_DATA_ISSUE - + "BAD REQUEST: Error occured while attempting perform this operation.. the request may be incorrect."; - LOGGER.error(response); - } - return response; - } - - private String checkParameter(String[] parameters, String fullURL) { - if (parameters != null && parameters.length > 0) { - String queryString = ""; - for (String p : parameters) { - queryString += "&" + p; - if (p.equalsIgnoreCase("operation=post")) { - requestMethod = "POST"; - } else if (p.equalsIgnoreCase("operation=delete")) { - requestMethod = "DELETE"; - operation = "delete"; - } else if (p.equalsIgnoreCase("operation=get")) { - requestMethod = "GET"; - operation = "get"; - } else if (p.equalsIgnoreCase("operation=put")||p.equalsIgnoreCase("operation=create") - ||p.equalsIgnoreCase("operation=update")||p.equalsIgnoreCase("operation=createDictionary")){ - requestMethod = "PUT"; - if (p.equalsIgnoreCase("operation=create")) { - operation = "create"; - } else if (p.equalsIgnoreCase("operation=update")) { - operation = "update"; - } else if (p.equalsIgnoreCase("operation=createDictionary")){ - operation = "createDictionary"; - } - }else if (p.equalsIgnoreCase("importService=MICROSERVICE")||p.equalsIgnoreCase("importService=BRMSPARAM")){ - requestMethod = "PUT"; - } - } - fullURL += "?" + queryString.substring(1); - } - return fullURL; - } - - public StdPDPPolicy pushPolicy(String policyScope, String filePrefix, - String policyName, String clientScope, String pdpGroup, - UUID requestID) throws PolicyException { - String json = "{ " - + "\"apiflag\": \"api\"," - + "\"policyScope\": \""+policyScope+"\"," - + "\"filePrefix\": \""+filePrefix+"\"," - + "\"policyName\": \""+policyName+"\"," - + "\"clientScope\": \""+clientScope+"\"," - + "\"pdpGroup\": \""+pdpGroup+"\"}"; - //String response = null; - HttpURLConnection connection = null; - responseCode = 0; - if (paps == null || paps.isEmpty()) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty."; - LOGGER.error(message); - throw new PolicyException(message); - } - int papsCount = 0; - boolean connected = false; - while (papsCount < paps.size()) { - try { - String fullURL = getPAP(); - fullURL = (fullURL.endsWith("/"))? fullURL+"ecomp/pushPolicy" : fullURL+"/ecomp/pushPolicy"; - URL url = new URL(fullURL); - LOGGER.debug("--- Sending Request to PAP : "+ url.toString() + " ---"); - // Open the connection - connection = (HttpURLConnection) url.openConnection(); - // Setting Content-Type - connection.setRequestProperty("Content-Type","application/json"); - // Adding Authorization - connection.setRequestProperty("Authorization", "Basic "+ getPAPEncoding()); - connection.setRequestProperty("Environment", environment); - connection.setRequestProperty("ClientScope", clientScope); - // set the method and headers - connection.setRequestMethod("POST"); - connection.setUseCaches(false); - connection.setInstanceFollowRedirects(false); - connection.setDoOutput(true); - // Adding RequestID - if (requestID == null) { - requestID = UUID.randomUUID(); - LOGGER.info("No request ID provided, sending generated ID: " - + requestID.toString()); - } else { - LOGGER.info("Using provided request ID: " - + requestID.toString()); - } - connection.setRequestProperty("X-ECOMP-RequestID", - requestID.toString()); - // DO the connect - try (OutputStream os = connection.getOutputStream()) { - int count = IOUtils.copy(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), os); - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("copied to output, bytes=" + count); - } - } - connection.connect(); - responseCode = connection.getResponseCode(); - // If Connected to PAP then break from the loop and continue - // with the Request - if (connection.getResponseCode() > 0 || junit) { - connected = true; - break; - } else { - LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : " + connection.getResponseCode()); - rotatePAPList(); - } - } catch (Exception e) { - // This means that the PAP is not working - if (junit) { - connected = true; - break; - } - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "PAP connection Error : " + e); - rotatePAPList(); - } - papsCount++; - } - if (connected) { - // Read the Response - LOGGER.debug("connected to the PAP : " + getPAP()); - LOGGER.debug("--- Response: ---"); - if(connection != null){ - Map> headers = connection.getHeaderFields(); - for (String key : headers.keySet()) { - LOGGER.debug("Header :" + key + " Value: " + headers.get(key)); - } - try { - if(responseCode==202){ - StdPDPPolicy policy = (StdPDPPolicy) new ObjectInputStream(connection.getInputStream()).readObject(); - return policy; - } - } catch (IOException | ClassNotFoundException e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); - throw new PolicyException( - XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "Decoding the result ", e); - } - } - return null; - } else { - return null; - } - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PDPServices.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PDPServices.java deleted file mode 100644 index fb7b8e270..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PDPServices.java +++ /dev/null @@ -1,439 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.net.MalformedURLException; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Properties; -import java.util.UUID; - -import javax.json.Json; -import javax.json.JsonReader; -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.apache.commons.io.IOUtils; -import org.openecomp.policy.api.PolicyConfigStatus; -import org.openecomp.policy.api.PolicyDecision; -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.api.PolicyResponseStatus; -import org.openecomp.policy.api.PolicyType; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.XACMLPdpServlet; -import org.openecomp.policy.pdp.rest.api.models.PDPResponse; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.std.Matches; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.w3c.dom.Document; - -import com.att.research.xacml.api.Advice; -import com.att.research.xacml.api.AttributeAssignment; -import com.att.research.xacml.api.Decision; -import com.att.research.xacml.api.Obligation; -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.Response; -import com.att.research.xacml.api.Result; -import com.att.research.xacml.api.pdp.PDPEngine; -import com.att.research.xacml.std.json.JSONRequest; -import com.att.research.xacml.std.json.JSONResponse; -import com.att.research.xacml.util.XACMLProperties; - -public class PDPServices { - private static final Logger LOGGER = FlexLogger.getLogger(PDPServices.class.getName()); - // Change the default Priority value here. - private static final int DEFAULT_PRIORITY = 9999; - private boolean unique = false; - private Boolean decide = false; - private Request rainydayRequest = null; - - public Collection generateRequest(String jsonString, UUID requestID, boolean unique, boolean decide) throws PolicyException{ - this.unique = unique; - this.decide = decide; - Collection results = null; - Response response = null; - // Create Request. We need XACML API here. - try { - Request request = JSONRequest.load(jsonString); - // Assign a rainy day treatment request to parse the decided treatment - if (jsonString.contains("BB_ID")) { - rainydayRequest = request; - } - // Call the PDP - LOGGER.info("--- Generating Request: ---\n" + JSONRequest.toString(request)); - response = callPDP(request, requestID); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e); - PDPResponse pdpResponse = new PDPResponse(); - results = new HashSet<>(); - pdpResponse.setPolicyConfigMessage("Unable to Call PDP. Error with the URL"); - pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); - pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED); - results.add(pdpResponse); - throw new PolicyException(e); - } - if (response != null) { - results = checkResponse(response); - } else { - LOGGER.info("No Response Received from PDP"); - PDPResponse pdpResponse = new PDPResponse(); - results = new HashSet<>(); - pdpResponse.setPolicyConfigMessage("No Response Received"); - pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); - pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED); - results.add(pdpResponse); - } - return results; - } - - private Collection checkResponse(Response response) throws PolicyException{ - String pdpConfigLocation = null; - Collection combinedResult = new HashSet<>(); - int priority = DEFAULT_PRIORITY; - Map uniqueResult = new HashMap<>(); - for (Result result : response.getResults()) { - if (!result.getDecision().equals(Decision.PERMIT)) { - LOGGER.info("Decision not a Permit. " + result.getDecision().toString()); - PDPResponse pdpResponse = new PDPResponse(); - if (decide) { - String indeterminatePropValue = XACMLProperties.getProperty("decision.inStringdeterminate.response"); - if(result.getDecision().equals(Decision.INDETERMINATE)&& indeterminatePropValue != null){ - if("PERMIT".equalsIgnoreCase(indeterminatePropValue)){ - pdpResponse.setDecision(PolicyDecision.PERMIT); - }else{ - pdpResponse.setDecision(PolicyDecision.DENY); - } - }else{ - pdpResponse.setDecision(PolicyDecision.DENY); - } - for(Advice advice: result.getAssociatedAdvice()){ - for(AttributeAssignment attribute: advice.getAttributeAssignments()){ - pdpResponse.setDetails(attribute.getAttributeValue().getValue().toString()); - break; - } - } - combinedResult.add(pdpResponse); - return combinedResult; - } - pdpResponse.setStatus(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Params passed: Decision not a Permit.",PolicyResponseStatus.NO_ACTION_REQUIRED,PolicyConfigStatus.CONFIG_NOT_FOUND); - combinedResult.add(pdpResponse); - return combinedResult; - } else { - if (decide) { - // check for Decision for decision based calls. - PDPResponse pdpResponse = new PDPResponse(); - pdpResponse.setDecision(PolicyDecision.PERMIT); - - //if this is a Rainy Day treatment decision we need to get the selected treatment - if(rainydayRequest!=null){ - pdpResponse.setDetails(getRainyDayTreatment(result)); - } else { - pdpResponse.setDetails("Decision Permit. OK!"); - } - combinedResult.add(pdpResponse); - return combinedResult; - } - if (!result.getAssociatedAdvice().isEmpty()) { - // Configurations should be in advice. - // Also PDP took actions could be here. - for (Advice advice : result.getAssociatedAdvice()) { - int config = 0, uri = 0; - String configURL = null; - String policyName = null; - String policyVersion = null; - Matches match = new Matches(); - Map matchingConditions = new HashMap<>(); - Map configAttributes = new HashMap<>(); - Map responseAttributes = new HashMap<>(); - Map actionTaken = new HashMap<>(); - PDPResponse pdpResponse = new PDPResponse(); - Map adviseAttributes = new HashMap<>(); - for (AttributeAssignment attribute : advice.getAttributeAssignments()) { - adviseAttributes.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString()); - if ("CONFIGURATION".equalsIgnoreCase(attribute.getAttributeValue().getValue().toString())) { - config++; - } else if (attribute.getDataTypeId().stringValue().endsWith("anyURI")) { - uri++; - if (uri == 1) { - configURL = attribute.getAttributeValue().getValue().toString(); - pdpConfigLocation = configURL.replace("$URL", XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)); - } else { - if (!("PDP".equalsIgnoreCase(attribute.getIssuer()))) { - throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error having multiple URI in the Policy"); - } - } - } else if ("PolicyName".equalsIgnoreCase(attribute.getAttributeId().stringValue())) { - policyName = attribute.getAttributeValue().getValue().toString(); - } else if ("VersionNumber".equalsIgnoreCase(attribute.getAttributeId().stringValue())) { - policyVersion = attribute.getAttributeValue().getValue().toString(); - } else if ("Priority".equalsIgnoreCase(attribute.getAttributeId().stringValue())){ - try{ - priority = Integer.parseInt(attribute.getAttributeValue().getValue().toString()); - } catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Unable to Parse Integer for Priority. Setting to default value",e); - priority = DEFAULT_PRIORITY; - } - } else if (attribute.getAttributeId().stringValue().startsWith("matching")) { - matchingConditions.put(attribute.getAttributeId().stringValue() - .replaceFirst("(matching).", ""),attribute.getAttributeValue().getValue().toString()); - if ("ECOMPName".equals(attribute.getAttributeId().stringValue() - .replaceFirst("(matching).", ""))) { - match.setEcompName(attribute.getAttributeValue().getValue().toString()); - } else if ("ConfigName".equals(attribute.getAttributeId().stringValue() - .replaceFirst("(matching).", ""))) { - match.setConfigName(attribute.getAttributeValue().getValue().toString()); - } else { - configAttributes.put(attribute.getAttributeId().stringValue() - .replaceFirst("(matching).", ""),attribute.getAttributeValue().getValue().toString()); - } - } else if (attribute.getAttributeId().stringValue().startsWith("key:")) { - responseAttributes.put(attribute.getAttributeId().stringValue().replaceFirst("(key).", ""), - attribute.getAttributeValue().getValue().toString()); - } else if (attribute.getAttributeId().stringValue().startsWith("controller:")) { - responseAttributes.put("$"+ attribute.getAttributeId().stringValue(), - attribute.getAttributeValue().getValue().toString()); - } else if (attribute.getAttributeId().stringValue().startsWith("dependencies:")) { - responseAttributes.put("$dependency$", - attribute.getAttributeValue().getValue().toString()); - } - } - if (!configAttributes.isEmpty()) { - match.setConfigAttributes(configAttributes); - } - if ((config == 1) && (uri == 1)) { - // If there is a configuration. - try { - LOGGER.debug("Configuration Call to : " + configURL); - pdpResponse = configCall(pdpConfigLocation); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ e); - pdpResponse.setStatus("Error in Calling the Configuration URL "+ e, - PolicyResponseStatus.NO_ACTION_REQUIRED, - PolicyConfigStatus.CONFIG_NOT_FOUND); - } - pdpResponse.setPolicyName(policyName); - pdpResponse.setPolicyVersion(policyVersion); - pdpResponse.setMatchingConditions(matchingConditions); - pdpResponse.setResponseAttributes(responseAttributes); - if(!unique){ - combinedResult.add(pdpResponse); - }else{ - if(!uniqueResult.isEmpty()){ - if(uniqueResult.containsKey(priority)){ - // Not any more unique, check the matching conditions size - int oldSize = uniqueResult.get(priority).getMatchingConditions().size(); - int newSize = matchingConditions.size(); - if(oldSize < newSize){ - uniqueResult.put(priority, pdpResponse); - }else if(oldSize == newSize){ - pdpResponse = new PDPResponse(); - pdpResponse.setStatus("Two/more Policies have Same Priority and matching conditions, Please correct your policies.", - PolicyResponseStatus.NO_ACTION_REQUIRED, - PolicyConfigStatus.CONFIG_NOT_FOUND); - combinedResult.add(pdpResponse); - unique = false; - return combinedResult; - } - }else{ - uniqueResult.put(priority, pdpResponse); - } - }else{ - uniqueResult.put(priority, pdpResponse); - } - } - } else { - // Else it is Action Taken. - LOGGER.info("Action Taken by PDP. "); - actionTaken.putAll(adviseAttributes); - pdpResponse.setActionTaken(actionTaken); - pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.ACTION_TAKEN); - pdpResponse.setPolicyResponseMessage("Action Taken by the PDP"); - combinedResult.add(pdpResponse); - } - } - } - if (!result.getObligations().isEmpty()) { - // Obligation actions - // Action advised should be in obligations. - for (Obligation obligation : result.getObligations()) { - Map actionAdvised = new HashMap<>(); - PDPResponse pdpResponse = new PDPResponse(); - for (AttributeAssignment attribute : obligation.getAttributeAssignments()) { - actionAdvised.put(attribute.getAttributeId().stringValue(), - attribute.getAttributeValue().getValue().toString()); - } - pdpResponse.setActionAdvised(actionAdvised); - pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.ACTION_ADVISED); - pdpResponse.setPolicyResponseMessage("Action has been Advised "); - combinedResult.add(pdpResponse); - } - } - } - } - if(unique){ - // Select Unique policy. - int minNum = DEFAULT_PRIORITY; - for(int num: uniqueResult.keySet()){ - if(num < minNum){ - minNum = num; - } - } - combinedResult.add(uniqueResult.get(minNum)); - // Turn off Unique - unique = false; - } - - return combinedResult; - } - - private String getRainyDayTreatment(Result result) { - String treatment = null; - if (rainydayRequest!=null&& !result.getAssociatedAdvice().isEmpty()) { - // Get the desired treatment for requested errorCode from the Advice - for (Advice advice : result.getAssociatedAdvice()) { - Map adviseAttributes = new HashMap<>(); - for (AttributeAssignment attribute : advice.getAttributeAssignments()) { - adviseAttributes.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString()); - if ("treatment".equalsIgnoreCase(attribute.getAttributeId().stringValue())){ - treatment = attribute.getAttributeValue().getValue().toString(); - } - } - } - } - return treatment; - } - - private PDPResponse configCall(String pdpConfigLocation) throws Exception{ - PDPResponse pdpResponse = new PDPResponse(); - if(pdpConfigLocation.contains("/")){ - pdpConfigLocation = pdpConfigLocation.replace("/", File.separator); - } - InputStream inputStream = null; - try { - inputStream = new FileInputStream(new File(pdpConfigLocation)); - try { - if (pdpConfigLocation.endsWith("json")) { - pdpResponse.setType(PolicyType.JSON); - JsonReader jsonReader = Json.createReader(inputStream); - pdpResponse.setConfig(jsonReader.readObject().toString()); - jsonReader.close(); - } else if (pdpConfigLocation.endsWith("xml")) { - pdpResponse.setType(PolicyType.XML); - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - DocumentBuilder db = null; - try { - db = dbf.newDocumentBuilder(); - Document document = db.parse(inputStream); - DOMSource domSource = new DOMSource(document); - StringWriter writer = new StringWriter(); - StreamResult result = new StreamResult(writer); - TransformerFactory tf = TransformerFactory.newInstance(); - Transformer transformer; - transformer = tf.newTransformer(); - transformer.transform(domSource, result); - pdpResponse.setConfig(writer.toString()); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ e); - throw new Exception(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ "Unable to parse the XML config", e); - } - } else if (pdpConfigLocation.endsWith("properties")) { - pdpResponse.setType(PolicyType.PROPERTIES); - Properties configProp = new Properties(); - configProp.load(inputStream); - Map propVal = new HashMap<>(); - for(String name: configProp.stringPropertyNames()) { - propVal.put(name, configProp.getProperty(name)); - } - pdpResponse.setProperty(propVal); - } else if (pdpConfigLocation.endsWith("txt")) { - pdpResponse.setType(PolicyType.OTHER); - String other = IOUtils.toString(inputStream); - IOUtils.closeQuietly(inputStream); - pdpResponse.setConfig(other); - } else { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config Not Found"); - pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); - pdpResponse.setPolicyConfigMessage("Illegal form of Configuration Type Found."); - inputStream.close(); - return pdpResponse; - } - LOGGER.info("config Retrieved " + pdpConfigLocation); - pdpResponse.setStatus("Config Retrieved! ", - PolicyResponseStatus.NO_ACTION_REQUIRED, - PolicyConfigStatus.CONFIG_RETRIEVED); - return pdpResponse; - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - throw new Exception(XACMLErrorConstants.ERROR_PROCESS_FLOW + - "Cannot open a connection to the configURL", e); - } - } catch (MalformedURLException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in ConfigURL", e); - }finally{ - if(inputStream != null){ - inputStream.close(); - } - } - } - - private Response callPDP(Request request, - UUID requestID) throws Exception{ - Response response = null; - // Get the PDPEngine - if (requestID == null) { - requestID = UUID.randomUUID(); - LOGGER.debug("No request ID provided, sending generated ID: " + requestID.toString()); - } else { - LOGGER.debug("Using provided request ID: " + requestID.toString()); - } - PDPEngine pdpEngine = XACMLPdpServlet.getPDPEngine(); - if (pdpEngine == null) { - String message = "PDPEngine not loaded."; - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message); - return response; - } - // call the PDPEngine to decide and give the response on the Request. - try { - response = pdpEngine.decide(request); - LOGGER.info("Response from the PDP is: \n" + JSONResponse.toString(response)); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); - return null; - } - return response; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java deleted file mode 100644 index 2a526f751..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PolicyEngineImportService.java +++ /dev/null @@ -1,186 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.io.BufferedInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.UUID; - -import org.openecomp.policy.api.ImportParameters; -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.api.ImportParameters.IMPORT_TYPE; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.utils.PolicyUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.http.HttpStatus; -import org.springframework.web.multipart.MultipartFile; - -public class PolicyEngineImportService { - private static Logger LOGGER = FlexLogger.getLogger(PolicyEngineImportService.class.getName()); - - private String importResponse = null; - private HttpStatus status = HttpStatus.BAD_REQUEST; - private String message = null; - private ImportParameters importParameters = null; - private MultipartFile file = null; - - public PolicyEngineImportService(String importParametersJson, - MultipartFile file, - String requestID) { - try { - this.importParameters = PolicyUtils.jsonStringToObject(importParametersJson, ImportParameters.class); - } catch (Exception e) { - importResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e; - status = HttpStatus.BAD_REQUEST; - // This needs to stop here in case if there a issue here. Avoiding Null pointer exceptions. - return; - } - this.file = file; - if(importParameters.getRequestID()==null){ - UUID requestUUID = null; - if (requestID != null && !requestID.isEmpty()) { - try { - requestUUID = UUID.fromString(requestID); - } catch (IllegalArgumentException e) { - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); - } - }else{ - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); - } - this.importParameters.setRequestID(requestUUID); - } - try{ - run(); - specialCheck(); - }catch(PolicyException e){ - importResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e; - status = HttpStatus.BAD_REQUEST; - } - } - - private void specialCheck() { - if(importResponse==null || importResponse.contains("PE200")){ - status = HttpStatus.INTERNAL_SERVER_ERROR; - }else if(importResponse.contains("BAD REQUEST") || importResponse.contains("PE300")){ - status = HttpStatus.BAD_REQUEST; - } - } - - private void run() throws PolicyException{ - // Check Validation. - if(!getValidation()){ - LOGGER.error(message); - throw new PolicyException(message); - } - // Get Result. - try{ - status = HttpStatus.OK; - importResponse = processResult(); - }catch (Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - status = HttpStatus.BAD_REQUEST; - throw new PolicyException(e); - } - } - - private String processResult() throws PolicyException{ - String response = null; - InputStream targetStream = null; - String fileName = file.getOriginalFilename(); - switch (importParameters.getServiceType()){ - case MICROSERVICE: - if (fileName.endsWith(".xmi") || fileName.endsWith(".zip")){ - try { - targetStream = new BufferedInputStream(file.getInputStream()); - } catch (IOException e) { - response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in reading in the file provided"; - LOGGER.error(response + e); - return response; - } - }else{ - response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect File Type Given. Please use a file of type .xmi or .zip."; - LOGGER.error(response); - return response; - } - break; - case BRMSPARAM: - if (fileName.endsWith(".drl")){ - try { - targetStream = new BufferedInputStream(file.getInputStream()); - } catch (IOException e) { - response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in reading in the file provided"; - LOGGER.error(response + e); - return response; - } - }else{ - response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect File Type Given. Please use a file of type .drl"; - LOGGER.error(response); - return response; - } - break; - default: - response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect ServiceType Given. "; - LOGGER.error(response); - return response; - } - String[] parameters = new String[] {"importService=" + importParameters.getServiceType(), "serviceName=" - + importParameters.getServiceName(), "fileName=" + fileName, "version=" + importParameters.getVersion(), "description=" + importParameters.getDescription()}; - PAPServices papServices = new PAPServices(); - response = (String) papServices.callPAP(targetStream, parameters, importParameters.getRequestID(), "importMS"); - return response; - } - - private boolean getValidation() { - if(importParameters==null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + " no Import Parameters given. "; - return false; - } - if(importParameters.getServiceName()==null || importParameters.getServiceName().trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing service name value."; - return false; - } - if(importParameters.getServiceType()==null || importParameters.getServiceType().toString().trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing service Type value."; - return false; - } - if(importParameters.getServiceType().equals(IMPORT_TYPE.MICROSERVICE) && (importParameters.getVersion()==null || importParameters.getVersion().trim().isEmpty())){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing version value."; - return false; - } - if(file==null || file.isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing File."; - return false; - } - return true; - } - - public String getResult() { - return importResponse; - } - - public HttpStatus getResponseCode() { - return status; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PushPolicyService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PushPolicyService.java deleted file mode 100644 index a703c50d6..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/PushPolicyService.java +++ /dev/null @@ -1,236 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.util.UUID; - -import org.openecomp.policy.api.PolicyException; -import org.openecomp.policy.api.PushPolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; -import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; -import org.springframework.http.HttpStatus; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDPPolicy; - -public class PushPolicyService { - private static final Logger LOGGER = FlexLogger.getLogger(PushPolicyService.class.getName()); - - private String pushResult = null; - private HttpStatus status = HttpStatus.BAD_REQUEST; - private PushPolicyParameters pushPolicyParameters = null; - private String message = null; - private String policyName = null; - private String policyScope = null; - private String pdpGroup = null; - private String policyType = null; - private String filePrefix = null; - private String clientScope = null; - - public PushPolicyService(PushPolicyParameters pushPolicyParameters, - String requestID) { - this.pushPolicyParameters = pushPolicyParameters; - if(pushPolicyParameters.getRequestID()==null){ - UUID requestUUID = null; - if (requestID != null && !requestID.isEmpty()) { - try { - requestUUID = UUID.fromString(requestID); - } catch (IllegalArgumentException e) { - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); - } - }else{ - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); - } - this.pushPolicyParameters.setRequestID(requestUUID); - } - try{ - run(); - specialCheck(); - }catch(PolicyException e){ - pushResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e; - status = HttpStatus.BAD_REQUEST; - } - } - - private void specialCheck() { - if(pushResult.contains("BAD REQUEST") || pushResult.contains("PE300")){ - status = HttpStatus.BAD_REQUEST; - } - } - - private void run() throws PolicyException{ - // Check Validation. - if(!getValidation()){ - LOGGER.error(message); - throw new PolicyException(message); - } - // Process Results. - try{ - status = HttpStatus.OK; - pushResult = processResult(); - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - status = HttpStatus.BAD_REQUEST; - throw new PolicyException(e); - } - } - - private String processResult() throws PolicyException{ - PAPServices papServices = new PAPServices(); - String response = null; - StdPDPPolicy selectedPolicy = papServices.pushPolicy(policyScope, filePrefix, policyName, clientScope, pdpGroup, pushPolicyParameters.getRequestID()); - if(selectedPolicy==null){ - response = XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404. " - + "This indicates a problem with getting the version from the PAP or the policy does not exist."; - LOGGER.error(response); - return response; - } - try { - LOGGER.debug("StdPDPPolicy object contains: " + selectedPolicy.getId() + ", " + selectedPolicy.getName() + ", " + selectedPolicy.getLocation().toString()); - response = copyPolicy(selectedPolicy, pdpGroup, clientScope, pushPolicyParameters.getRequestID()); - } catch (PAPException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+e.getMessage()); - throw new PolicyException(e); - } - LOGGER.debug("copyPolicy response: " + response); - if(response.contains("successfully")){ - response = (String) papServices.callPAP(selectedPolicy, new String[]{"groupId=" + pdpGroup, "policyId="+selectedPolicy.getId(), "apiflag=addPolicyToGroup", "operation=PUT"}, pushPolicyParameters.getRequestID(), clientScope); - } - LOGGER.debug("Final API response: " + response); - return response; - } - - private String copyPolicy(PDPPolicy policy, String group, String policyType, UUID requestID) throws PAPException { - String response = null; - if (policy == null || group == null) { - throw new PAPException("Null input policy="+policy+" group="+group); - } - try { - StdPAPPolicy location = new StdPAPPolicy(policy.getLocation()); - response = copyFile(policy.getId(), group, location, policyType, requestID); - } 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); - } - return response; - } - - private String copyFile(String policyId, String group, StdPAPPolicy location, String clientScope, UUID requestID) throws PAPException { - String response = null; - // send the policy file to the PAP Servlet - PAPServices papService = new PAPServices(); - try { - response = (String) papService.callPAP(location, new String[] {"groupId=" + group, "policyId="+policyId, "apiflag=api", "operation=post"}, requestID, clientScope); - } catch (Exception e) { - String message = "Unable to PUT policy '" + policyId + "', e:" + e; - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); - throw new PAPException(message); - } - return response; - } - - private boolean getValidation() { - // While Validating, extract the required values. - if (pushPolicyParameters.getPolicyName() != null - && pushPolicyParameters.getPolicyName().contains(".")) { - policyName = pushPolicyParameters.getPolicyName().substring(pushPolicyParameters.getPolicyName().lastIndexOf('.') + 1, - pushPolicyParameters.getPolicyName().length()); - policyScope = pushPolicyParameters.getPolicyName().substring(0,pushPolicyParameters.getPolicyName().lastIndexOf('.')); - LOGGER.info("Name is " + policyName + " scope is " + policyScope); - } else { - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; - return false; - } - if (policyName==null||policyName.trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - return false; - } - policyType = pushPolicyParameters.getPolicyType(); - if(policyType== null || policyType.trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PolicyType given."; - return false; - } - - setClientScope(); - if(clientScope==null){ - return false; - } - - pdpGroup = pushPolicyParameters.getPdpGroup(); - if(pdpGroup==null || pdpGroup.trim().isEmpty()){ - pdpGroup = "default"; - } - - LOGGER.debug("clientScope is " + clientScope); - LOGGER.debug("filePrefix is " + filePrefix); - - return true; - } - - private void setClientScope() { - if ("Firewall".equalsIgnoreCase(policyType)) { - clientScope = "ConfigFirewall"; - filePrefix = "Config_FW_"; - } else if ("Action".equalsIgnoreCase(policyType)) { - clientScope = "Action"; - filePrefix = "Action_"; - } else if ("Decision".equalsIgnoreCase(policyType)) { - clientScope = "Decision"; - filePrefix = "Decision_"; - } else if ("Base".equalsIgnoreCase(policyType)) { - clientScope = "Config"; - filePrefix = "Config_"; - } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyType)) { - clientScope = "ConfigClosedLoop"; - filePrefix = "Config_Fault_"; - } else if ("ClosedLoop_PM".equalsIgnoreCase(policyType)) { - clientScope = "ConfigClosedLoop"; - filePrefix = "Config_PM_"; - } else if ("MicroService".equalsIgnoreCase(policyType)) { - clientScope = "ConfigMS"; - filePrefix = "Config_MS_"; - } else if ("BRMS_RAW".equalsIgnoreCase(policyType)) { - clientScope = "ConfigBrmsRaw"; - filePrefix = "Config_BRMS_Raw_"; - } else if ("BRMS_PARAM".equalsIgnoreCase(policyType)) { - clientScope = "ConfigBrmsParam"; - filePrefix = "Config_BRMS_Param_"; - } else { - clientScope = null; - message = XACMLErrorConstants.ERROR_DATA_ISSUE + policyType - + " is not a valid Policy Type."; - } - } - - public String getResult() { - return pushResult; - } - - public HttpStatus getResponseCode() { - return status; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/SendEventService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/SendEventService.java deleted file mode 100644 index c16872ebc..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/services/SendEventService.java +++ /dev/null @@ -1,170 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.UUID; - -import javax.json.Json; -import javax.json.JsonArrayBuilder; -import javax.json.JsonObject; -import javax.json.JsonObjectBuilder; - -import org.openecomp.policy.api.EventRequestParameters; -import org.openecomp.policy.api.PolicyEventException; -import org.openecomp.policy.api.PolicyResponse; -import org.openecomp.policy.api.PolicyResponseStatus; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.models.PDPResponse; -import org.openecomp.policy.std.StdPolicyResponse; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.http.HttpStatus; - -public class SendEventService { - private static final Logger LOGGER = FlexLogger.getLogger(SendEventService.class.getName()); - - private Collection policyResponses = null; - private HttpStatus status = HttpStatus.BAD_REQUEST; - private EventRequestParameters eventRequestParameters = null; - private String message = null; - - public SendEventService(EventRequestParameters eventRequestParameters, - String requestID) { - this.eventRequestParameters=eventRequestParameters; - if(eventRequestParameters.getRequestID()==null){ - UUID requestUUID = null; - if (requestID != null && !requestID.isEmpty()) { - try { - requestUUID = UUID.fromString(requestID); - } catch (IllegalArgumentException e) { - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); - } - }else{ - requestUUID = UUID.randomUUID(); - LOGGER.info("Generated Random UUID: " + requestUUID.toString()); - } - this.eventRequestParameters.setRequestID(requestUUID); - } - policyResponses = new ArrayList<>(); - try{ - run(); - }catch(PolicyEventException e){ - StdPolicyResponse policyResponse = new StdPolicyResponse(); - policyResponse.setPolicyResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE+e); - policyResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED); - policyResponses.add(policyResponse); - status = HttpStatus.BAD_REQUEST; - } - } - - private void run() throws PolicyEventException{ - // getValidation. - if(!getValidation()){ - LOGGER.error(message); - throw new PolicyEventException(message); - } - // Generate Request. - String modelString = getModel().toString(); - LOGGER.debug("Generated JSON Request is: " + modelString); - // Process Result. - try { - PDPServices pdpServices = new PDPServices(); - status = HttpStatus.OK; - policyResponses = eventResult(pdpServices.generateRequest(modelString, eventRequestParameters.getRequestID(),false, false)); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); - status = HttpStatus.BAD_REQUEST; - throw new PolicyEventException(XACMLErrorConstants.ERROR_DATA_ISSUE +e); - } - } - - private Collection eventResult( - Collection generateRequest) { - Collection result = new HashSet<>(); - if (generateRequest == null) { - return result; - } - if (!generateRequest.isEmpty()) { - for (PDPResponse stdStatus : generateRequest) { - StdPolicyResponse policyResponse = new StdPolicyResponse(); - policyResponse.setActionAdvised(stdStatus.getActionAdvised()); - policyResponse.setActionTaken(stdStatus.getActionTaken()); - policyResponse.setPolicyResponseMessage(stdStatus.getPolicyResponseMessage()); - policyResponse.setPolicyResponseStatus(stdStatus.getPolicyResponseStatus()); - policyResponse.setRequestAttributes(eventRequestParameters.getEventAttributes()); - result.add(policyResponse); - } - } - return result; - } - - private JsonObject getModel() throws PolicyEventException{ - JsonArrayBuilder resourceArray = Json.createArrayBuilder(); - Map eventAttributes = eventRequestParameters.getEventAttributes(); - for (Entry key : eventAttributes.entrySet()) { - if (key.getKey().isEmpty()) { - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key"; - LOGGER.error(message); - throw new PolicyEventException(message); - } - JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); - if (key.getValue().matches("[0-9]+")) { - int val = Integer.parseInt(key.getValue()); - resourceBuilder.add("Value", val); - } else { - resourceBuilder.add("Value", key.getValue()); - } - resourceBuilder.add("AttributeId", key.getKey()); - resourceArray.add(resourceBuilder); - } - return Json.createObjectBuilder() - .add("Request", Json.createObjectBuilder() - .add("Resource",Json.createObjectBuilder() - .add("Attribute",resourceArray))) - .build(); - } - - private boolean getValidation() { - if (eventRequestParameters == null) { - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Parameters Given. "; - return false; - } - if (eventRequestParameters.getEventAttributes() == null || eventRequestParameters.getEventAttributes().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Attributes Given. "; - return false; - } - return true; - } - - public Collection getResult() { - return policyResponses; - } - - public HttpStatus getResponseCode() { - return status; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/utils/PolicyApiUtils.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/utils/PolicyApiUtils.java deleted file mode 100644 index 984cc907b..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/api/utils/PolicyApiUtils.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.utils; - -import java.io.StringReader; - -import javax.json.Json; -import javax.json.JsonException; -import javax.json.JsonObject; -import javax.json.JsonReader; -import javax.json.stream.JsonParsingException; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -import com.google.common.base.CharMatcher; - -public class PolicyApiUtils { - private static Logger LOGGER = FlexLogger.getLogger(PolicyApiUtils.class - .getName()); - - public static Boolean validateNONASCIICharactersAndAllowSpaces( - String jsonString) { - Boolean isValidForm = false; - if (jsonString.isEmpty()) { - LOGGER.error("The Value is empty."); - return false; - } else { - if (CharMatcher.ASCII.matchesAllOf((CharSequence) jsonString)) { - LOGGER.info("The Value does not contain ASCII Characters"); - isValidForm = true; - } else { - LOGGER.error("The Value Contains Non ASCII Characters"); - isValidForm = false; - } - } - return isValidForm; - } - - public static boolean isNumeric(String str) { - for (char c : str.toCharArray()) { - if (!Character.isDigit(c)) - return false; - } - return true; - } - - public static JsonObject stringToJsonObject(String value) - throws JsonException, JsonParsingException, IllegalStateException { - JsonReader jsonReader = Json.createReader(new StringReader(value)); - JsonObject object = jsonReader.readObject(); - jsonReader.close(); - return object; - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java deleted file mode 100644 index 5c3dcad60..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPApiAuth.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.config; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -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.HashMap; -import java.util.Map; -import java.util.Properties; -import java.util.StringTokenizer; - -import org.openecomp.policy.api.PolicyEngineException; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -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.utils.AAFPolicyClient; -import org.openecomp.policy.utils.AAFPolicyException; -import org.openecomp.policy.utils.PolicyUtils; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; - -import com.att.research.xacml.util.XACMLProperties; - -public class PDPApiAuth { - private static final Logger LOGGER = FlexLogger.getLogger(PDPApiAuth.class); - - private static String environment = null; - private static Path clientPath = null; - private static Map> clientMap = null; - private static Long oldModified = null; - private static AAFPolicyClient aafClient = null; - - private PDPApiAuth(){ - // Private Constructor - } - - /* - * Set Property by reading the properties File. - */ - public static void setProperty() { - environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); - String clientFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PEP_IDFILE); - if(clientFile!=null){ - clientPath = Paths.get(clientFile); - } - try { - aafClient = AAFPolicyClient.getInstance(XACMLProperties.getProperties()); - } catch (AAFPolicyException | IOException e) { - LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AAF Client Not instantiated properly."); - } - } - - /* - * Return Environment value of the PDP servlet. - */ - public static String getEnvironment() { - if(environment==null){ - setProperty(); - } - return environment; - } - - /* - * Security check for authentication and authorizations. - */ - public static boolean checkPermissions(String clientEncoding, String requestID, - String resource) { - try{ - String[] userNamePass = PolicyUtils.decodeBasicEncoding(clientEncoding); - if(userNamePass==null || userNamePass.length==0){ - String usernameAndPassword = null; - byte[] decodedBytes = Base64.getDecoder().decode(clientEncoding); - usernameAndPassword = new String(decodedBytes, "UTF-8"); - StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); - String username = tokenizer.nextToken(); - String password = tokenizer.nextToken(); - userNamePass= new String[]{username, password}; - } - LOGGER.info("User " + userNamePass[0] + " is Accessing Policy Engine API."); - Boolean result = false; - // Check Backward Compatibility. - try{ - result = clientAuth(userNamePass); - }catch(Exception e){ - LOGGER.error(MessageCodes.ERROR_PERMISSIONS, e); - } - if(!result){ - String aafPolicyNameSpace = XACMLProperties.getProperty("policy.aaf.namespace"); - String aafResource = XACMLProperties.getProperty("policy.aaf.resource"); - if(!userNamePass[0].contains("@") && aafPolicyNameSpace!= null){ - userNamePass[0] = userNamePass[0] + "@" + aafPolicyNameSpace; - }else{ - LOGGER.info("No AAF NameSpace specified in properties"); - } - if(aafResource != null){ - resource = aafResource + resource; - }else{ - LOGGER.info("No AAF Resource specified in properties"); - } - LOGGER.info("Contacting AAF in : " + environment); - result = aafClient.checkAuthPerm(userNamePass[0], userNamePass[1], resource, environment, ".*"); - } - return result; - }catch(Exception e){ - LOGGER.error(MessageCodes.ERROR_PERMISSIONS, e); - return false; - } - } - - private static Boolean clientAuth(String[] userNamePass){ - if(clientPath==null){ - setProperty(); - } - if (!clientPath.toFile().exists()) { - return false; - }else if(clientPath.toString().endsWith(".properties")) { - try { - readProps(clientPath); - if (clientMap.containsKey(userNamePass[0]) && clientMap.get(userNamePass[0]).get(0).equals(userNamePass[1])) { - return true; - } - }catch(PolicyEngineException e){ - LOGGER.error(MessageCodes.ERROR_PERMISSIONS, e); - return false; - } - } - return false; - } - - private static Map> readProps(Path clientPath) throws PolicyEngineException{ - if(oldModified!=null){ - Long newModified = clientPath.toFile().lastModified(); - if (newModified == oldModified) { - return clientMap; - } - } - InputStream in; - Properties clientProp = new Properties(); - try { - in = new FileInputStream(clientPath.toFile()); - clientProp.load(in); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR , e); - throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Load the Properties file", e); - } - // Read the Properties and Load the Clients and their scopes. - clientMap = new HashMap<>(); - // - for (Object propKey : clientProp.keySet()) { - String clientID = (String)propKey; - String clientValue = clientProp.getProperty(clientID); - if (clientValue != null && clientValue.contains(",")) { - ArrayList clientValues = new ArrayList<>(Arrays.asList(clientValue.split("\\s*,\\s*"))); - if(clientValues.get(0)!=null || clientValues.get(1)!=null || clientValues.get(0).isEmpty() || clientValues.get(1).isEmpty()){ - clientMap.put(clientID, clientValues); - } - } - } - if (clientMap.isEmpty()) { - LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS + "No Clients ID , Client Key and Scopes are available. Cannot serve any Clients !!"); - throw new PolicyEngineException("Empty Client file"); - } - oldModified = clientPath.toFile().lastModified(); - return clientMap; - } -} \ No newline at end of file diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPRestConfig.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPRestConfig.java deleted file mode 100644 index 6686673d3..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPRestConfig.java +++ /dev/null @@ -1,77 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.config; - -import javax.servlet.MultipartConfigElement; - -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.pdp.rest.api.controller.PolicyEngineServices; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -import springfox.documentation.builders.ApiInfoBuilder; -import springfox.documentation.builders.PathSelectors; -import springfox.documentation.builders.RequestHandlerSelectors; -import springfox.documentation.service.ApiInfo; -import springfox.documentation.spi.DocumentationType; -import springfox.documentation.spring.web.plugins.Docket; -import springfox.documentation.swagger2.annotations.EnableSwagger2; - -@Configuration -@EnableWebMvc -@EnableSwagger2 -@ComponentScan(basePackageClasses = PolicyEngineServices.class) -public class PDPRestConfig extends WebMvcConfigurerAdapter{ - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); - } - - private ApiInfo apiInfo(){ - return new ApiInfoBuilder() - .title("Policy Engine REST API") - .description("This API helps to make queries against Policy Engine") - .version("3.0") - .build(); - } - - @Bean - public Docket policyAPI(){ - PolicyLogger.info("Setting up Swagger... "); - return new Docket(DocumentationType.SWAGGER_2) - .select() - .apis(RequestHandlerSelectors.basePackage("org.openecomp.policy.pdp.rest.api")) - .paths(PathSelectors.any()) - .build() - .apiInfo(apiInfo()); - } - - @Bean - public MultipartConfigElement multipartConfigElement(){ - String location = System.getProperty("java.io.tmpdir"); - MultipartConfigElement mp = new MultipartConfigElement(location); - return mp; - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPRestInitializer.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPRestInitializer.java deleted file mode 100644 index e6acc61bd..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/config/PDPRestInitializer.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.config; - -import javax.servlet.MultipartConfigElement; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; -import org.springframework.web.servlet.DispatcherServlet; - -/** - * PDP REST API configuration initialization. - * - * @version 0.1 - */ -public class PDPRestInitializer implements WebApplicationInitializer { - @Override - public void onStartup(ServletContext container) throws ServletException { - PolicyLogger.info("PDP-REST Application Initialization Started... "); - AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); - ctx.register(PDPRestConfig.class); - ctx.setServletContext(container); - ctx.refresh(); - ServletRegistration.Dynamic servlet = container.addServlet( - "dispatcher", new DispatcherServlet(ctx)); - servlet.setLoadOnStartup(1); - servlet.addMapping("/api/*"); - servlet.setMultipartConfig(ctx.getBean(MultipartConfigElement.class)); - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPIPFinderFactory.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPIPFinderFactory.java deleted file mode 100644 index 6de84d174..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPIPFinderFactory.java +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.impl; - -import java.util.Properties; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import com.att.research.xacml.api.pip.PIPException; -import com.att.research.xacml.api.pip.PIPFinder; -import com.att.research.xacml.api.pip.PIPFinderFactory; -import com.att.research.xacml.std.pip.finders.ConfigurableEngineFinder; -import com.att.research.xacml.util.XACMLProperties; - -public class XACMLPdpPIPFinderFactory extends PIPFinderFactory { - private ConfigurableEngineFinder pipFinder; - - private static Log LOGGER = LogFactory.getLog(XACMLPdpPIPFinderFactory.class); - - public XACMLPdpPIPFinderFactory() { - } - - public XACMLPdpPIPFinderFactory(Properties properties) { - } - - @Override - public PIPFinder getFinder() throws PIPException { - if (pipFinder == null) { - synchronized(this) { - if (pipFinder == null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Creating default configurable engine finder"); - } - pipFinder = new ConfigurableEngineFinder(); - Properties xacmlProperties = null; - try { - xacmlProperties = XACMLProperties.getProperties(); - } catch (Exception ex) { - LOGGER.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR+ "Exception getting XACML properties: " + ex.getMessage(), ex); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, ex, "Exception getting XACML properties"); - return null; - } - if (xacmlProperties != null) { - ((ConfigurableEngineFinder)pipFinder).configure(xacmlProperties); - } - } - } - } - return pipFinder; - } - - @Override - public PIPFinder getFinder(Properties properties) throws PIPException { - if (pipFinder == null) { - synchronized(this) { - if (pipFinder == null) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Creating configurable engine finder using: " + properties); - } - pipFinder = new ConfigurableEngineFinder(); - ((ConfigurableEngineFinder)pipFinder).configure(properties); - } - } - } - return this.pipFinder; - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPolicyFinderFactory.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPolicyFinderFactory.java deleted file mode 100644 index 0d6d12a63..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/impl/XACMLPdpPolicyFinderFactory.java +++ /dev/null @@ -1,208 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.impl; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import com.att.research.xacml.std.StdStatusCode; -import com.att.research.xacml.std.dom.DOMStructureException; -import com.att.research.xacml.util.FactoryException; -import com.att.research.xacml.util.XACMLProperties; -import com.att.research.xacmlatt.pdp.policy.Policy; -import com.att.research.xacmlatt.pdp.policy.PolicyDef; -import com.att.research.xacmlatt.pdp.policy.PolicyFinder; -import com.att.research.xacmlatt.pdp.policy.PolicyFinderFactory; -import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef; -import com.att.research.xacmlatt.pdp.std.StdPolicyFinder; -import com.google.common.base.Splitter; - -public class XACMLPdpPolicyFinderFactory extends PolicyFinderFactory { - public static final String PROP_FILE = ".file"; - public static final String PROP_URL = ".url"; - - private static Log LOGGER = LogFactory.getLog(XACMLPdpPolicyFinderFactory.class); - private List rootPolicies; - private List referencedPolicies; - private boolean needsInit = true; - - private Properties properties = null; - - public XACMLPdpPolicyFinderFactory() { - // - // Here we differ from the StdPolicyFinderFactory in that we initialize right away. - // We do not wait for a policy request to happen to look for and load policies. - // - this.init(); - } - - public XACMLPdpPolicyFinderFactory(Properties properties) { - // - // Save our properties - // - this.properties = properties; - // - // Here we differ from the StdPolicyFinderFactory in that we initialize right away. - // We do not wait for a policy request to happen to look for and load policies. - // - this.init(); - } - - /** - * Loads the PolicyDef for the given String identifier by looking first - * for a ".file" property associated with the ID and using that to load from a File and - * looking for a ".url" property associated with the ID and using that to load from a URL. - * - * @param policyId the String identifier for the policy - * @return a PolicyDef loaded from the given identifier - */ - protected PolicyDef loadPolicyDef(String policyId) { - String propLocation = null; - if (this.properties == null) { - propLocation = XACMLProperties.getProperty(policyId + PROP_FILE); - } else { - propLocation = this.properties.getProperty(policyId + PROP_FILE); - } - if (propLocation != null) { - File fileLocation = new File(propLocation); - if (!fileLocation.exists()) { - XACMLPdpPolicyFinderFactory.LOGGER.error("Policy file " + fileLocation.getAbsolutePath() + " does not exist."); - } else if (!fileLocation.canRead()) { - XACMLPdpPolicyFinderFactory.LOGGER.error("Policy file " + fileLocation.getAbsolutePath() + " cannot be read."); - } else { - try { - XACMLPdpPolicyFinderFactory.LOGGER.info("Loading policy file " + fileLocation); - PolicyDef policyDef = DOMPolicyDef.load(fileLocation); - if (policyDef != null) { - return policyDef; - } - } catch (DOMStructureException ex) { - XACMLPdpPolicyFinderFactory.LOGGER.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error loading policy file " + fileLocation.getAbsolutePath() + ": " + ex.getMessage(), ex); - return new Policy(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, ex.getMessage()); - } - } - } - if (this.properties == null) { - propLocation = XACMLProperties.getProperty(policyId + PROP_URL); - } else { - propLocation = this.properties.getProperty(policyId + PROP_URL); - } - if (propLocation != null) { - InputStream is = null; - try { - URL url = new URL(propLocation); - URLConnection urlConnection = url.openConnection(); - XACMLPdpPolicyFinderFactory.LOGGER.info("Loading policy file " + url.toString()); - is = urlConnection.getInputStream(); - PolicyDef policyDef = DOMPolicyDef.load(is); - if (policyDef != null) { - return policyDef; - } - } catch (MalformedURLException ex) { - XACMLPdpPolicyFinderFactory.LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Invalid URL " + propLocation + ": " + ex.getMessage(), ex); - } catch (IOException ex) { - XACMLPdpPolicyFinderFactory.LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "IOException opening URL " + propLocation + ": " + ex.getMessage(), ex); - } catch (DOMStructureException ex) { - XACMLPdpPolicyFinderFactory.LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Invalid Policy " + propLocation + ": " + ex.getMessage(), ex); - return new Policy(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, ex.getMessage()); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - XACMLPdpPolicyFinderFactory.LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception closing InputStream for GET of url " + propLocation + " : " + e.getMessage() + " (May be memory leak)", e); - } - } - } - } - - XACMLPdpPolicyFinderFactory.LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"No known location for Policy " + policyId); - return null; - } - - /** - * Finds the identifiers for all of the policies referenced by the given property name in the - * XACMLProperties and loads them using the requested loading method. - * - * @param propertyName the String name of the property containing the list of policy identifiers - * @return a List of PolicyDefs loaded from the given property name - */ - protected List getPolicyDefs(String propertyName) { - String policyIds = XACMLProperties.getProperty(propertyName); - if (policyIds == null || policyIds.length() == 0) { - return null; - } - - Iterable policyIdArray = Splitter.on(',').trimResults().omitEmptyStrings().split(policyIds); - if (policyIdArray == null) { - return null; - } - - List listPolicyDefs = new ArrayList<>(); - for (String policyId : policyIdArray) { - PolicyDef policyDef = this.loadPolicyDef(policyId); - if (policyDef != null) { - listPolicyDefs.add(policyDef); - } - } - return listPolicyDefs; - } - - protected synchronized void init() { - if (this.needsInit) { - if (XACMLPdpPolicyFinderFactory.LOGGER.isDebugEnabled()) { - XACMLPdpPolicyFinderFactory.LOGGER.debug("Initializing"); - } - this.rootPolicies = this.getPolicyDefs(XACMLProperties.PROP_ROOTPOLICIES); - this.referencedPolicies = this.getPolicyDefs(XACMLProperties.PROP_REFERENCEDPOLICIES); - if (XACMLPdpPolicyFinderFactory.LOGGER.isDebugEnabled()) { - XACMLPdpPolicyFinderFactory.LOGGER.debug("Root Policies: " + this.rootPolicies); - XACMLPdpPolicyFinderFactory.LOGGER.debug("Referenced Policies: " + this.referencedPolicies); - } - this.needsInit = false; - } - } - - @Override - public PolicyFinder getPolicyFinder() throws FactoryException { - // - // Force using any properties that were passed upon construction - // - return new StdPolicyFinder(this.rootPolicies, this.referencedPolicies, this.properties); - } - - @Override - public PolicyFinder getPolicyFinder(Properties properties) throws FactoryException { - return new StdPolicyFinder(this.rootPolicies, this.referencedPolicies, properties); - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMBeanListener.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMBeanListener.java deleted file mode 100644 index c56ddba9a..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMBeanListener.java +++ /dev/null @@ -1,85 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.jmx; - -import java.lang.management.ManagementFactory; - -import javax.management.MBeanServer; -import javax.management.ObjectName; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import javax.servlet.annotation.WebListener; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -/** - * - * - */ - -@WebListener -public class PdpRestMBeanListener implements ServletContextListener { - private static final String JMX_OBJECT_NAME = "PdpRest:type=PdpRestMonitor"; - private static final Logger LOGGER = FlexLogger.getLogger(PdpRestMBeanListener.class); - - private ObjectName objectName; - - @Override - public void contextInitialized(ServletContextEvent contextEvent) { - if (LOGGER.isInfoEnabled()) - LOGGER.info("Registering."); - - final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); - try { - objectName = new ObjectName(JMX_OBJECT_NAME); - server.registerMBean(PdpRestMonitor.getSingleton(), objectName); - LOGGER.info("MBean registered: " + objectName); - } catch (Exception e) { - - LOGGER.warn(e.getMessage(), e); - - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to Register " +e.getMessage(), e); - - } - } - // mark - @Override - public void contextDestroyed(ServletContextEvent contextEvent) { - if (LOGGER.isInfoEnabled()) - LOGGER.info("Unregistering"); - final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); - try { - objectName = new ObjectName(JMX_OBJECT_NAME); - server.unregisterMBean(objectName); - if (LOGGER.isInfoEnabled()) - LOGGER.info("MBean unregistered: " + objectName); - } catch (Exception e) { - - LOGGER.warn(e.getMessage(), e); - - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to Destroy Context" +e.getMessage(), e); - - } - } - -} - diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMonitor.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMonitor.java deleted file mode 100644 index 1c088b24e..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMonitor.java +++ /dev/null @@ -1,162 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.jmx; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.atomic.AtomicLong; - -import org.openecomp.policy.xacml.util.MetricsUtil.AvgLatency; -import org.openecomp.policy.xacml.util.MetricsUtil.MaxLatency; -import org.openecomp.policy.xacml.util.MetricsUtil.MinLatency; - -public class PdpRestMonitor implements PdpRestMonitorMBean { - private static PdpRestMonitor singleton = new PdpRestMonitor(); - - private final AtomicLong pdpEvaluationAttempts = new AtomicLong(); - private final AtomicLong pdpEvaluationSuccesses = new AtomicLong(); - private final AtomicLong pdpEvaluationNA = new AtomicLong(); - private final AtomicLong pdpEvaluationPermit = new AtomicLong(); - private final AtomicLong pdpEvaluationDeny = new AtomicLong(); - private final Map policyCount = new HashMap<>(); - - private final MinLatency pdpEngineDecisionMinLatency = new MinLatency(); - private final MaxLatency pdpEngineDecisionMaxLatency = new MaxLatency(); - private final AvgLatency pdpEngineDecisionAvgLatency = new AvgLatency(); - - private volatile long lastDecisionLatency = 0; - - @Override - public long getPdpEvaluationAttempts() { - return pdpEvaluationAttempts.longValue(); - } - @Override - public long getPdpEvaluationPermit() { - return pdpEvaluationPermit.longValue(); - } - @Override - public long getPdpEvaluationDeny() { - return pdpEvaluationDeny.longValue(); - } - @Override - public long getPdpEvaluationSuccesses() { - return pdpEvaluationSuccesses.longValue(); - } - - @Override - public long getpdpEvaluationNA() { - return pdpEvaluationNA.longValue(); - } - @Override - public long getLastDecisionLatency() { - return lastDecisionLatency; - } - - /** - * @return the pdpEngineDecisionMinLatency - */ - @Override - public long getPdpEngineDecisionMinLatency() { - return pdpEngineDecisionMinLatency.min(); - } - - /** - * @return the pdpEngineDecisionMaxLatency - */ - @Override - public long getPdpEngineDecisionMaxLatency() { - return pdpEngineDecisionMaxLatency.max(); - } - - /** - * @return the pdpEngineDecisionAvgLatency - */ - @Override - public long getPdpEngineDecisionAvgLatency() { - return pdpEngineDecisionAvgLatency.avg(); - } - - @Override - public synchronized void resetLatency() { - this.lastDecisionLatency = 0; - this.pdpEngineDecisionMinLatency.reset(); - this.pdpEngineDecisionMaxLatency.reset(); - this.pdpEngineDecisionAvgLatency.reset(); - } - - @Override - public synchronized void resetCounters() { - this.pdpEvaluationAttempts.set(0); - this.pdpEvaluationSuccesses.set(0); - this.pdpEvaluationNA.set(0); - this.policyCount.clear(); - } - - public void pdpEvaluationAttempts() { - pdpEvaluationAttempts.incrementAndGet(); - } - - public void pdpEvaluationSuccess() { - pdpEvaluationSuccesses.incrementAndGet(); - } - - public void pdpEvaluationNA(){ - pdpEvaluationNA.incrementAndGet(); - } - public void pdpEvaluationPermit(){ - pdpEvaluationPermit.incrementAndGet(); - } - public void pdpEvaluationDeny(){ - pdpEvaluationDeny.incrementAndGet(); - } - - public synchronized void computeLatency(long latency) { - this.lastDecisionLatency = latency; - this.pdpEngineDecisionMinLatency.compute(latency); - this.pdpEngineDecisionMaxLatency.compute(latency); - this.pdpEngineDecisionAvgLatency.compute(latency); - } - - public void policyCountAdd(String policyID, Integer count){ - int countValue = count; - if (policyCount.containsKey(policyID)){ - countValue = countValue + policyCount.get(policyID); - } - policyCount.put(policyID, countValue); - } - public Map getpolicyMap() { - return policyCount; - } - public Integer getpolicyCount(String policyID) { - if (policyCount.containsKey(policyID)){ - return policyCount.get(policyID); - } - return null; - } - - public static PdpRestMonitor getSingleton() { - return singleton; - } - public static void setSingleton(PdpRestMonitor singleton) { - PdpRestMonitor.singleton = singleton; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMonitorMBean.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMonitorMBean.java deleted file mode 100644 index e7db09d24..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/jmx/PdpRestMonitorMBean.java +++ /dev/null @@ -1,40 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.jmx; - -import java.util.Map; - -public interface PdpRestMonitorMBean { - public long getPdpEvaluationAttempts(); - public long getPdpEvaluationSuccesses(); - public long getLastDecisionLatency(); - public long getPdpEngineDecisionMinLatency(); - public long getPdpEngineDecisionMaxLatency(); - public long getPdpEngineDecisionAvgLatency(); - public Integer getpolicyCount(String policyID); - - public void resetLatency(); - public void resetCounters(); - public long getpdpEvaluationNA(); - public long getPdpEvaluationPermit(); - public long getPdpEvaluationDeny(); - public Map getpolicyMap(); -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java deleted file mode 100644 index a1d0ece83..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java +++ /dev/null @@ -1,229 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.notifications; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.UUID; - -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.utils.BusConsumer; -import org.openecomp.policy.utils.BusPublisher; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; - -import com.att.nsa.cambria.client.CambriaClientFactory; -import com.att.nsa.cambria.client.CambriaConsumer; -import com.att.nsa.cambria.client.CambriaPublisher; -import com.att.research.xacml.util.XACMLProperties; - -@SuppressWarnings("deprecation") -public class ManualNotificationUpdateThread implements Runnable { - - private static final Logger LOGGER = FlexLogger.getLogger(ManualNotificationUpdateThread.class); - - private static String topic = null; - private static CambriaConsumer CConsumer = null; - private static String clusterList = null; - private static String update = null; - private static BusConsumer dmaapConsumer = null; - private static List dmaapList = null; - private static String propNotificationType = null; - private static String aafLogin = null; - private static String aafPassword = null; - - public volatile boolean isRunning = false; - - public synchronized boolean isRunning() { - return this.isRunning; - } - - public synchronized void terminate() { - this.isRunning = false; - } - - /** - * - * This is our thread that runs on startup if the system is configured to UEB to accept manual update requests - * - */ - @Override - public void run() { - synchronized(this) { - this.isRunning = true; - } - - URL aURL = null; - String group = UUID.randomUUID ().toString (); - String id = "0"; - String returnTopic = null; - propNotificationType = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TYPE); - if ("ueb".equals(propNotificationType)){ - try { - clusterList = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS).trim(); - String url = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID); - aURL = new URL(url); - topic = aURL.getHost() + aURL.getPort(); - } catch (NumberFormatException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get UEB cluster list or pdp url: ", e); - this.isRunning = false; - } catch (MalformedURLException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing URL to create topic for Notification ", e); - } - if(aURL != null){ - String consumerTopic = aURL.getHost() + aURL.getPort() + "UpdateRequest"; - SendMessage(consumerTopic, "Starting-Topic"); - final LinkedList urlList = new LinkedList<> (); - for ( String u : clusterList.split ( "," ) ){ - urlList.add ( u ); - } - - try { - CConsumer = CambriaClientFactory.createConsumer ( null, urlList, consumerTopic , group, id, 20*1000, 1000 ); - } catch (MalformedURLException | GeneralSecurityException e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create UEB Consumer: ", e1); - } - - while (this.isRunning()) { - LOGGER.debug("While loop test _ take out "); - try { - for ( String msg : CConsumer.fetch () ){ - LOGGER.debug("Manual Notification Recieved Message " + msg + " from UEB cluster : "); - returnTopic = processMessage(msg); - if(returnTopic != null){ - SendMessage(returnTopic, update); - } - } - } catch (IOException e) { - LOGGER.debug(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing UEB message" + e); - } - } - LOGGER.debug("Stopping UEB Consumer loop will no longer fetch messages from the cluster"); - } - } else if ("dmaap".equals(propNotificationType)) { - String dmaapServers = null; - try { - dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); - topic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC); - aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN"); - aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD"); - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get DMaaP servers list:", e); - this.isRunning = false; - } - - if(dmaapServers==null || topic==null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); - try { - throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); - } catch (Exception e) { - LOGGER.error(e); - } - } - - dmaapServers.trim(); - topic.trim(); - aafLogin.trim(); - aafPassword.trim(); - - String consumerTopic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC).trim(); - SendMessage(consumerTopic, "Starting-Topic"); - dmaapList = new ArrayList<>(); - for ( String u : dmaapServers.split ( "," ) ){ - dmaapList.add ( u ); - } - - try { - - dmaapConsumer = new BusConsumer.DmaapConsumerWrapper(dmaapList, consumerTopic, aafLogin, aafPassword, group, id, 20*1000, 1000); - } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create DMaaP Consumer: ", e1); - } - - while (this.isRunning()) { - LOGGER.debug("While loop test _ take out "); - try { - for ( String msg : dmaapConsumer.fetch () ){ - LOGGER.debug("Manual Notification Recieved Message " + msg + " from DMaaP server : "); - returnTopic = processMessage(msg); - if(returnTopic != null){ - SendMessage(returnTopic, update); - } - } - }catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing DMaaP message: ", e); } - } - LOGGER.debug("Stopping DMaaP Consumer loop will no longer fetch messages from the servers"); - } - } - - private void SendMessage( String topic, String message) { - CambriaPublisher pub = null; - BusPublisher publisher = null; - try { - if ("ueb".equals(propNotificationType)) { - pub = CambriaClientFactory.createSimplePublisher (null, clusterList, topic ); - pub.send( "pdpReturnMessage", message ); - LOGGER.debug("Sending Message to UEB topic: " + topic); - pub.close(); - - } else if ("dmaap".equals(propNotificationType)){ - publisher = new BusPublisher.DmaapPublisherWrapper(dmaapList,topic,aafLogin,aafPassword); - publisher.send( "pdpReturnMessage", message ); - LOGGER.debug("Sending to Message to DMaaP topic: " + topic); - publisher.close(); - } - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ "Error sending notification update: ", e); - } - if(pub != null){ - try { - pub.send( "pdpReturnMessage", message ); - LOGGER.debug("Sending to Message to tpoic" + topic); - pub.close(); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ "Error sending notification update" +e); - } - } - } - - private String processMessage(String msg) { - LOGGER.debug("notification message: " + msg); - String[] UID = msg.split("=")[1].split("\""); - - String returnTopic = topic + UID[0]; - if(msg.contains("Starting-Topic")){ - return null; - } - return returnTopic; - } - public static void setUpdate(String update) { - ManualNotificationUpdateThread.update = update; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Notification.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Notification.java deleted file mode 100644 index c9b510ec3..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Notification.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.notifications; - -import java.util.Collection; - -import org.openecomp.policy.api.NotificationType; - -/** - * Notification is the POJO which will be used to send the Notifications to the Server. - * Notification must contain the Removal and Updated policies. - * - * @version 0.2 - * - */ -public class Notification { - private Collection removedPolicies = null; - private Collection loadedPolicies = null; - private NotificationType notificationType= null; - - public Collection getRemovedPolicies() { - return removedPolicies; - } - - public void setRemovedPolicies(Collection removedPolicies) { - this.removedPolicies = removedPolicies; - } - - public Collection getLoadedPolicies() { - return loadedPolicies; - } - - public void setLoadedPolicies(Collection loadedPolicies) { - this.loadedPolicies = loadedPolicies; - } - - public NotificationType getNotificationType() { - return notificationType; - } - - public void setNotificationType(NotificationType notificationType){ - this.notificationType= notificationType; - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationController.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationController.java deleted file mode 100644 index 57678461d..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationController.java +++ /dev/null @@ -1,415 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.notifications; - -import java.io.File; -import java.io.FileFilter; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.net.URLConnection; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.io.filefilter.WildcardFileFilter; -import org.openecomp.policy.api.NotificationType; -import org.openecomp.policy.api.RemovedPolicy; -import org.openecomp.policy.api.UpdateType; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.PapUrlResolver; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; - -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.att.research.xacmlatt.pdp.policy.AllOf; -import com.att.research.xacmlatt.pdp.policy.AnyOf; -import com.att.research.xacmlatt.pdp.policy.Match; -import com.att.research.xacmlatt.pdp.policy.PolicyDef; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.ObjectWriter; - -/** - * NotificationController Checks for the Updated and Removed policies. It - * notifies the Server to send Notifications to the Client. - * - * @version 0.2 - * - */ -public class NotificationController { - private static final Logger LOGGER = FlexLogger.getLogger(NotificationController.class); - private static Notification record = new Notification(); - private PDPStatus oldStatus = null; - private Removed removed = null; - private Updated updated = null; - private ManualNotificationUpdateThread registerMaunualNotificationRunnable = null; - private Thread manualNotificationThread = null; - private boolean manualThreadStarted = false; - - private static String notificationJSON = null; - private static String propNotificationType = null; - private static String pdpURL = null; - private static Boolean notificationFlag = false; - - public void check(PDPStatus newStatus,Map policyContainer) { - boolean updated = false; - boolean removed = false; - Notification notification = new Notification(); - HashSet removedPolicies = new HashSet<>(); - HashSet updatedPolicies = new HashSet<>(); - - if (oldStatus == null) { - oldStatus = newStatus; - } - // Debugging purpose only. - LOGGER.debug("old config Status :" + oldStatus.getStatus()); - LOGGER.debug("new config Status :" + newStatus.getStatus()); - - // Depending on the above condition taking the Change as an Update. - if (oldStatus.getStatus().toString() != newStatus.getStatus().toString()) { - LOGGER.info("There is an Update to the PDP"); - LOGGER.debug(oldStatus.getLoadedPolicies()); - LOGGER.debug(newStatus.getLoadedPolicies()); - // Check if there is an Update/additions in the policy. - for (PDPPolicy newPolicy : newStatus.getLoadedPolicies()) { - boolean change = true; - for (PDPPolicy oldPolicy : oldStatus.getLoadedPolicies()) { - // Check if there are same policies. - if (oldPolicy.getId().equals(newPolicy.getId())) { - // Check if they have same version. - if (oldPolicy.getVersion().equals(newPolicy.getVersion())) { - change = false; - } - } - } - // if there is a change Send the notifications to the Client. - if (change) { - sendUpdate(newPolicy, policyContainer); - updated = true; - updatedPolicies.add(this.updated); - } - } - // Check if there is any removal of policy. - for (PDPPolicy oldPolicy : oldStatus.getLoadedPolicies()) { - boolean change = true; - for (PDPPolicy newPolicy : newStatus.getLoadedPolicies()) { - // Check if there are same policies. - if (oldPolicy.getId().equals(newPolicy.getId())) { - // Check if they have same version. - if (oldPolicy.getVersion().equals(newPolicy.getVersion())) { - change = false; - } - } - } - // if there is a change Send the notifications to the Client. - if (change) { - sendremove(oldPolicy); - removed = true; - removedPolicies.add(this.removed); - } - } - } - // At the end the oldStatus must be updated with the newStatus. - oldStatus = newStatus; - // Sending Notification to the Server to pass over to the clients - if (updated || removed) { - // Call the Notification Server.. - notification.setRemovedPolicies(removedPolicies); - notification.setLoadedPolicies(updatedPolicies); - notification = setUpdateTypes(updated, removed, notification); - ObjectWriter om = new ObjectMapper().writer(); - try { - notificationJSON = om.writeValueAsString(notification); - LOGGER.info(notificationJSON); - // NotificationServer Method here. - propNotificationType = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TYPE); - pdpURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID); - if (("ueb".equals(propNotificationType)||"dmaap".equals(propNotificationType)) && !manualThreadStarted) { - LOGGER.debug("Starting Thread to accept UEB or DMAAP notfications."); - this.registerMaunualNotificationRunnable = new ManualNotificationUpdateThread(); - this.manualNotificationThread = new Thread(this.registerMaunualNotificationRunnable); - this.manualNotificationThread.start(); - manualThreadStarted = true; - } - String notificationJSON= null; - notificationFlag = true; - try{ - notificationJSON= record(notification); - }catch(Exception e){ - LOGGER.error(e); - } - NotificationServer.setUpdate(notificationJSON); - ManualNotificationUpdateThread.setUpdate(notificationJSON); - } catch (JsonProcessingException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() +e); - } - } - } - - public static void sendNotification(){ - if(notificationFlag){ - try { - NotificationServer.sendNotification(notificationJSON, propNotificationType, pdpURL); - } catch (Exception e) { - LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "+ e.getMessage() + e); - } - notificationFlag = false; - } - } - - private void sendremove(PDPPolicy oldPolicy) { - removed = new Removed(); - // Want to know what is removed ? - LOGGER.info("Policy removed: " + oldPolicy.getId()+ " with version number: " + oldPolicy.getVersion()); - removed.setPolicyName(oldPolicy.getId()); - removed.setVersionNo(oldPolicy.getVersion()); - removeFile(oldPolicy); - } - - private void sendUpdate(PDPPolicy newPolicy,Map policyContainer) { - updated = new Updated(); - // Want to know what is new ? - LOGGER.info("The new Policy is: " + newPolicy.getId()); - LOGGER.info("The version no. is: " + newPolicy.getVersion()); - updated.setPolicyName(newPolicy.getId()); - updated.setVersionNo(newPolicy.getVersion()); - updated.setUpdateType(UpdateType.NEW); - // If the policy is of Config type then retrieve its matches. - if (newPolicy.getName().contains(".Config_")) { - // Take a Configuration copy to PDP webapps. - final String urlStart = "attributeId=URLID,expression"; - final String urlEnd = "}}},{"; - String policy = policyContainer.get(newPolicy.getId()).toString(); - if(policy.contains(urlStart)){ - String urlFinePartOne = policy.substring(policy.indexOf(urlStart)+urlStart.length()); - String urlFinePart = urlFinePartOne.substring(0,urlFinePartOne.indexOf(urlEnd)); - String urlString = urlFinePart.substring(urlFinePart.indexOf("value=$URL")+6); - callPap(urlString, "Config"); - } - Iterator anyOfs = policyContainer.get(newPolicy.getId()).getTarget().getAnyOfs(); - while (anyOfs.hasNext()) { - AnyOf anyOf = anyOfs.next(); - Iterator allOfs = anyOf.getAllOfs(); - while (allOfs.hasNext()) { - AllOf allOf = allOfs.next(); - Iterator matches = allOf.getMatches(); - HashMap matchValues = new HashMap<>(); - while (matches.hasNext()) { - Match match = matches.next(); - LOGGER.info("Attribute Value is: "+ match.getAttributeValue().getValue().toString()); - String[] result = match.getAttributeRetrievalBase().toString().split("attributeId="); - result[1] = result[1].replaceAll("}", ""); - if (!result[1].equals("urn:oasis:names:tc:xacml:1.0:subject:subject-id")) { - LOGGER.info("Attribute id is: " + result[1]); - } - matchValues.put(result[1], match.getAttributeValue().getValue().toString()); - LOGGER.info("Match is : "+ result[1]+ " , " + match.getAttributeValue().getValue().toString()); - } - updated.setMatches(matchValues); - } - } - }else if(newPolicy.getName().contains(".Action_")){ - // Take Configuration copy to PDP Webapps. - // Action policies have .json as extension. - String urlString = "$URL/Action/" + newPolicy.getId().substring(0, newPolicy.getId().lastIndexOf(".")) + ".json"; - callPap(urlString, "Action"); - } - } - - // Adding this for Recording the changes to serve Polling requests.. - private static String record(Notification notification) throws Exception { - // Initialization with updates. - if (record.getRemovedPolicies() == null || record.getLoadedPolicies() == null) { - record.setRemovedPolicies(notification.getRemovedPolicies()); - record.setLoadedPolicies(notification.getLoadedPolicies()); - } else { - // Check if there is anything new and update the record.. - if (record.getLoadedPolicies() != null || record.getRemovedPolicies() != null) { - HashSet removedPolicies = (HashSet) record.getRemovedPolicies(); - HashSet updatedPolicies = (HashSet) record.getLoadedPolicies(); - - // Checking with New updated policies. - if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) { - for (Updated newUpdatedPolicy : notification.getLoadedPolicies()) { - // If it was removed earlier then we need to remove from our record - Iterator oldRemovedPolicy = removedPolicies.iterator(); - while (oldRemovedPolicy.hasNext()) { - Removed policy = oldRemovedPolicy.next(); - if (newUpdatedPolicy.getPolicyName().equals(policy.getPolicyName())) { - if (newUpdatedPolicy.getVersionNo().equals(policy.getVersionNo())) { - oldRemovedPolicy.remove(); - } - } - } - // If it was previously updated need to Overwrite it to the record. - Iterator oldUpdatedPolicy = updatedPolicies.iterator(); - while (oldUpdatedPolicy.hasNext()) { - Updated policy = oldUpdatedPolicy.next(); - if (newUpdatedPolicy.getPolicyName().equals(policy.getPolicyName())) { - if (newUpdatedPolicy.getVersionNo().equals(policy.getVersionNo())) { - oldUpdatedPolicy.remove(); - } - } - } - updatedPolicies.add(newUpdatedPolicy); - } - } - // Checking with New Removed policies. - if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) { - for (Removed newRemovedPolicy : notification.getRemovedPolicies()) { - // If it was previously removed Overwrite it to the record. - Iterator oldRemovedPolicy = removedPolicies.iterator(); - while (oldRemovedPolicy.hasNext()) { - Removed policy = oldRemovedPolicy.next(); - if (newRemovedPolicy.getPolicyName().equals(policy.getPolicyName())) { - if (newRemovedPolicy.getVersionNo().equals(policy.getVersionNo())) { - oldRemovedPolicy.remove(); - } - } - } - // If it was added earlier then we need to remove from our record. - Iterator oldUpdatedPolicy = updatedPolicies.iterator(); - while (oldUpdatedPolicy.hasNext()) { - Updated policy = oldUpdatedPolicy.next(); - if (newRemovedPolicy.getPolicyName().equals(policy.getPolicyName())) { - if (newRemovedPolicy.getVersionNo().equals(policy.getVersionNo())) { - oldUpdatedPolicy.remove(); - } - } - } - removedPolicies.add(newRemovedPolicy); - } - } - record.setRemovedPolicies(removedPolicies); - record.setLoadedPolicies(updatedPolicies); - } - } - // Send the Result to the caller. - ObjectWriter om = new ObjectMapper().writer(); - String json = null; - try { - json = om.writeValueAsString(record); - } catch (JsonProcessingException e) { - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e); - } - LOGGER.info(json); - return json; - } - - private static Notification setUpdateTypes(boolean updated, boolean removed, Notification notification) { - if(notification!=null){ - if(updated && removed){ - notification.setNotificationType(NotificationType.BOTH); - if(notification.getLoadedPolicies()!=null){ - HashSet updatedPolicies = new HashSet<>(); - for(Updated oldUpdatedPolicy: notification.getLoadedPolicies()){ - Updated updatePolicy = oldUpdatedPolicy; - if(notification.getRemovedPolicies()!=null){ - for(RemovedPolicy removedPolicy: notification.getRemovedPolicies()){ - String regex = ".(\\d)*.xml"; - if(removedPolicy.getPolicyName().replaceAll(regex, "").equals(oldUpdatedPolicy.getPolicyName().replaceAll(regex, ""))){ - updatePolicy.setUpdateType(UpdateType.UPDATE); - break; - } - } - } - updatedPolicies.add(updatePolicy); - } - notification.setLoadedPolicies(updatedPolicies); - } - }else if(updated){ - notification.setNotificationType(NotificationType.UPDATE); - }else if(removed){ - notification.setNotificationType(NotificationType.REMOVE); - } - } - return notification; - } - - private void removeFile(PDPPolicy oldPolicy) { - try{ - Path removedPolicyFile = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_CONFIG)+File.separator+oldPolicy.getId()); - Files.deleteIfExists(removedPolicyFile); - boolean delete=false; - File dir= null; - if(oldPolicy.getName().startsWith("Config")){ - delete = true; - dir = new File(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)+File.separator+"Config"); - }else if(oldPolicy.getName().startsWith("Action")){ - delete = true; - dir = new File(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)+File.separator+"Action"); - } - if(delete){ - FileFilter fileFilter = new WildcardFileFilter(oldPolicy.getId().substring(0, oldPolicy.getId().lastIndexOf("."))+".*"); - File[] configFile = dir.listFiles(fileFilter); - if(configFile.length==1){ - Files.deleteIfExists(configFile[0].toPath()); - } - } - }catch(Exception e){ - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Couldn't remove the policy/config file " + oldPolicy.getName() + e); - } - } - - private void callPap(String urlString, String type) { - Path configLocation = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)+File.separator+type); - if(Files.notExists(configLocation)){ - try { - Files.createDirectories(configLocation); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW +"Failed to create config directory: " + configLocation.toAbsolutePath().toString(), e); - } - } - PapUrlResolver papUrls = PapUrlResolver.getInstance(); - while(papUrls.hasMoreUrls()){ - String papPath = papUrls.getUrl(); - papPath = papPath.substring(0, papPath.lastIndexOf("/pap")); - String papAddress= urlString.replace("$URL", papPath); - String fileName = papAddress.substring(papAddress.lastIndexOf("/")+1); - String fileLocation = configLocation.toString() + File.separator + fileName; - try { - URL papURL = new URL(papAddress); - LOGGER.info("Calling " +papAddress + " for Configuration Copy."); - URLConnection urlConnection = papURL.openConnection(); - File file= new File(fileLocation); - try (InputStream is = urlConnection.getInputStream(); - OutputStream os = new FileOutputStream(file)) { - IOUtils.copy(is, os); - break; - } - } catch (Exception e) { - LOGGER.error(e + e.getMessage()); - } - papUrls.getNext(); - } - } -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java deleted file mode 100644 index 9bd2e1f20..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/NotificationServer.java +++ /dev/null @@ -1,224 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.notifications; - -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.security.GeneralSecurityException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.TimeUnit; - -import javax.websocket.OnClose; -import javax.websocket.OnError; -import javax.websocket.OnMessage; -import javax.websocket.OnOpen; -import javax.websocket.Session; -import javax.websocket.server.ServerEndpoint; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.pdp.rest.api.services.NotificationService; -import org.openecomp.policy.rest.XACMLRestProperties; -import org.openecomp.policy.utils.BusPublisher; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; - -import com.att.nsa.cambria.client.CambriaBatchingPublisher; -import com.att.nsa.cambria.client.CambriaClientBuilders; -import com.att.research.xacml.util.XACMLProperties; - - -/** - * The NotificationServer sends the Server Notifications to the Clients once there is any Event. - * WebSockets is being used as a medium for sending Notifications. - * UEB is being used as a medium for sending Notifications. - * DMAAP is being used as a medium for sending Notifications. - * - * @version 0.2 - * - **/ -@ServerEndpoint(value = "/notifications") -public class NotificationServer { - private static final Logger LOGGER = FlexLogger.getLogger(NotificationServer.class); - private static Queue queue = new ConcurrentLinkedQueue<>(); - private static String update = null; - private static String hosts = null; - private static URL aURL = null; - - @OnOpen - public void openConnection(Session session) { - LOGGER.info("Session Connected: " + session.getId()); - queue.add(session); - } - - @OnClose - public void closeConnection(Session session) { - queue.remove(session); - } - - @OnError - public void error(Session session, Throwable t) { - queue.remove(session); - LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Session Error for : " + session.getId() + " Error: " + t.getMessage()); - - } - - @OnMessage - public void Message(String message, Session session) { - - if(message.equalsIgnoreCase("Manual")) { - try { - session.getBasicRemote().sendText(update); - session.close(); - } catch (IOException e) { - LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "+ e.getMessage() + e); - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending Message update"); - } - } - } - - public static void sendNotification(String notification, String propNotificationType, String pdpURL) throws Exception { - - LOGGER.debug("Notification set to " + propNotificationType); - if (propNotificationType.equals("ueb")){ - - String topic = null; - try { - aURL = new URL(pdpURL); - topic = aURL.getHost() + aURL.getPort(); - } catch (MalformedURLException e1) { - pdpURL = pdpURL.replace("/", ""); - topic = pdpURL.replace(":", ""); - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in parsing out pdpURL for UEB notfication "); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e1, "Error in parsing out pdpURL for UEB notfication "); - } - hosts = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); - String apiKey = XACMLProperties.getProperty(XACMLRestProperties.PROP_UEB_API_KEY); - String apiSecret = XACMLProperties.getProperty(XACMLRestProperties.PROP_UEB_API_SECRET); - - LOGGER.debug("Creating Publisher for host: " + hosts + " with topic: " + topic); - CambriaBatchingPublisher pub = null; - try { - if(hosts==null || topic==null || apiKey==null || apiSecret==null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file "); - throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file "); - } - - hosts.trim(); - topic.trim(); - apiKey.trim(); - apiSecret.trim(); - pub = new CambriaClientBuilders.PublisherBuilder () - .usingHosts ( hosts ) - .onTopic ( topic ) - .authenticatedBy ( apiKey, apiSecret ) - .build () - ; - - } catch (MalformedURLException e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error creating the UEB publisher" + e1.getMessage()); - } catch (GeneralSecurityException e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error creating the UEB publisher" + e1.getMessage() +e1); - } - if(pub != null){ - try { - pub.send( "MyPartitionKey", notification ); - } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending notification update" + e.getMessage() + e); - } - // close the publisher. The batching publisher does not send events - // immediately, so you MUST use close to send any remaining messages. - // You provide the amount of time you're willing to wait for the sends - // to succeed before giving up. If any messages are unsent after that time, - // they're returned to your app. You could, for example, persist to disk - // and try again later. - final List stuck = pub.close ( 20, TimeUnit.SECONDS ); - - if (!stuck.isEmpty()){ - LOGGER.error( stuck.size() + " messages unsent" ); - }else{ - LOGGER.info( "Clean exit; all messages sent: " + notification ); - } - } - } else if (propNotificationType.equals("dmaap")) { - - // Setting up the Publisher for DMaaP MR - String dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); - String topic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC); - String aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN"); - String aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD"); - - try { - if(dmaapServers==null || topic==null){ - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); - throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); - } - - dmaapServers.trim(); - topic.trim(); - aafLogin.trim(); - aafPassword.trim(); - - List dmaapList = null; - if(dmaapServers.contains(",")) { - dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*"))); - } else { - dmaapList = new ArrayList<>(); - dmaapList.add(dmaapServers); - } - - BusPublisher publisher = - new BusPublisher.DmaapPublisherWrapper(dmaapList, - topic, - aafLogin, - aafPassword); - - // Sending notification through DMaaP Message Router - publisher.send( "MyPartitionKey", notification); - LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + topic); - publisher.close(); - - } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending notification update" + e.getMessage() + e); - } - } - - for(Session session: queue) { - try { - session.getBasicRemote().sendText(notification); - } catch (IOException e) { - LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "+ e.getMessage() + e); - } - } - NotificationService.sendNotification(notification); - } - - public static void setUpdate(String update) { - NotificationServer.update = update; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Removed.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Removed.java deleted file mode 100644 index 151b40125..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Removed.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.notifications; - -import org.openecomp.policy.api.RemovedPolicy; - - -/** - * Removal is the POJO for removal updates of the Policy. - * It must have the Policy removed and its Version number. - * - * @version 0.2 - * - */ -public class Removed implements RemovedPolicy{ - - private String policyName = null; - private String versionNo = null; - - public String getVersionNo() { - return versionNo; - } - - public void setVersionNo(String versionNo) { - this.versionNo = versionNo; - } - - public String getPolicyName() { - return policyName; - } - - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Updated.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Updated.java deleted file mode 100644 index f0d9aa38d..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/Updated.java +++ /dev/null @@ -1,74 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.notifications; - -import java.util.HashMap; - -import org.openecomp.policy.api.LoadedPolicy; -import org.openecomp.policy.api.UpdateType; - -/** - * Updated is the POJO which consists of any new or Updated Policy information. - * It must hold the Policy Name, version Number, Matches. - * - * @version 0.2 - * - */ -public class Updated implements LoadedPolicy{ - private String policyName = null; - private String versionNo = null; - private HashMap matches = null; - private UpdateType updateType = null; - - public String getPolicyName() { - return policyName; - } - - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - - public String getVersionNo() { - return versionNo; - } - - public void setVersionNo(String versionNo) { - this.versionNo = versionNo; - } - - public HashMap getMatches() { - return matches; - } - - public void setMatches(HashMap matches) { - this.matches = matches; - } - - @Override - public UpdateType getUpdateType() { - return this.updateType; - } - - public void setUpdateType(UpdateType updateType){ - this.updateType = updateType; - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/package-info.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/package-info.java deleted file mode 100644 index 7d3995ec6..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/notifications/package-info.java +++ /dev/null @@ -1,28 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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========================================================= - */ - -/** - * This is the new Addition to the PDP Server added for sending Notifications to the Clients - * about the policy Updates/ Removals. - * - * @version 0.1 - * - */ -package org.openecomp.policy.pdp.rest.notifications; diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/AuthenticationService.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/AuthenticationService.java deleted file mode 100644 index 5a6258032..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/AuthenticationService.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.restAuth; - -import java.util.Base64; -import java.util.StringTokenizer; - -import org.openecomp.policy.rest.XACMLRestProperties; - -import com.att.research.xacml.util.XACMLProperties; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - -public class AuthenticationService { - private String pdpID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_USERID); - private String pdpPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_PASS); - - public boolean authenticate(String authCredentials) { - - if (null == authCredentials) - return false; - // header value format will be "Basic encodedstring" for Basic authentication. - final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", ""); - String usernameAndPassword = null; - try { - byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword); - usernameAndPassword = new String(decodedBytes, "UTF-8"); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); - return false; - } - try { - final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); - final String username = tokenizer.nextToken(); - final String password = tokenizer.nextToken(); - return pdpID.equals(username) && pdpPass.equals(password); - }catch (Exception e){ - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); - return false; - } - } - -} diff --git a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java b/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java deleted file mode 100644 index 4bc14df02..000000000 --- a/ECOMP-PDP-REST/src/main/java/org/openecomp/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java +++ /dev/null @@ -1,117 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.restAuth; - -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.annotation.WebFilter; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.policy.pdp.rest.config.PDPApiAuth; - -/** - * Servlet Filter implementation class PDPAuthenticationFilter - */ -@WebFilter("/*") -public class PDPAuthenticationFilter implements Filter { - - public static final String AUTHENTICATION_HEADER = "Authorization"; - public static final String ENVIRONMENT_HEADER = "Environment"; - - @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain filter) throws IOException, ServletException { - if (request instanceof HttpServletRequest) { - HttpServletRequest httpServletRequest = (HttpServletRequest) request; - String environment = httpServletRequest.getHeader(ENVIRONMENT_HEADER); - String authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER); - String path = ((HttpServletRequest) request).getRequestURI(); - // better injected - AuthenticationService authenticationService = new AuthenticationService(); - - boolean authenticationStatus = authenticationService.authenticate(authCredentials); - - if (authenticationStatus) { - if (check(path)) { - // New API request. - path = path.substring(path.substring(1).indexOf("/") + 1); - if (environment == null) { - // Allow Old clients. - if(!path.contains("/api/")){ - request.getRequestDispatcher("/api/" + path).forward(request,response); - }else{ - request.getRequestDispatcher(path).forward(request,response); - } - } else if (environment.equalsIgnoreCase(PDPApiAuth.getEnvironment())) { - // Validated new Clients. - if(!path.contains("/api/")){ - request.getRequestDispatcher("/api/" + path).forward(request,response); - }else{ - request.getRequestDispatcher(path).forward(request,response); - } - } else if(response instanceof HttpServletResponse) { - HttpServletResponse httpServletResponse = (HttpServletResponse) response; - httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } - } else { - filter.doFilter(request, response); - } - } else if (path.contains("swagger") || path.contains("api-docs") - || path.contains("configuration") || path.contains("count")) { - path = path.substring(path.substring(1).indexOf("/") + 2); - request.getRequestDispatcher("/api/" + path).forward(request,response); - } else if(path.contains("notifications")){ - filter.doFilter(request, response); - } else { - if (response instanceof HttpServletResponse) { - HttpServletResponse httpServletResponse = (HttpServletResponse) response; - httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } - } - } - } - - private boolean check(String path) { - if(path.endsWith("/pdp/")|| path.endsWith("/pdp")|| path.endsWith("/test")){ - return false; - }else{ - return true; - } - } - - @Override - public void destroy() { - // Do nothing. - } - - @Override - public void init(FilterConfig arg0) throws ServletException { - // Do nothing. - } - -} diff --git a/ECOMP-PDP-REST/src/main/resources/log4j.properties b/ECOMP-PDP-REST/src/main/resources/log4j.properties deleted file mode 100644 index 3b31771c4..000000000 --- a/ECOMP-PDP-REST/src/main/resources/log4j.properties +++ /dev/null @@ -1,71 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP-REST -# ================================================================================ -# 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========================================================= -### - -# -# Use this properties for Deployments. -# -# -# Set root logger level to DEBUG and its only appender to FILE. -#log4j.rootLogger=DEBUG, FILE, CONSOLE -log4j.rootLogger=INFO, FILE - -# FILE appender -log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender -log4j.appender.FILE.File=${catalina.base}/logs/pdp-rest.log -log4j.appender.FILE.ImmediateFlush=true -log4j.appender.FILE.Threshold=debug -log4j.appender.FILE.append=true -log4j.appender.FILE.DatePattern='.'yyyy-MM-dd -log4j.appender.FILE.layout=org.apache.log4j.PatternLayout -log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss}{GMT+0}+00:00|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%l||%m%n - -# for Developments and Debugging -#log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender -#log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout -#log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n - -# -# This is specifically for Xacml request/response logging -# -log4j.logger.xacml.request=INFO, REQUEST_LOG - -log4j.appender.REQUEST_LOG=org.apache.log4j.DailyRollingFileAppender -log4j.appender.REQUEST_LOG.File=${catalina.base}/logs/pdp-rest-reqres.log -log4j.appender.REQUEST_LOG.ImmediateFlush=true -log4j.appender.REQUEST_LOG.Threshold=debug -log4j.appender.REQUEST_LOG.append=true -log4j.appender.REQUEST_LOG.DatePattern='.'yyyy-MM-dd - -log4j.appender.REQUEST_LOG.layout=org.apache.log4j.PatternLayout -log4j.appender.REQUEST_LOG.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} %m%n - -# -# audit (transaction) logging -# -log4j.logger.auditLogger=INFO,AUDIT_LOG -log4j.additivity.auditLogger=false - -log4j.appender.AUDIT_LOG=org.apache.log4j.DailyRollingFileAppender -log4j.appender.AUDIT_LOG.File=${catalina.base}/logs/audit.log -log4j.appender.AUDIT_LOG.Append=true -log4j.appender.AUDIT_LOG.DatePattern='.'yyyy-MM-dd -log4j.appender.AUDIT_LOG.threshold=INFO -log4j.appender.AUDIT_LOG.layout=org.apache.log4j.EnhancedPatternLayout -log4j.appender.AUDIT_LOG.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss}{GMT+0}+00:00|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%X{className}|%X{timer}|%m%n diff --git a/ECOMP-PDP-REST/src/main/resources/logback.xml b/ECOMP-PDP-REST/src/main/resources/logback.xml deleted file mode 100644 index df4d33f32..000000000 --- a/ECOMP-PDP-REST/src/main/resources/logback.xml +++ /dev/null @@ -1,253 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --> - - - - - - - - - - - - - - - - - - - - ${defaultPattern} - - - - - - - - - - - - - ${logDirectory}/${auditLogName}.log - - ${logDirectory}/${auditLogName}.%i.log.zip - - 1 - 9 - - - 5MB - - - ${defaultAuditPattern} - - - - - 256 - - - - - - - - ${logDirectory}/${metricsLogName}.log - - ${logDirectory}/${metricsLogName}.%i.log.zip - - 1 - 9 - - - 5MB - - - - ${defaultMetricPattern} - - - - - 256 - - - - - - - - ${logDirectory}/${errorLogName}.log - - ${logDirectory}/${errorLogName}.%i.log.zip - - 1 - 9 - - - ERROR - - - 5MB - - - ${defaultErrorPattern} - - - - - 256 - - - - - - - ${debugLogDirectory}/${debugLogName}.log - - ${debugLogDirectory}/${debugLogName}.%i.log.zip - - 1 - 9 - - - DEBUG - - - 5MB - - - ${debugLoggerPattern} - - - - - 256 - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/PapUrlResolverTest.java b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/PapUrlResolverTest.java deleted file mode 100644 index 1811d8912..000000000 --- a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/PapUrlResolverTest.java +++ /dev/null @@ -1,224 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Properties; - -import org.junit.Assert; -import org.junit.Test; -import org.openecomp.policy.rest.XACMLRestProperties; - -public class PapUrlResolverTest { - - - @Test - public void testPropertyModifications(){ - DateFormat df = new SimpleDateFormat(); - //first sort order - String urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; - String failed = "-1,-1,-1,-1"; - String succeeded = "-1,-1,-1,-1"; - PapUrlResolver rs = PapUrlResolver.getInstance(urls, failed, succeeded); - Assert.assertEquals(rs.getProperties().getProperty(XACMLRestProperties.PROP_PAP_URLS),urls); - - rs.failed(); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - rs.succeeded(); - Assert.assertFalse(rs.hasMoreUrls()); - Properties prop = rs.getProperties(); - Assert.assertEquals(df.format(new Date())+",-1,-1,-1",prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS)); - Assert.assertEquals("-1,"+df.format(new Date())+",-1,-1",prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS)); - - failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); - succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); - rs = PapUrlResolver.getInstance(urls, failed, succeeded); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://two.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://three.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://four.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://one.localhost.com", rs.getUrl()); - rs.succeeded(); - rs.getNext(); - Assert.assertFalse(rs.hasMoreUrls()); - prop = rs.getProperties(); - Assert.assertEquals("-1,-1,-1,-1",prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS)); - - failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); - succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); - rs = PapUrlResolver.getInstance(urls, failed, succeeded); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://one.localhost.com", rs.getUrl()); - rs.succeeded(); - rs.getNext(); - Assert.assertFalse(rs.hasMoreUrls()); - prop = rs.getProperties(); - failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); - succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); - rs = PapUrlResolver.getInstance(urls, failed, succeeded); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://one.localhost.com", rs.getUrl()); - rs.succeeded(); - rs.getNext(); - Assert.assertFalse(rs.hasMoreUrls()); - prop = rs.getProperties(); - failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); - succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); - rs = PapUrlResolver.getInstance(urls, failed, succeeded); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://one.localhost.com", rs.getUrl()); - rs.succeeded(); - rs.getNext(); - Assert.assertFalse(rs.hasMoreUrls()); - - - prop = rs.getProperties(); - succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); - } - @SuppressWarnings("unused") - @Test - public void testModifyUrl(){ - String newUrl = PapUrlResolver.modifyUrl("http://mypap1.com/pap?id=987654", "http://mypap2.com:45/pap/"); - int u = 8; - } - - @Test - public void testSorts(){ - long currentTime = new Date().getTime(); - DateFormat df = new SimpleDateFormat(); - //first sort order - String urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; - String failed = df.format(new Date(currentTime-3600000))+",-1,-1,"+df.format(new Date(currentTime-3200000)); - String succeeded = "-1,8/13/15 5:41 PM,8/13/15 4:41 PM,-1"; - PapUrlResolver rs = PapUrlResolver.getInstance(urls, failed, succeeded); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://two.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://three.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://one.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://four.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertFalse(rs.hasMoreUrls()); - - urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; - failed = "-1,-1,-1,-1"; - succeeded = "-1,"+df.format(new Date(currentTime-3600000))+","+df.format(new Date(currentTime-6600000))+",-1"; - rs = PapUrlResolver.getInstance(urls, failed, succeeded); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://one.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://two.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://three.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://four.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertFalse(rs.hasMoreUrls()); - - urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; - failed = "-1,-1,-1,-1"; - succeeded = "-1,-1,-1,-1"; - rs = PapUrlResolver.getInstance(urls, failed, succeeded); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://one.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://two.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://three.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://four.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertFalse(rs.hasMoreUrls()); - - urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; - failed = df.format(new Date(currentTime-3900000))+","+df.format(new Date(currentTime-5600000))+","+df.format(new Date(currentTime-4600000))+","+df.format(new Date(currentTime-3600000)); - succeeded = "-1,-1,-1,-1"; - rs = PapUrlResolver.getInstance(urls, failed, succeeded); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://two.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://three.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://one.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://four.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertFalse(rs.hasMoreUrls()); - - urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; - failed = df.format(new Date(currentTime-(3600000*4)))+",-1,-1,-1"; - succeeded = "-1,-1,-1,-1"; - rs = PapUrlResolver.getInstance(urls, failed, succeeded); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://two.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://three.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://four.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://one.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertFalse(rs.hasMoreUrls()); - - urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; - failed = df.format(new Date(currentTime-(3600000*6)))+",-1,-1,-1"; - succeeded = "-1,-1,-1,-1"; - rs = PapUrlResolver.getInstance(urls, failed, succeeded); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://one.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://two.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://three.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertTrue(rs.hasMoreUrls()); - Assert.assertEquals("http://four.localhost.com", rs.getUrl()); - rs.getNext(); - Assert.assertFalse(rs.hasMoreUrls()); - } -} diff --git a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/XACMLPdpServletTest.java b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/XACMLPdpServletTest.java deleted file mode 100644 index e0d2f18c1..000000000 --- a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/XACMLPdpServletTest.java +++ /dev/null @@ -1,364 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import java.util.Random; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletInputStream; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.junit.Before; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.openecomp.policy.common.im.AdministrativeStateException; -import org.openecomp.policy.common.im.IntegrityMonitor; -import org.openecomp.policy.common.im.StandbyStatusException; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.mock.web.MockServletConfig; - -import com.mockrunner.mock.web.MockServletInputStream; - -import junit.framework.TestCase; - -@RunWith(PowerMockRunner.class) -@PrepareForTest(IntegrityMonitor.class) // so PowerMock can mock static method of IntegrityMonitor -public class XACMLPdpServletTest extends TestCase{ - private static Logger LOGGER = FlexLogger.getLogger(XACMLPdpServletTest.class); - - private List headers = new ArrayList<>(); - - private HttpServletRequest httpServletRequest; - private HttpServletResponse httpServletResponse; - private ServletOutputStream mockOutput; - private ServletInputStream mockInput; - private ServletConfig servletConfig; - private XACMLPdpServlet pdpServlet; - private IntegrityMonitor im; - - - - @Before - public void setUp(){ - httpServletRequest = Mockito.mock(HttpServletRequest.class); - Mockito.when(httpServletRequest.getMethod()).thenReturn("POST"); - Mockito.when(httpServletRequest.getHeaderNames()).thenReturn(Collections.enumeration(headers)); - Mockito.when(httpServletRequest.getAttributeNames()).thenReturn(Collections.enumeration(headers)); - - - mockOutput = Mockito.mock(ServletOutputStream.class); - - httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - - try { - Mockito.when(httpServletResponse.getOutputStream()).thenReturn(mockOutput); - } catch (IOException e) { - fail(); - } - - servletConfig = Mockito.mock(MockServletConfig.class); - //servletConfig - Mockito.when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers)); - pdpServlet = new XACMLPdpServlet(); - - Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.pdp.properties"); - - System.setProperty("xacml.properties", "xacml.pdp.properties"); - System.setProperty("xacml.rest.pdp.config", "config_testing"); - System.setProperty("xacml.rest.pdp.webapps", "/webapps"); - System.setProperty("xacml.rootPolicies", "test_PolicyEngine.xml"); - System.setProperty("xacml.referencedPolicies", "test_PolicyEngine.xml"); - System.setProperty("test_PolicyEngine.xml.file", "config_testing\\test_PolicyEngine.xml"); - System.setProperty("xacml.rest.pdp.register", "false"); - System.setProperty("com.sun.management.jmxremote.port", "9999"); - - im = Mockito.mock(IntegrityMonitor.class); - // Need PowerMockito for mocking static method getInstance(...) - PowerMockito.mockStatic(IntegrityMonitor.class); - try { - // when IntegrityMonitor.getInstance is called, return the mock object - PowerMockito.when(IntegrityMonitor.getInstance(Mockito.anyString(), Mockito.any(Properties.class))).thenReturn(im); - } catch (Exception e1) { - LOGGER.error("Exception Occured"+e1); - } - - try { - Mockito.doNothing().when(im).startTransaction(); - } catch (StandbyStatusException | AdministrativeStateException e) { - fail(); - } - Mockito.doNothing().when(im).endTransaction(); - } - - public void testInit(){ - LOGGER.info("XACMLPdpServletTest - testInit"); - try { - pdpServlet.init(servletConfig); - assertTrue(true); - } catch (Exception e) { - LOGGER.error("Exception Occured"+e); - fail(); - - } - - } - - public void testDoGetNoTypeError(){ - LOGGER.info("XACMLPdpServletTest - testDoGetNoTypeError"); - try{ - pdpServlet.init(servletConfig); - pdpServlet.doGet(httpServletRequest, httpServletResponse); - Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_BAD_REQUEST, "type not 'config' or 'hb'"); - assertTrue(true); - }catch(Exception e){ - System.out.println("Unexpected exception in testDoGetNoTypeError"); - LOGGER.error("Exception Occured"+e); - fail(); - } - } - - public void testDoGetConfigType(){ - LOGGER.info("XACMLPdpServletTest - testDoGetConfigType"); - Mockito.when(httpServletRequest.getParameter("type")).thenReturn("config"); - - try{ - pdpServlet.init(servletConfig); - pdpServlet.doGet(httpServletRequest, httpServletResponse); - Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); - assertTrue(true); - }catch (Exception e){ - System.out.println("Unexpected exception in testDoGetConfigType"); - LOGGER.error("Exception Occured"+e); - fail(); - } - - } - - - public void testDoGetTypeHb(){ - LOGGER.info("XACMLPdpServletTest - testDoGetTypeHb"); - try{ - Mockito.when(httpServletRequest.getParameter("type")).thenReturn("hb"); - pdpServlet.init(servletConfig); - pdpServlet.doGet(httpServletRequest, httpServletResponse); - Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_NO_CONTENT); - assertTrue(true); - }catch(Exception e){ - System.out.println("Unexpected exception in testDoGetTypeHb"); - LOGGER.error("Exception Occured"+e); - fail(); - } - } - public void testDoGetTypeStatus(){ - LOGGER.info("XACMLPdpServletTest - testDoGetTypeStatus"); - try{ - Mockito.when(httpServletRequest.getParameter("type")).thenReturn("Status"); - pdpServlet.init(servletConfig); - pdpServlet.doGet(httpServletRequest, httpServletResponse); - Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); - assertTrue(true); - }catch(Exception e){ - System.out.println("Unexpected exception in testDoGetTypeStatus"); - LOGGER.error("Exception Occured"+e); - fail(); - } - } - - public void testDoPost(){ - LOGGER.info("XACMLPdpServletTest - testDoPost"); - try{ - pdpServlet.init(servletConfig); - pdpServlet.doPost(httpServletRequest, httpServletResponse); - assertTrue(true); - }catch (Exception e){ - System.out.println("Unexpected exception in testDoPost"); - LOGGER.error("Exception Occured"+e); - fail(); - } - } - - public void testDoPostToLong(){ - LOGGER.info("XACMLPdpServletTest - testDoPostToLong"); - try{ - Mockito.when(httpServletRequest.getContentType()).thenReturn("stuff"); - Mockito.when(httpServletRequest.getContentLength()).thenReturn(32768); - - pdpServlet.init(servletConfig); - pdpServlet.doPost(httpServletRequest, httpServletResponse); - assertTrue(true); - }catch (Exception e){ - System.out.println("Unexpected exception in testDoPostToLong"); - LOGGER.error("Exception Occured"+e); - fail(); - } - } - - public void testDoPostContentLengthNegative(){ - LOGGER.info("XACMLPdpServletTest - testDoPostToLong"); - try{ - Mockito.when(httpServletRequest.getContentType()).thenReturn("stuff"); - Mockito.when(httpServletRequest.getContentLength()).thenReturn(-1); - - pdpServlet.init(servletConfig); - pdpServlet.doPost(httpServletRequest, httpServletResponse); - assertTrue(true); - }catch (Exception e){ - System.out.println("Unexpected exception in testDoPostContentLengthNegative"); - LOGGER.error("Exception Occured"+e); - fail(); - } - } - - public void testDoPostContentTypeNonValid(){ - LOGGER.info("XACMLPdpServletTest - testDoPostToLong"); - try{ - Mockito.when(httpServletRequest.getContentType()).thenReturn(";"); - Mockito.when(httpServletRequest.getContentLength()).thenReturn(30768); - - pdpServlet.init(servletConfig); - pdpServlet.doPost(httpServletRequest, httpServletResponse); - assertTrue(true); - }catch (Exception e){ - System.out.println("Unexpected exception in testDoPostContentTypeNonValid"); - LOGGER.error("Exception Occured"+e); - fail(); - } - } - - public void testDoPostContentTypeConfigurationError(){ - LOGGER.info("XACMLPdpServletTest - testDoPostToLong"); - try{ - Mockito.when(httpServletRequest.getContentType()).thenReturn("stuff"); - Mockito.when(httpServletRequest.getContentLength()).thenReturn(30768); - - pdpServlet.init(servletConfig); - pdpServlet.doPost(httpServletRequest, httpServletResponse); - assertTrue(true); - }catch (Exception e){ - System.out.println("Unexpected exception in testDoPostContentTypeConfigurationError"); - LOGGER.error("Exception Occured"+e); - fail(); - } - } - - public void testDoPutCacheEmpty(){ - LOGGER.info("XACMLPdpServletTest - testDoPutCacheEmpty"); - mockInput = Mockito.mock(ServletInputStream.class); - - try{ - Mockito.when(httpServletRequest.getParameter("cache")).thenReturn("cache"); - Mockito.when(httpServletRequest.getContentType()).thenReturn("text/x-java-properties"); - Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); - pdpServlet.init(servletConfig); - pdpServlet.doPut(httpServletRequest, httpServletResponse); - Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT must contain at least one property"); - assertTrue(true); - }catch (Exception e){ - System.out.println("Unexpected exception in testDoPutCacheEmpty"); - LOGGER.error("Exception Occured"+e); - fail(); - } - } - - public void testDoPutConfigPolicies(){ - LOGGER.info("XACMLPdpServletTest - testDoPutConfigPolicies"); - byte[] b = new byte[20]; - new Random().nextBytes(b); - - mockInput = new MockServletInputStream(b); - - try{ - Mockito.when(httpServletRequest.getParameter("cache")).thenReturn("policies"); - Mockito.when(httpServletRequest.getContentType()).thenReturn("text/x-java-properties"); - Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); - pdpServlet.init(servletConfig); - pdpServlet.doPut(httpServletRequest, httpServletResponse); - assertTrue(true); - }catch (Exception e){ - System.out.println("Unexpected exception in testDoPutConfigPolicies"); - LOGGER.error("Exception Occured"+e); - fail(); - } - } - - public void testDoPutToLong(){ - LOGGER.info("XACMLPdpServletTest - testDoPutToLong"); - try{ - Mockito.when(httpServletRequest.getParameter("cache")).thenReturn("policies"); - - Mockito.when(httpServletRequest.getContentType()).thenReturn("text/x-java-properties"); - Mockito.when(httpServletRequest.getContentLength()).thenReturn(1000000000); - - pdpServlet.init(servletConfig); - pdpServlet.doPut(httpServletRequest, httpServletResponse); - Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_BAD_REQUEST, "Content-Length larger than server will accept."); - assertTrue(true); - }catch (Exception e){ - System.out.println("Unexpected exception in testDoPutToLong"); - LOGGER.error("Exception Occured"+e); - fail(); - } - } - - public void testDoPutInvalidContentType(){ - LOGGER.info("XACMLPdpServletTest - testDoPutToLong"); - try{ - Mockito.when(httpServletRequest.getParameter("cache")).thenReturn("policies"); - - Mockito.when(httpServletRequest.getContentType()).thenReturn("text/json"); - Mockito.when(httpServletRequest.getContentLength()).thenReturn(32768); - - pdpServlet.init(servletConfig); - pdpServlet.doPut(httpServletRequest, httpServletResponse); - Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid cache: 'policies' or content-type: 'text/json'"); - assertTrue(true); - }catch (Exception e){ - System.out.println("Unexpected exception in testDoPutInvalidContentType"); - LOGGER.error("Exception Occured"+e); - fail(); - } - } - - public void testDestroy(){ - LOGGER.info("XACMLPdpServletTest - testDestroy"); - - try{ - pdpServlet.init(servletConfig); - pdpServlet.destroy(); - }catch(Exception e){ - System.out.println("Unexpected exception in testDestroy"); - LOGGER.error("Exception Occured"+e); - fail(); - } - } -} diff --git a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/services/PDPServicesTest.java b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/services/PDPServicesTest.java deleted file mode 100644 index fd20e3162..000000000 --- a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/services/PDPServicesTest.java +++ /dev/null @@ -1,194 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.services; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; -import java.util.Map.Entry; - -import javax.json.Json; -import javax.json.JsonArrayBuilder; -import javax.json.JsonObject; -import javax.json.JsonObjectBuilder; - -import org.junit.*; -import org.junit.runner.RunWith; - -import static org.junit.Assert.*; - -import org.openecomp.policy.api.DecisionRequestParameters; -import org.openecomp.policy.api.PolicyDecisionException; -import org.openecomp.policy.pdp.rest.api.models.PDPResponse; -import org.openecomp.policy.pdp.rest.config.PDPRestConfig; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {PDPRestConfig.class}) -@WebAppConfiguration -public class PDPServicesTest { - /** - * Run the PDPServices() constructor test. - * - * @generatedBy CodePro at 7/20/17 9:26 AM - */ - @Test - public void testPDPServices_1() - throws Exception { - PDPServices result = new PDPServices(); - assertNotNull(result); - // add additional test code here - } - - /** - * Run the Collection generateRequest(String,UUID,boolean,boolean) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 7/20/17 9:26 AM - */ - @Test - public void testGenerateRequest_1() - throws Exception { - DecisionRequestParameters pep = new DecisionRequestParameters(); - Map eventAttributes = new HashMap<>(); - eventAttributes.put("TEST", "test"); - pep.setECOMPComponentName("te123"); - pep.setDecisionAttributes(eventAttributes); - PDPServices fixture = new PDPServices(); - - //Failure Tests. - String jsonString = getModel(pep).toString(); - UUID requestID = UUID.randomUUID(); - - Collection result = fixture.generateRequest(jsonString, requestID, false, true); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.pdp.rest.api.services.PDPServices - assertNotNull(result); - - } - - private JsonObject getModel(DecisionRequestParameters pep) throws PolicyDecisionException{ - JsonArrayBuilder resourceArray = Json.createArrayBuilder(); - - Map decisionAttributes = pep.getDecisionAttributes(); - for (Entry key : decisionAttributes.entrySet()) { - JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); - if (key.getValue().matches("[0-9]+")) { - - if ((key.getKey().equals("ErrorCode")) || (key.getKey().equals("WorkStep"))) { - - resourceBuilder.add("Value", key.getValue()); - - } else { - - int val = Integer.parseInt(key.getValue()); - resourceBuilder.add("Value", val); - - } - - } else { - resourceBuilder.add("Value", key.getValue()); - } - resourceBuilder.add("AttributeId", key.getKey()); - resourceArray.add(resourceBuilder); - } - return Json.createObjectBuilder() - .add("Request", Json.createObjectBuilder() - .add("AccessSubject", Json.createObjectBuilder() - .add("Attribute", Json.createObjectBuilder() - .add("Value", pep.getECOMPComponentName()) - .add("AttributeId", "ECOMPName"))) - .add("Resource", Json.createObjectBuilder() - .add("Attribute", resourceArray)) - .add("Action", Json.createObjectBuilder() - .add("Attribute", Json.createObjectBuilder() - .add("Value", "DECIDE") - .add("AttributeId", "urn:oasis:names:tc:xacml:1.0:action:action-id")))) - .build(); - } - - /** - * Run the Collection generateRequest(String,UUID,boolean,boolean) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 7/20/17 9:26 AM - */ - @Test(expected = org.openecomp.policy.api.PolicyException.class) - public void testGenerateRequest_2() - throws Exception { - PDPServices fixture = new PDPServices(); - fixture.generateRequest("", UUID.randomUUID(), true, true); - String jsonString = ""; - UUID requestID = UUID.randomUUID(); - boolean unique = true; - boolean decide = true; - - Collection result = fixture.generateRequest(jsonString, requestID, unique, decide); - - // add additional test code here - assertNotNull(result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 7/20/17 9:26 AM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 7/20/17 9:26 AM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 7/20/17 9:26 AM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PDPServicesTest.class); - } -} \ No newline at end of file diff --git a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/NotificationAPITest.java b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/NotificationAPITest.java deleted file mode 100644 index 8d6cf8945..000000000 --- a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/NotificationAPITest.java +++ /dev/null @@ -1,87 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.test; - -import static org.awaitility.Awaitility.await; -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -import org.junit.Before; -import org.junit.Test; -import org.openecomp.policy.pdp.rest.api.services.NotificationService; -import org.openecomp.policy.pdp.rest.api.services.NotificationService.NotificationServiceType; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import org.springframework.http.HttpStatus; - -import com.att.research.xacml.util.XACMLProperties; - -public class NotificationAPITest { - - @Before - public void setup() throws IOException{ - // Fix properties for next test cases. - XACMLProperties.reloadProperties(); - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/pass.xacml.pdp.properties"); - XACMLProperties.getProperties(); - } - - @Test - public void testPropertyFailure() throws IOException{ - // Change properties and fail. - XACMLProperties.reloadProperties(); - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/fail.xacml.pdp.properties"); - XACMLProperties.getProperties(); - NotificationService notificationService = new NotificationService(null,null,null); - assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); - setup(); - } - - @Test - public void testFailureTopicName(){ - NotificationService notificationService = new NotificationService(null,null,null); - assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); - assertEquals(XACMLErrorConstants.ERROR_DATA_ISSUE + "org.openecomp.policy.api.PolicyException: Notification Topic is null", notificationService.getResult()); - notificationService = new NotificationService(" ",null,null); - assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); - assertEquals(XACMLErrorConstants.ERROR_DATA_ISSUE + "org.openecomp.policy.api.PolicyException: Notification Topic is not valid. ", notificationService.getResult()); - } - - @Test - public void testFailureServiceType(){ - NotificationService notificationService = new NotificationService("test",null,null); - assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); - } - - @Test - public void threadTest() throws InterruptedException{ - NotificationService notificationSerivce = new NotificationService("test",null,NotificationServiceType.ADD); - assertEquals(HttpStatus.OK, notificationSerivce.getResponseCode()); - // Wait for thread to remove the Topic Entry. - await().atMost(Integer.toUnsignedLong(2500),TimeUnit.MILLISECONDS).until(()-> { - // Trying to remove again should fail - NotificationService nService = new NotificationService("test",null,NotificationServiceType.REMOVE); - return HttpStatus.BAD_REQUEST.equals(nService.getResponseCode()); - }); - // Coverage Tests, Call Notification Service. - NotificationService.sendNotification("test"); - } -} diff --git a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/PolicyEngineServicesTest.java b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/PolicyEngineServicesTest.java deleted file mode 100644 index eb514a8f5..000000000 --- a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/PolicyEngineServicesTest.java +++ /dev/null @@ -1,832 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.test; - -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; - -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.openecomp.policy.api.AttributeType; -import org.openecomp.policy.api.ConfigRequestParameters; -import org.openecomp.policy.api.DecisionRequestParameters; -import org.openecomp.policy.api.DeletePolicyCondition; -import org.openecomp.policy.api.DeletePolicyParameters; -import org.openecomp.policy.api.DictionaryParameters; -import org.openecomp.policy.api.DictionaryType; -import org.openecomp.policy.api.EventRequestParameters; -import org.openecomp.policy.api.PolicyClass; -import org.openecomp.policy.api.PolicyConfigType; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.api.PolicyType; -import org.openecomp.policy.api.PushPolicyParameters; -import org.openecomp.policy.pdp.rest.XACMLPdpServlet; -import org.openecomp.policy.pdp.rest.api.models.ConfigFirewallPolicyAPIRequest; -import org.openecomp.policy.pdp.rest.api.models.ConfigNameRequest; -import org.openecomp.policy.pdp.rest.api.models.ConfigPolicyAPIRequest; -import org.openecomp.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl; -import org.openecomp.policy.pdp.rest.config.PDPRestConfig; -import org.openecomp.policy.utils.PolicyUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.web.context.WebApplicationContext; - -import com.att.research.xacml.util.XACMLProperties; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {PDPRestConfig.class}) -@WebAppConfiguration -public class PolicyEngineServicesTest { - private static final String CLIENTAUTHHEADER = "ClientAuth"; - private static final String UUIDHEADER = "X-ECOMP-RequestID"; - // This value is as per test resource code. Don't change this. - private static final String CLIENTAUTHVALUE = "Basic cHl0aG9uOnRlc3Q="; - private static final String ERRORCLIENTVALUE = "Basic dGVzdDp0ZXN0MTIz"; - - private MockMvc mockMvc; - private HttpHeaders headers; - - @Autowired - private WebApplicationContext webApplicationContext; - - @Before() - public void setup() throws IOException{ - headers = new HttpHeaders(); - headers.add(CLIENTAUTHHEADER, CLIENTAUTHVALUE); - XACMLProperties.reloadProperties(); - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/pass.xacml.pdp.properties"); - XACMLProperties.getProperties(); - this.mockMvc = webAppContextSetup(webApplicationContext).build(); - } - - @Test - public void getConfigAPIFailureTest() throws Exception{ - ConfigRequestParameters pep = new ConfigRequestParameters(); - pep.setPolicyName(".*"); - mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().is(400)); - // Authorization tests. - mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "")) - .andExpect(status().isUnauthorized()); - mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")) - .andExpect(status().isUnauthorized()); - mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, ERRORCLIENTVALUE)) - .andExpect(status().isUnauthorized()); - // Set wrong request. - pep.setPolicyName(null); - pep.setConfigName("test"); - mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, "123").contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isBadRequest()); - } - - @Test - public void getConfigServiceTest() throws Exception{ - ConfigRequestParameters pep = new ConfigRequestParameters(); - pep.setPolicyName(".*"); - mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, UUID.randomUUID()).contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); - // Without policyName and using ecompName and other fields. - pep.setPolicyName(null); - pep.setEcompName("test"); - pep.setConfigName("test"); - mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); - // with config attributes. - Map configAttributes = new HashMap<>(); - configAttributes.put("test", "test"); - pep.setConfigAttributes(configAttributes); - pep.makeUnique(true); - mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); - } - - @Test - public void getConfigByPolicyNameTest() throws Exception{ - ConfigNameRequest pep = new ConfigNameRequest(); - pep.setPolicyName(".*"); - mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().is(400)); - // Authorization tests. - mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "")) - .andExpect(status().isUnauthorized()); - mockMvc.perform(post("/getConfigByPolicyName").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, UUID.randomUUID()).contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); - } - - @Test - public void listConfigTest() throws Exception{ - ConfigRequestParameters pep = new ConfigRequestParameters(); - pep.setPolicyName(".*"); - mockMvc.perform(post("/listConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().is(400)); - // Authorization tests. - mockMvc.perform(post("/listConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "")) - .andExpect(status().isUnauthorized()); - mockMvc.perform(post("/listConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, UUID.randomUUID()).contentType(MediaType.APPLICATION_JSON)) - .andExpect(status().isOk()); - } - - @Test - public void getMetricsTest() throws Exception{ - //Failure Tests. - mockMvc.perform(get("/getMetrics")).andExpect(status().isBadRequest()); - mockMvc.perform(get("/getMetrics").header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); - //Service Tests. - mockMvc.perform(get("/getMetrics").headers(headers).header(UUIDHEADER, "123")).andExpect(status().isOk()); - mockMvc.perform(get("/getMetrics").headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isOk()); - mockMvc.perform(get("/getMetrics").headers(headers)).andExpect(status().isOk()); - } - - @Test - public void getNotificationAuthFailureTest() throws Exception{ - mockMvc.perform(post("/getNotification").header(CLIENTAUTHHEADER, "").content("test")).andExpect(status().isUnauthorized()); - mockMvc.perform(post("/getNotification").header(CLIENTAUTHHEADER, "Basic test123").content("test")).andExpect(status().isUnauthorized()); - mockMvc.perform(post("/getNotification").header(CLIENTAUTHHEADER, ERRORCLIENTVALUE).content(" ")).andExpect(status().isUnauthorized()); - } - - @Test - public void getNotificationTopicFailureTest() throws Exception{ - mockMvc.perform(post("/getNotification")).andExpect(status().isBadRequest()); - mockMvc.perform(post("/getNotification").headers(headers).content("")).andExpect(status().isBadRequest()); - } - - @Test - public void getNotificationTopicValidFailTest() throws Exception{ - // Check failures. - mockMvc.perform(post("/getNotification").headers(headers).content(" ")).andExpect(status().isBadRequest()); - mockMvc.perform(post("/stopNotification").headers(headers).content(" ")).andExpect(status().isBadRequest()); - mockMvc.perform(post("/sendHeartbeat").headers(headers).content(" ")).andExpect(status().isBadRequest()); - } - - @Test - public void getNotificationTopicValidPassTest() throws Exception{ - // Add a Topic. - mockMvc.perform(post("/getNotification").headers(headers).header(UUIDHEADER, "123").content("test")).andExpect(status().isOk()); - // Try to add same topic should fail. - mockMvc.perform(post("/getNotification").headers(headers).header(UUIDHEADER, UUID.randomUUID()).content("test")).andExpect(status().isBadRequest()); - // do a heart beat. - mockMvc.perform(post("/sendHeartbeat").headers(headers).content("test")).andExpect(status().isOk()); - // remove the added Topic. - mockMvc.perform(post("/stopNotification").headers(headers).content("test")).andExpect(status().isOk()); - // try to remove again should fail. - mockMvc.perform(post("/sendHeartbeat").headers(headers).content("test")).andExpect(status().isBadRequest()); - } - - @Test - public void sendEventTest() throws Exception{ - EventRequestParameters pep = new EventRequestParameters(); - Map eventAttributes = new HashMap<>(); - eventAttributes.put("TEST", "test"); - pep.setEventAttributes(eventAttributes); - //Failure Tests. - mockMvc.perform(post("/sendEvent")).andExpect(status().isBadRequest()); - mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); - //Service Tests. - mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isOk()); - pep.setEventAttributes(null); - mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setEventAttributes(eventAttributes); - mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isOk()); - pep.setEventAttributes(eventAttributes); - pep.setRequestID(UUID.randomUUID()); - mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isOk()); - } - - @Test - public void getDecisionTest() throws Exception{ - DecisionRequestParameters pep = new DecisionRequestParameters(); - Map eventAttributes = new HashMap<>(); - eventAttributes.put("TEST", "test"); - pep.setECOMPComponentName("te123"); - pep.setDecisionAttributes(eventAttributes); - //Failure Tests. - mockMvc.perform(post("/getDecision")).andExpect(status().isBadRequest()); - mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); - //Service Tests. - mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isOk()); - pep.setDecisionAttributes(null); - pep.setECOMPComponentName(null); - mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setECOMPComponentName("testing"); - mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setDecisionAttributes(eventAttributes); - pep.setRequestID(UUID.randomUUID()); - mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isOk()); - } - - @Test - public void pushPolicyTest() throws Exception{ - PushPolicyParameters pep = new PushPolicyParameters(); - //Failure Tests. - mockMvc.perform(put("/pushPolicy")).andExpect(status().isBadRequest()); - mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); - //Service Tests. - mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyName("scopeless"); - mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setPolicyName("testing.test"); - pep.setPolicyType("wrong"); - mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setPolicyType("BRMS_PARAM"); - mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setPolicyType("BRMS_RAW"); - mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setPolicyType("MicroService"); - mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setPolicyType("ClosedLoop_PM"); - mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setPolicyType("ClosedLoop_Fault"); - mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setPolicyType("Base"); - mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setPolicyType("Decision"); - mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setPolicyType("Action"); - mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setPolicyType("Firewall"); - mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setPdpGroup("default"); - mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isBadRequest()); - pep.setRequestID(UUID.randomUUID()); - mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - } - - @Test - public void deletePolicyTest() throws Exception{ - DeletePolicyParameters pep = new DeletePolicyParameters(); - //Failure Tests. - mockMvc.perform(delete("/deletePolicy")).andExpect(status().isBadRequest()); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); - //Service Tests. - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyName("testing"); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "test123")).andExpect(status().isBadRequest()); - pep.setPolicyName("testscope.name"); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setPolicyName("testscope.name"); - pep.setPolicyType("wrong"); - pep.setRequestID(UUID.randomUUID()); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setPolicyType("BRMS_PARAM"); - pep.setPolicyComponent("wrong"); - pep.setRequestID(null); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setPolicyType("BRMS_RAW"); - pep.setPolicyComponent("PDP"); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyType("MicroService"); - pep.setPolicyComponent("PAP"); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyType("ClosedLoop_PM"); - pep.setPolicyComponent("PDP"); - pep.setDeleteCondition(DeletePolicyCondition.ALL); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyType("ClosedLoop_Fault"); - pep.setDeleteCondition(DeletePolicyCondition.ONE); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyType("Base"); - pep.setPolicyComponent("PAP"); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyType("Decision"); - pep.setPolicyComponent("PDP"); - pep.setPolicyName("test.xml"); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyType("Action"); - pep.setPolicyName("scope.Config_test.xml"); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPdpGroup("default"); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyComponent("PAP"); - pep.setPolicyType("Firewall"); - pep.setDeleteCondition(null); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyComponent("PAP"); - pep.setDeleteCondition(DeletePolicyCondition.ONE); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyComponent("fail"); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyComponent("PDP"); - pep.setPolicyName("testscope.policyName"); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyComponent(null); - mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - } - - @Test - public void createUpdatePolicyTest() throws Exception{ - PolicyParameters pep = new PolicyParameters(); - //Failure Tests. - mockMvc.perform(put("/createPolicy")).andExpect(status().isBadRequest()); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); - mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); - //Service Tests. - setCreateUpdateImpl(); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyName("failName"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "test 123")).andExpect(status().isBadRequest()); - pep.setPolicyName("test. name"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setPolicyName(" "); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyName("test. "); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyName("te st.name"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyName("test.name"); - pep.setPolicyDescription("testá"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setPolicyName("test.name"); - pep.setPolicyDescription("good"); - pep.setTtlDate(new Date()); - pep.setRequestID(UUID.randomUUID()); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - } - - @Test - public void brmsPolicyCreationTests() throws Exception{ - PolicyParameters pep = new PolicyParameters(); - pep.setPolicyName("test.name"); - pep.setPolicyDescription("good"); - pep.setTtlDate(new Date()); - pep.setRequestID(UUID.randomUUID()); - setCreateUpdateImpl(); - // Checks for BRMS Param Policy. - pep.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setRiskLevel("test"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - Map> attributes = new HashMap<>(); - Map matching = new HashMap<>(); - matching.put("key", "value"); - attributes.put(AttributeType.MATCHING, matching); - pep.setAttributes(attributes); - pep.setRiskLevel("5"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - // Checks for BRMS Raw Policy - pep.setPolicyConfigType(PolicyConfigType.BRMS_RAW); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("test"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setRiskLevel(null); - pep.setConfigBody("package droolsexample\n\n import com.sample.ItemCity;\nimport java.math.BigDecimal;\nrule \"Nagpur Medicine Item\"\n\n when\n item : ItemCity(purchaseCity == ItemCity.City.NAGPUR,\n typeofItem == ItemCity.Type.MEDICINES)\n then\n BigDecimal tax = new BigDecimal(0.0);\n item.setLocalTax(tax.multiply(item.getSellPrice()));\nend"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setRiskLevel("5"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - } - - @Test - public void baseConfigTests() throws Exception{ - PolicyParameters pep = new PolicyParameters(); - pep.setPolicyName("test.name"); - pep.setPolicyDescription("good"); - pep.setTtlDate(new Date()); - pep.setRequestID(UUID.randomUUID()); - setCreateUpdateImpl(); - // Checks for Base config Policy. - pep.setPolicyConfigType(PolicyConfigType.Base); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("testbody"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBodyType(PolicyType.OTHER); - pep.setRiskLevel("test"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setRiskLevel("4"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setEcompName("ec nam-e"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setEcompName("ecompName"); - pep.setConfigName("tes config"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigName("configName"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - pep.setConfigBody("{'test':'test}"); - pep.setConfigBodyType(PolicyType.JSON); - mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - Map> attributes = new HashMap<>(); - Map matching = new HashMap<>(); - matching.put("key", "value"); - attributes.put(AttributeType.MATCHING, matching); - pep.setAttributes(attributes); - pep.setConfigBody("testBody"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - } - - @Test - public void closedLoopPolicyTests() throws Exception{ - PolicyParameters pep = new PolicyParameters(); - pep.setPolicyName("test.name"); - pep.setPolicyDescription("good"); - pep.setTtlDate(new Date()); - pep.setRequestID(UUID.randomUUID()); - setCreateUpdateImpl(); - // Checks for Closed loop Policy. - pep.setPolicyConfigType(PolicyConfigType.ClosedLoop_Fault); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("te stá"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("testBody"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("{\"key\":\"value\"}"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("{\"ecompname\":\"\"}"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("{\"ecompname\":\"test\"}"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - pep.setRiskLevel("test"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setRiskLevel("4"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - } - - @Test - public void closedLoopPMTests() throws Exception{ - PolicyParameters pep = new PolicyParameters(); - pep.setPolicyName("test.name"); - pep.setPolicyDescription("good"); - pep.setTtlDate(new Date()); - pep.setRequestID(UUID.randomUUID()); - setCreateUpdateImpl(); - // Checks for Closed loop Policy. - pep.setPolicyConfigType(PolicyConfigType.ClosedLoop_PM); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("te stá"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("testBody"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("{\"key\":\"value\"}"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("{\"ecompname\":\"\"}"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("{\"ecompname\":\"test\"}"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("{\"ecompname\":\"test\", \"serviceTypePolicyName\":\"value\"}"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - pep.setRiskLevel("test"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setRiskLevel("4"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - } - - @Test - public void firewallPolicyTests() throws Exception{ - PolicyParameters pep = new PolicyParameters(); - pep.setPolicyName("test.name"); - pep.setPolicyDescription("good"); - pep.setTtlDate(new Date()); - pep.setRequestID(UUID.randomUUID()); - setCreateUpdateImpl(); - // Checks for Closed loop Policy. - pep.setPolicyConfigType(PolicyConfigType.Firewall); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("te st"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("{}"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("{\"test\":\"test\"}"); - pep.setRiskLevel("test"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setRiskLevel("4"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("{\"configName\":\"test\"}"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - } - - @Test - public void microServicePolicyTests() throws Exception{ - PolicyParameters pep = new PolicyParameters(); - pep.setPolicyName("test.name"); - pep.setPolicyDescription("good"); - pep.setTtlDate(new Date()); - pep.setRequestID(UUID.randomUUID()); - setCreateUpdateImpl(); - // Checks for Closed loop Policy. - pep.setPolicyConfigType(PolicyConfigType.MicroService); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("te st"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("{}"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setConfigBody("{\"test\":\"test\"}"); - pep.setEcompName(" "); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setEcompName("testecomp"); - pep.setRiskLevel("fail"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setRiskLevel("4"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - pep.setConfigBody("{\"service\":\"test\",\"uuid\":\"test\",\"location\":\"test\",\"configName\":\"test\",\"description\":\"test\",\"priority\":\"test\",\"version\":\"test\"}"); - mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - } - - @Test - public void actionDecisionPolicyCreationTests() throws Exception{ - PolicyParameters pep = new PolicyParameters(); - pep.setPolicyName("test.name"); - pep.setPolicyDescription("good"); - pep.setTtlDate(new Date()); - pep.setRequestID(UUID.randomUUID()); - setCreateUpdateImpl(); - // Checks for action Policy. - pep.setPolicyClass(PolicyClass.Action); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - Map> attributes = new HashMap<>(); - pep.setAttributes(attributes); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - attributes.put(AttributeType.MATCHING, new HashMap<>()); - pep.setAttributes(attributes); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - Map matching = new HashMap<>(); - matching.put("key", "value"); - attributes.put(AttributeType.MATCHING, matching); - pep.setAttributes(attributes); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setActionAttribute("A1"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setActionPerformer("PEX"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setActionPerformer("PEP"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - // Checks for Decision Policy. - pep.setPolicyClass(PolicyClass.Decision); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setEcompName("xyz"); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - attributes.remove(AttributeType.MATCHING); - attributes.put(AttributeType.SETTINGS, matching); - pep.setAttributes(attributes); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - attributes.put(AttributeType.MATCHING, matching); - pep.setAttributes(attributes); - mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - } - - @Test - public void createUpdateDictionaryTests() throws Exception{ - DictionaryParameters pep = new DictionaryParameters(); - //Failure Tests. - mockMvc.perform(put("/createDictionaryItem")).andExpect(status().isBadRequest()); - mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); - mockMvc.perform(put("/updateDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); - //Service Tests. - mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); - pep.setDictionaryType(DictionaryType.MicroService); - mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); - pep.setDictionary("test dict"); - pep.setRequestID(UUID.randomUUID()); - mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - pep.setDictionaryJson("{\"test\":\"value\"}"); - mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isInternalServerError()); - pep.setDictionaryJson("test123"); - mockMvc.perform(put("/updateDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isBadRequest()); - pep.setDictionary("MicroServiceDictionary"); - mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isBadRequest()); - } - - @Test - public void getDictionaryTests() throws Exception{ - DictionaryParameters pep = new DictionaryParameters(); - //Failure Tests. - mockMvc.perform(post("/getDictionaryItems")).andExpect(status().isBadRequest()); - mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); - //Service Tests. - mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); - pep.setDictionaryType(DictionaryType.Common); - mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, UUID.randomUUID().toString())).andExpect(status().isBadRequest()); - pep.setDictionary("EcompName"); - mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - pep.setRequestID(UUID.randomUUID()); - mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); - } - - @Test - public void policyEngineImportTests() throws Exception{ - //Failure Tests. - mockMvc.perform(post("/policyEngineImport")).andExpect(status().isBadRequest()); - } - - @Test - public void oldConfigAPITests() throws Exception{ - ConfigPolicyAPIRequest pep = new ConfigPolicyAPIRequest(); - //Failure Tests. - mockMvc.perform(put("/createConfig")).andExpect(status().isBadRequest()); - mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); - mockMvc.perform(put("/updateConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); - //Service Tests. - mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); - pep.setPolicyScope("test"); - mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); - pep.setPolicyName("name"); - mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); - pep.setConfigType("OTHER"); - mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); - pep.setTtlDate(new Date().toString()); - mockMvc.perform(put("/updateConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); - } - - @Test - public void oldFirewallAPITests() throws Exception{ - ConfigFirewallPolicyAPIRequest pep = new ConfigFirewallPolicyAPIRequest(); - //Failure Tests. - mockMvc.perform(put("/createFirewallConfig")).andExpect(status().isBadRequest()); - mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); - mockMvc.perform(put("/updateFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); - //Service Tests. - mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); - pep.setPolicyScope("test"); - mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); - pep.setPolicyName("name"); - mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); - pep.setTtlDate(new Date().toString()); - mockMvc.perform(put("/updateFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); - } - - private void setCreateUpdateImpl() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - Method setter = XACMLPdpServlet.class.getDeclaredMethod("setCreateUpdatePolicyConstructor", String.class); - setter.setAccessible(true); - setter.invoke(new XACMLPdpServlet(), CreateUpdatePolicyServiceImpl.class.getName()); - } - - //Health Check Tests - @Test - public void getCountTest() throws Exception { - mockMvc.perform(get("/count")) - .andExpect(status().isOk()); - } -} diff --git a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/getConfigTest.java b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/getConfigTest.java deleted file mode 100644 index ebe86b0d8..000000000 --- a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/getConfigTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.test; - -import static org.junit.Assert.assertEquals; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Collection; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.junit.Test; -import org.openecomp.policy.api.ConfigRequestParameters; -import org.openecomp.policy.api.PolicyConfigStatus; -import org.openecomp.policy.pdp.rest.api.models.PolicyConfig; -import org.openecomp.policy.pdp.rest.api.services.GetConfigService; - -public class getConfigTest { - private static final String TEST = "test"; - - @SuppressWarnings("unchecked") - @Test - public void filterMethodTest() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ - ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); - GetConfigService getConfigService= new GetConfigService(configRequestParameters, null); - Method filter = GetConfigService.class.getDeclaredMethod("filterResults", Collection.class,ConfigRequestParameters.class); - filter.setAccessible(true); - List policyConfigs = new LinkedList<>(); - - List filterResults = (List) filter.invoke(getConfigService, policyConfigs,configRequestParameters); - assertEquals(PolicyConfigStatus.CONFIG_NOT_FOUND, filterResults.get(0).getPolicyConfigStatus()); - // Check again with some values - configRequestParameters.setPolicyName(TEST); - configRequestParameters.setEcompName(TEST); - configRequestParameters.setConfigName(TEST); - Map configAttributes = new HashMap<>(); - configAttributes.put(TEST, TEST); - configRequestParameters.setConfigAttributes(configAttributes); - PolicyConfig pConfig = new PolicyConfig(); - pConfig.setPolicyName(TEST); - Map matching = new HashMap<>(); - matching.put("ECOMPName", TEST); - matching.put("ConfigName", TEST); - matching.put("TEST", TEST); - pConfig.setMatchingConditions(matching); - policyConfigs.add(pConfig); - filterResults = (List) filter.invoke(getConfigService, policyConfigs,configRequestParameters); - assertEquals(PolicyConfigStatus.CONFIG_NOT_FOUND, filterResults.get(0).getPolicyConfigStatus()); - } -} diff --git a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/getDictionaryTest.java b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/getDictionaryTest.java deleted file mode 100644 index 3ade07ccb..000000000 --- a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/api/test/getDictionaryTest.java +++ /dev/null @@ -1,231 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.api.test; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.lang.reflect.Method; - -import org.junit.Test; -import org.openecomp.policy.api.DictionaryParameters; -import org.openecomp.policy.pdp.rest.api.services.GetDictionaryService; - -public class getDictionaryTest { - - @Test - public void dictionaryJsonTest() throws Exception{ - Method formatDictionary = GetDictionaryService.class.getDeclaredMethod("formatDictionaryJson", String.class); - formatDictionary.setAccessible(true); - String input="{\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\"," - + "\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\"," - + "\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\"}"; - DictionaryParameters dp = new DictionaryParameters(); - dp.setDictionary("test"); - GetDictionaryService gds = new GetDictionaryService(dp, null); - String result = (String) formatDictionary.invoke(gds, input); - assertNull(result); - // - dp.setDictionary("EcompName"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("Attribute"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("Action"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("BRMSParamTemplate"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("VSCLAction"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("VNFType"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("PEPOptions"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("Varbind"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("Service"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("Site"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("Settings"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("DescriptiveScope"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("Enforcer"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("ActionList"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("ProtocolList"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("Zone"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("SecurityZone"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("PrefixList"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("AddressGroup"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("ServiceGroup"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("ServiceList"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("TermList"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("RuleList"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("FirewallRuleList"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("Term"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("MicroServiceLocation"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("MicroServiceConfigName"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("DCAEUUID"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("MicroServiceModels"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("PolicyScopeService"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("PolicyScopeResource"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("PolicyScopeType"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("PolicyScopeClosedLoop"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("GroupPolicyScopeList"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("RiskType"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("SafePolicyWarning"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - // - dp.setDictionary("MicroServiceDictionary"); - gds = new GetDictionaryService(dp, null); - result = (String) formatDictionary.invoke(gds, input); - assertNotNull(result); - } -} diff --git a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/auth/test/FilterTests.java b/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/auth/test/FilterTests.java deleted file mode 100644 index 944dd90a9..000000000 --- a/ECOMP-PDP-REST/src/test/java/org/openecomp/policy/pdp/rest/auth/test/FilterTests.java +++ /dev/null @@ -1,199 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP-REST - * ================================================================================ - * 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.pdp.rest.auth.test; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.IOException; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.junit.Before; -import org.junit.Test; -import org.openecomp.policy.pdp.rest.restAuth.PDPAuthenticationFilter; - -import com.att.research.xacml.util.XACMLProperties; -import com.mockrunner.mock.web.MockRequestDispatcher; - -public class FilterTests { - - private PDPAuthenticationFilter authenticationFilter = new PDPAuthenticationFilter(); - private final String VALIDHEADERVALUE = "Basic dGVzdHBkcDphbHBoYTQ1Ng=="; - - @Before - public void setUp() throws Exception{ - authenticationFilter.init(null); - XACMLProperties.reloadProperties(); - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/pass.xacml.pdp.properties"); - XACMLProperties.getProperties(); - } - - @Test - public void testDoFilterError() throws IOException, ServletException { - // create the objects to be mocked - HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); - HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); - FilterChain filterChain = mock(FilterChain.class); - // - when(httpServletRequest.getRequestURI()).thenReturn("error"); - authenticationFilter.doFilter(httpServletRequest, httpServletResponse, - filterChain); - // verify if unauthorized - verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } - - @Test - public void testDoFilterNotification() throws IOException, ServletException { - // create the objects to be mocked - HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); - HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); - FilterChain filterChain = mock(FilterChain.class); - // - when(httpServletRequest.getRequestURI()).thenReturn("notifications"); - authenticationFilter.doFilter(httpServletRequest, httpServletResponse, - filterChain); - verify(filterChain).doFilter(httpServletRequest,httpServletResponse); - } - - @Test - public void testDoFilterSwagger() throws Exception{ - // create the objects to be mocked - HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); - HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); - FilterChain filterChain = mock(FilterChain.class); - // - when(httpServletRequest.getRequestURI()).thenReturn("/pdp/swagger"); - when(httpServletRequest.getRequestDispatcher("/api/swagger")).thenReturn(new MockRequestDispatcher()); - authenticationFilter.doFilter(httpServletRequest, httpServletResponse, - filterChain); - verify(httpServletRequest).getRequestDispatcher("/api/swagger"); - when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api-docs/"); - when(httpServletRequest.getRequestDispatcher("/api/api-docs/")).thenReturn(new MockRequestDispatcher()); - authenticationFilter.doFilter(httpServletRequest, httpServletResponse, - filterChain); - verify(httpServletRequest).getRequestDispatcher("/api/api-docs/"); - when(httpServletRequest.getRequestURI()).thenReturn("/pdp/configuration"); - when(httpServletRequest.getRequestDispatcher("/api/configuration")).thenReturn(new MockRequestDispatcher()); - authenticationFilter.doFilter(httpServletRequest, httpServletResponse, - filterChain); - verify(httpServletRequest).getRequestDispatcher("/api/configuration"); - } - - @Test - public void newRequestAuthFailTest() throws Exception{ - // create the objects to be mocked - HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); - HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); - FilterChain filterChain = mock(FilterChain.class); - // - when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); - when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("error"); - authenticationFilter.doFilter(httpServletRequest, httpServletResponse, - filterChain); - // verify if unauthorized - verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } - - @Test - public void tokenFailureTest() throws Exception{ - // create the objects to be mocked - HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); - HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); - FilterChain filterChain = mock(FilterChain.class); - // - when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); - when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic test123"); - authenticationFilter.doFilter(httpServletRequest, httpServletResponse, - filterChain); - // verify if unauthorized - verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } - - @Test - public void oldRequestAuthPassTest() throws Exception{ - // create the objects to be mocked - HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); - HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); - FilterChain filterChain = mock(FilterChain.class); - // New request no environment header check - when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); - when(httpServletRequest.getRequestDispatcher("/api/getConfig")).thenReturn(new MockRequestDispatcher()); - when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); - authenticationFilter.doFilter(httpServletRequest, httpServletResponse, - filterChain); - // verify if authorized - verify(httpServletRequest).getRequestDispatcher("/api/getConfig"); - // - // Old Requests Checks - // - when(httpServletRequest.getRequestURI()).thenReturn("/pdp/getConfig"); - when(httpServletRequest.getRequestDispatcher("/api//getConfig")).thenReturn(new MockRequestDispatcher()); - when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); - authenticationFilter.doFilter(httpServletRequest, httpServletResponse, - filterChain); - // verify if authorized - verify(httpServletRequest).getRequestDispatcher("/api//getConfig"); - } - - @Test - public void newRequestAuthPassTest() throws Exception{ - // create the objects to be mocked - HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); - HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); - FilterChain filterChain = mock(FilterChain.class); - // - // Requests with Valid Environment Header values. - // - when(httpServletRequest.getRequestURI()).thenReturn("/pdp/getConfig"); - when(httpServletRequest.getRequestDispatcher("/api//getConfig")).thenReturn(new MockRequestDispatcher()); - when(httpServletRequest.getHeader(PDPAuthenticationFilter.ENVIRONMENT_HEADER)).thenReturn("DEVL"); - when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); - authenticationFilter.doFilter(httpServletRequest, httpServletResponse, - filterChain); - // verify if authorized - verify(httpServletRequest).getRequestDispatcher("/api//getConfig"); - // New request no environment header check - when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); - when(httpServletRequest.getRequestDispatcher("/api/getConfig")).thenReturn(new MockRequestDispatcher()); - when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); - authenticationFilter.doFilter(httpServletRequest, httpServletResponse, - filterChain); - // verify if authorized - verify(httpServletRequest).getRequestDispatcher("/api/getConfig"); - // - // - // Requests with InValid Environment Header - // - when(httpServletRequest.getRequestURI()).thenReturn("/pdp/getConfig"); - when(httpServletRequest.getRequestDispatcher("/api//getConfig")).thenReturn(new MockRequestDispatcher()); - when(httpServletRequest.getHeader(PDPAuthenticationFilter.ENVIRONMENT_HEADER)).thenReturn("TEST"); - when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); - authenticationFilter.doFilter(httpServletRequest, httpServletResponse, - filterChain); - // verify if unauthorized - verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); - } -} diff --git a/ECOMP-PDP-REST/src/test/resources/fail.xacml.pdp.properties b/ECOMP-PDP-REST/src/test/resources/fail.xacml.pdp.properties deleted file mode 100644 index 52ca6ab92..000000000 --- a/ECOMP-PDP-REST/src/test/resources/fail.xacml.pdp.properties +++ /dev/null @@ -1,171 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP-REST -# ================================================================================ -# 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========================================================= -### - -# Default XACML Properties File for PDP RESTful servlet -# -# Standard API Factories -# -xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory -xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory -xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory -# NOT USED SEE BELOW xacml.pipFinderFactory=org.openecomp.policy.xacml.std.pip.StdPIPFinderFactory -xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory -# -# AT&T PDP Implementation Factories -# -xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory -xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory -xacml.att.functionDefinitionFactory=org.openecomp.policy.xacml.custom.EcompFunctionDefinitionFactory -# NOT USED SEE BELOW xacml.att.policyFinderFactory=org.openecomp.policy.pdp.std.StdPolicyFinderFactory -# creteUpdate Policy Implementation Class details. -createUpdatePolicy.impl.className=org.openecomp.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl -# AAF Implementation class details -aafClient.impl.className=org.openecomp.policy.utils.AAFPolicyClientImpl -# -# AT&T RESTful PDP Implementation Factories -# -xacml.pipFinderFactory=org.openecomp.policy.pdp.rest.impl.XACMLPdpPIPFinderFactory -xacml.att.policyFinderFactory=org.openecomp.policy.pdp.rest.XACMLPdpPolicyFinderFactory -# -# When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into -# into one PolicySet and use the given Policy Algorithm. -# -xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides -# -# PDP RESTful API properties -# -# Set this to the address where the XACML-PAP-REST servlet is running -xacml.rest.pap.url=http://localhost:8070/pap/ - -#if multiple paps exist, the xacml.rest.pap.url can be removed and they can be defined like this: -#xacml.rest.pap.urls=http://localhost:9090/pap/,http://localhost:9091/pap/ - -# -# Give the running PDP an ID for the PAP. The url that its running as is a good choice. -# The PAP identifies PDP's using the URL of the PDP. -# -xacml.rest.pdp.id=http://localhost:8082/pdp/ - -# Give the port number used for the PDP - -xacml.jmx.port=0 - - -# Notification Properties -# Notifcation type: websocket, ueb or dmaap... if left blank websocket is the default -NOTIFICATION_TYPE=websocket -NOTIFICATION_SERVERS= -NOTIFICATION_TOPIC= -NOTIFICATION_DELAY=500 -UEB_API_KEY= -UEB_API_SECRET= -DMAAP_AAF_LOGIN=test -DMAAP_AAF_PASSWORD=test - -# -# Set the directory where the PDP holds its Policy Cache and PIP Configuration -# -xacml.rest.pdp.config=config - -xacml.rest.pdp.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ -# -# Initialize register with PAP servlet -# -xacml.rest.pdp.register=true -# -# Sleep period in seconds between register attempts -# -xacml.rest.pdp.register.sleep=15 -# -# number of attempts to register. -1 means keep trying forever. -# -xacml.rest.pdp.register.retries=-1 -# -# max number of bytes in a POST of a XML/JSON request -# old value #32767 -xacml.rest.pdp.maxcontent=99999999 -# -# Set UserID here -xacml.rest.pdp.userid=testpdp -# Set Password here -xacml.rest.pdp.password=alpha456 - -# id PAP -xacml.rest.pap.userid=testpap -#if multiple paps have different logins, they can be defined like this: -#http\://localhost\:9090/pap/.xacml.rest.pap.userid=testpap - -# pass PAP -xacml.rest.pap.password=alpha123 -#http\://localhost\:9090/pap/.xacml.rest.pap.password=alpha123 - -# Delay for Notifications Don't change this. Value in milliSec. -xacml.rest.notification.delay=30 -# Buffer Size. -REQUEST_BUFFER_SIZE=15 - -#properties for MySql xacml database: PLEASE DO NOT REMOVE... NEEDED FOR APIs -javax.persistence.jdbc.driver=com.mysql.jdbc.Driver -javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/xacml -javax.persistence.jdbc.user=policy_user -javax.persistence.jdbc.password=policy_user - - -#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java*** - -#The name of the PDP. Must be unique across the system -xacml.rest.pdp.resource.name=site_1.pdp_1 - -#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** - -#Interval between forward progress counter updates in seconds -fp_monitor_interval=30 - -#Number of forward progress counter failures before failover -failed_counter_threshold=3 - -#Interval in seconds between test transactions if there is no other traffic -test_trans_interval=10 - -#Interval in seconds between updates of the forward progress counter in the DB -write_fpc_interval=5 - -#Name of the site -site_name=site_1 - -#Node type -node_type=pdp_xacml - -#Dependency groups are groups of resources upon which a node operational state is dependent upon). -#Each group is a comma-separated list of resource names and groups are separated by a semicolon. -#A group may contain one or more members. Resource names must match the resource names defined -#in the respective servers' properties files -dependency_groups=site_1.pdplp_1;site_1.astragw_1;site_1.brmsgw_1 - -# this can be DEVL, TEST, PROD -ENVIRONMENT=DEVL -xacml.rest.pep.idfile = src/test/resources/client.properties - -#AAF Policy Name space -#Not Mandatory for Open Ecomp -policy.aaf.namespace = -policy.aaf.resource = -# -DMAAP_AAF_LOGIN = diff --git a/ECOMP-PDP-REST/src/test/resources/pass.xacml.pdp.properties b/ECOMP-PDP-REST/src/test/resources/pass.xacml.pdp.properties deleted file mode 100644 index 0fe3e2aee..000000000 --- a/ECOMP-PDP-REST/src/test/resources/pass.xacml.pdp.properties +++ /dev/null @@ -1,171 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP-REST -# ================================================================================ -# 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========================================================= -### - -# Default XACML Properties File for PDP RESTful servlet -# -# Standard API Factories -# -xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory -xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory -xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory -# NOT USED SEE BELOW xacml.pipFinderFactory=org.openecomp.policy.xacml.std.pip.StdPIPFinderFactory -xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory -# -# AT&T PDP Implementation Factories -# -xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory -xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory -xacml.att.functionDefinitionFactory=org.openecomp.policy.xacml.custom.EcompFunctionDefinitionFactory -# NOT USED SEE BELOW xacml.att.policyFinderFactory=org.openecomp.policy.pdp.std.StdPolicyFinderFactory -# creteUpdate Policy Implementation Class details. -createUpdatePolicy.impl.className=org.openecomp.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl -# AAF Implementation class details -aafClient.impl.className=org.openecomp.policy.utils.AAFPolicyClientImpl -# -# AT&T RESTful PDP Implementation Factories -# -xacml.pipFinderFactory=org.openecomp.policy.pdp.rest.impl.XACMLPdpPIPFinderFactory -xacml.att.policyFinderFactory=org.openecomp.policy.pdp.rest.XACMLPdpPolicyFinderFactory -# -# When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into -# into one PolicySet and use the given Policy Algorithm. -# -xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides -# -# PDP RESTful API properties -# -# Set this to the address where the XACML-PAP-REST servlet is running -xacml.rest.pap.url=http://localhost:8070/pap/ - -#if multiple paps exist, the xacml.rest.pap.url can be removed and they can be defined like this: -#xacml.rest.pap.urls=http://localhost:9090/pap/,http://localhost:9091/pap/ - -# -# Give the running PDP an ID for the PAP. The url that its running as is a good choice. -# The PAP identifies PDP's using the URL of the PDP. -# -xacml.rest.pdp.id=http://localhost:8082/pdp/ - -# Give the port number used for the PDP - -xacml.jmx.port=0 - - -# Notification Properties -# Notifcation type: websocket, ueb or dmaap... if left blank websocket is the default -NOTIFICATION_TYPE=websocket -NOTIFICATION_SERVERS=test -NOTIFICATION_TOPIC=test -NOTIFICATION_DELAY=500 -UEB_API_KEY= -UEB_API_SECRET= -DMAAP_AAF_LOGIN=test -DMAAP_AAF_PASSWORD=test - -# -# Set the directory where the PDP holds its Policy Cache and PIP Configuration -# -xacml.rest.pdp.config=config - -xacml.rest.pdp.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ -# -# Initialize register with PAP servlet -# -xacml.rest.pdp.register=true -# -# Sleep period in seconds between register attempts -# -xacml.rest.pdp.register.sleep=15 -# -# number of attempts to register. -1 means keep trying forever. -# -xacml.rest.pdp.register.retries=-1 -# -# max number of bytes in a POST of a XML/JSON request -# old value #32767 -xacml.rest.pdp.maxcontent=99999999 -# -# Set UserID here -xacml.rest.pdp.userid=testpdp -# Set Password here -xacml.rest.pdp.password=alpha456 - -# id PAP -xacml.rest.pap.userid=testpap -#if multiple paps have different logins, they can be defined like this: -#http\://localhost\:9090/pap/.xacml.rest.pap.userid=testpap - -# pass PAP -xacml.rest.pap.password=alpha123 -#http\://localhost\:9090/pap/.xacml.rest.pap.password=alpha123 - -# Delay for Notifications Don't change this. Value in milliSec. -xacml.rest.notification.delay=30 -# Buffer Size. -REQUEST_BUFFER_SIZE=15 - -#properties for MySql xacml database: PLEASE DO NOT REMOVE... NEEDED FOR APIs -javax.persistence.jdbc.driver=com.mysql.jdbc.Driver -javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/xacml -javax.persistence.jdbc.user=policy_user -javax.persistence.jdbc.password=policy_user - - -#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java*** - -#The name of the PDP. Must be unique across the system -xacml.rest.pdp.resource.name=site_1.pdp_1 - -#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** - -#Interval between forward progress counter updates in seconds -fp_monitor_interval=30 - -#Number of forward progress counter failures before failover -failed_counter_threshold=3 - -#Interval in seconds between test transactions if there is no other traffic -test_trans_interval=10 - -#Interval in seconds between updates of the forward progress counter in the DB -write_fpc_interval=5 - -#Name of the site -site_name=site_1 - -#Node type -node_type=pdp_xacml - -#Dependency groups are groups of resources upon which a node operational state is dependent upon). -#Each group is a comma-separated list of resource names and groups are separated by a semicolon. -#A group may contain one or more members. Resource names must match the resource names defined -#in the respective servers' properties files -dependency_groups=site_1.pdplp_1;site_1.astragw_1;site_1.brmsgw_1 - -# this can be DEVL, TEST, PROD -ENVIRONMENT=DEVL -xacml.rest.pep.idfile = src/test/resources/client.properties - -#AAF Policy Name space -#Not Mandatory for Open Ecomp -policy.aaf.namespace = -policy.aaf.resource = -# -DMAAP_AAF_LOGIN = diff --git a/ECOMP-PDP-REST/src/test/resources/test.drl b/ECOMP-PDP-REST/src/test/resources/test.drl deleted file mode 100644 index 2a58f5439..000000000 --- a/ECOMP-PDP-REST/src/test/resources/test.drl +++ /dev/null @@ -1,1121 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * archetype-closed-loop-demo-rules - * ================================================================================ - * 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.controlloop; - -import java.util.List; -import java.util.LinkedList; -import java.util.Map; -import java.util.HashMap; -import java.util.UUID; - -import org.onap.policy.controlloop.VirtualControlLoopEvent; -import org.onap.policy.controlloop.ControlLoopEventStatus; -import org.onap.policy.controlloop.VirtualControlLoopNotification; -import org.onap.policy.controlloop.ControlLoopNotificationType; -import org.onap.policy.controlloop.ControlLoopOperation; -import org.onap.policy.controlloop.ControlLoopOperationWrapper; -import org.onap.policy.template.demo.ControlLoopException; - -import org.onap.policy.aai.AAINQF199.AAINQF199CloudRegion; -import org.onap.policy.aai.AAINQF199.AAINQF199ExtraProperties; -import org.onap.policy.aai.AAINQF199.AAINQF199ExtraProperty; -import org.onap.policy.aai.AAINQF199.AAINQF199GenericVNF; -import org.onap.policy.aai.AAINQF199.AAINQF199InstanceFilters; -import org.onap.policy.aai.AAINQF199.AAINQF199InventoryResponseItem; -import org.onap.policy.aai.AAINQF199.AAINQF199InventoryResponseItems; -import org.onap.policy.aai.AAINQF199.AAINQF199Manager; -import org.onap.policy.aai.AAINQF199.AAINQF199NamedQuery; -import org.onap.policy.aai.AAINQF199.AAINQF199QueryParameters; -import org.onap.policy.aai.AAINQF199.AAINQF199Request; -import org.onap.policy.aai.AAINQF199.AAINQF199RequestWrapper; -import org.onap.policy.aai.AAINQF199.AAINQF199Response; -import org.onap.policy.aai.AAINQF199.AAINQF199ResponseWrapper; -import org.onap.policy.aai.AAINQF199.AAINQF199ServiceInstance; -import org.onap.policy.aai.AAINQF199.AAINQF199Tenant; -import org.onap.policy.aai.AAINQF199.AAINQF199VfModule; -import org.onap.policy.aai.AAINQF199.AAINQF199VServer; -import org.onap.policy.aai.util.Serialization; - -import org.onap.policy.appc.CommonHeader; -import org.onap.policy.appc.Request; -import org.onap.policy.appc.Response; -import org.onap.policy.appc.ResponseCode; -import org.onap.policy.appc.ResponseStatus; -import org.onap.policy.appc.ResponseValue; - -import org.onap.policy.template.demo.EventManager; -import org.onap.policy.vnf.trafficgenerator.PGRequest; -import org.onap.policy.vnf.trafficgenerator.PGStream; -import org.onap.policy.vnf.trafficgenerator.PGStreams; - -import org.onap.policy.mso.MSOManager; -import org.onap.policy.mso.MSORequest; -import org.onap.policy.mso.MSORequestStatus; -import org.onap.policy.mso.MSORequestDetails; -import org.onap.policy.mso.MSOModelInfo; -import org.onap.policy.mso.MSOCloudConfiguration; -import org.onap.policy.mso.MSORequestInfo; -import org.onap.policy.mso.MSORequestParameters; -import org.onap.policy.mso.MSORelatedInstanceListElement; -import org.onap.policy.mso.MSORelatedInstance; -import org.onap.policy.mso.MSOResponse; - -import org.openecomp.policy.drools.system.PolicyEngine; - -// -// These parameters are required to build the runtime policy -// -declare Params - closedLoopControlName : String - actor : String - aaiURL : String - aaiUsername : String - aaiPassword : String - msoURL : String - msoUsername : String - msoPassword : String - aaiNamedQueryUUID : String - aaiPatternMatch : int - notificationTopic : String - appcTopic : String -end - -/* -* -* Called once and only once to insert the parameters into working memory for this Closed Loop policy. -* (Comment SETUP rule out for the first ECOMP opensource release since policy BRMS_GW already puts a Params fact in there) -* -* -*rule "${policyName}.SETUP" -* when -* then -* System.out.println("rule SETUP is triggered."); -* Params params = new Params(); -* params.setClosedLoopControlName("${closedLoopControlName}"); -* params.setActor("${actor}"); -* params.setAaiURL("${aaiURL}"); -* params.setAaiUsername("${aaiUsername}"); -* params.setAaiPassword("${aaiPassword}"); -* params.setMsoURL("${msoURL}"); -* params.setMsoUsername("${msoUsername}"); -* params.setMsoPassword("${msoPassword}"); -* params.setAaiNamedQueryUUID("${aaiNamedQueryUUID}"); -* params.setAaiPatternMatch(${aaiPatternMatch}); -* params.setNotificationTopic("${notificationTopic}"); -* params.setAppcTopic("${appcTopic}"); -* // -* // This stays in memory as long as the rule is alive and running -* // -* insert(params); -*end -*/ -/* -* -* This rule responds to DCAE Events -* -*/ -rule "${policyName}.EVENT" - when - $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) - $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) - not ( EventManager( closedLoopControlName == $event.closedLoopControlName )) - then - System.out.println("rule EVENT is triggered."); - try { - // - // Check the requestID in the event to make sure it is not null before we create the EventManager. - // The EventManager will do extra syntax checking as well check if the closed loop is disabled/ - // - if ($event.requestID == null) { - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.notification = ControlLoopNotificationType.REJECTED; - notification.from = "policy"; - notification.message = "Missing requestID from DCAE event"; - notification.policyName = drools.getRule().getName(); - notification.policyScope = "${policyScope}"; - notification.policyVersion = "${policyVersion}"; - // - // Let interested parties know - // - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Can't deliver notification: " + notification); - } - // - // Retract it from memory - // - retract($event); - System.out.println("Event with requestID=null has been retracted."); - } else { - // - // Create an EventManager - // - EventManager manager = new EventManager($params.getClosedLoopControlName(), $event.requestID, $event.target); - // - // Determine if EventManager can actively process the event (i.e. syntax) - // - VirtualControlLoopNotification notification = manager.activate($event); - notification.from = "policy"; - notification.policyName = drools.getRule().getName(); - notification.policyScope = "${policyScope}"; - notification.policyVersion = "${policyVersion}"; - // - // Are we actively pursuing this event? - // - if (notification.notification == ControlLoopNotificationType.ACTIVE) { - // - // Insert Event Manager into memory, this will now kick off processing. - // - insert(manager); - // - // Let interested parties know - // - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Can't deliver notification: " + notification); - } - } else { - // - // Let interested parties know - // - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Can't deliver notification: " + notification); - } - // - // Retract it from memory - // - retract($event); - } - // - // Now that the manager is inserted into Drools working memory, we'll wait for - // another rule to fire in order to continue processing. This way we can also - // then screen for additional ONSET and ABATED events for this same RequestIDs - // and for different RequestIDs but with the same closedLoopControlName and target. - // - } - // - } catch (Exception e) { - e.printStackTrace(); - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.notification = ControlLoopNotificationType.REJECTED; - notification.message = "Exception occurred " + e.getMessage(); - notification.policyName = drools.getRule().getName(); - notification.policyScope = "${policyScope}"; - notification.policyVersion = "${policyVersion}"; - // - // - // - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e1) { - System.out.println("Can't deliver notification: " + notification); - e1.printStackTrace(); - } - // - // Retract the event - // - retract($event); - } -end - -/* -* -* This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager -* is created. We can start the operations for this closed loop. -* -*/ -rule "${policyName}.EVENT.MANAGER" - when - $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) - $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) - $manager : EventManager( closedLoopControlName == $event.closedLoopControlName, controlLoopResult == null) - then - System.out.println("rule EVENT.MANAGER is triggered."); - // - // Check which event this is. - // - EventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event); - // - // We only want the initial ONSET event in memory, - // all the other events need to be retracted to support - // cleanup and avoid the other rules being fired for this event. - // - if (eventStatus != EventManager.NEW_EVENT_STATUS.FIRST_ONSET) { - System.out.println("Retracting "+eventStatus+" Event."); - retract($event); - return; - } - // - // Now the event in memory is first onset event - // - try { - // - // Pull the known AAI field from the Event - // - // generic-vnf is needed for vFirewall case - // vserver-name is needed for vLoadBalancer case - // - String genericVNF = $event.AAI.get("generic-vnf.vnf-id"); - String vserver = $event.AAI.get("vserver.vserver-name"); - // - // Check if we are implementing a simple pattern match. - // - if ($params.getAaiPatternMatch() == 1) { - // - // Yes - // - //Basic naming characteristics: - //VF Name (9 char)+VM name (13 char total)+VFC (19 char total) - //Example: - //VF Name (9 characters): cscf0001v - //VM Name(13 characters): cscf0001vm001 - //VFC name(19 characters): cscf0001vm001cfg001 - // - // zdfw1fwl01fwl02 or zdfw1fwl01fwl01 - // replaced with - // zdfw1fwl01pgn02 or zdfw1fwl01pgn01 - // - int index = genericVNF.lastIndexOf("fwl"); - if (index == -1) { - System.err.println("The generic-vnf.vnf-id from DCAE Event is not valid."); - } else { - genericVNF = genericVNF.substring(0, index) + "pgn" + genericVNF.substring(index+"fwl".length()); - } - // - // Construct an APPC request - // - ControlLoopOperation operation = new ControlLoopOperation(); - operation.actor = $params.getActor(); - operation.operation = "ModifyConfig"; - operation.target = $event.target; - // - // Create operationWrapper - // - ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); - // - // insert operationWrapper into memory - // - insert(operationWrapper); - // - Request request = new Request(); - request.CommonHeader = new CommonHeader(); - request.CommonHeader.RequestID = $event.requestID; - request.Action = operation.operation; - request.Payload = new HashMap(); - // - // Fill in the payload - // - request.Payload.put("generic-vnf.vnf-id", genericVNF); - // - PGRequest pgRequest = new PGRequest(); - pgRequest.pgStreams = new PGStreams(); - - PGStream pgStream; - for(int i = 0; i < 5; i++){ - pgStream = new PGStream(); - pgStream.streamId = "fw_udp"+(i+1); - pgStream.isEnabled = "true"; - pgRequest.pgStreams.pgStream.add(pgStream); - } - request.Payload.put("pg-streams", pgRequest.pgStreams); - - if (request != null) { - // - // Insert request into memory - // - insert(request); - // - // Tell interested parties we are performing this Operation - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.notification = ControlLoopNotificationType.OPERATION; - // message and history ?? - notification.from = "policy"; - notification.policyName = drools.getRule().getName(); - notification.policyScope = "${policyScope}"; - notification.policyVersion = "${policyVersion}"; - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - System.out.println("Can't deliver notification: " + notification); - e.printStackTrace(); - } - // - // Now send the operation request - // - if (request instanceof Request) { - try { - System.out.println("APPC request sent:"); - System.out.println(Serialization.gsonPretty.toJson(request)); - PolicyEngine.manager.deliver($params.getAppcTopic(), request); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Can't deliver request: " + request); - } - } - } else { - // - // what happens if it is null - // - } - // - } else { - // - // create AAI named-query request with UUID started with "F199" - // - AAINQF199Request aainqf199request = new AAINQF199Request(); - AAINQF199QueryParameters aainqf199queryparam = new AAINQF199QueryParameters(); - AAINQF199NamedQuery aainqf199namedquery = new AAINQF199NamedQuery(); - AAINQF199InstanceFilters aainqf199instancefilter = new AAINQF199InstanceFilters(); - // - // queryParameters - // - aainqf199namedquery.namedQueryUUID = UUID.fromString($params.getAaiNamedQueryUUID()); - aainqf199queryparam.namedQuery = aainqf199namedquery; - aainqf199request.queryParameters = aainqf199queryparam; - // - // instanceFilters - // - Map aainqf199instancefiltermap = new HashMap(); - Map aainqf199instancefiltermapitem = new HashMap(); - aainqf199instancefiltermapitem.put("vserver-name", vserver); - aainqf199instancefiltermap.put("vserver", aainqf199instancefiltermapitem); - aainqf199instancefilter.instanceFilter.add(aainqf199instancefiltermap); - aainqf199request.instanceFilters = aainqf199instancefilter; - // - // print aainqf199request for debug - // - System.out.println("AAI Request sent:"); - System.out.println(Serialization.gsonPretty.toJson(aainqf199request)); - // - // Create AAINQF199RequestWrapper - // - AAINQF199RequestWrapper aainqf199RequestWrapper = new AAINQF199RequestWrapper($event.requestID, aainqf199request); - // - // insert aainqf199request into memory - // - insert(aainqf199RequestWrapper); - } - // - } catch (Exception e) { - e.printStackTrace(); - } -end - -/* -* -* This rule happens when we got a valid ONSET, closed loop is enabled, an Event Manager -* is created, AAI Manager and AAI Request are ready in memory. We can start sending query to AAI and then wait for response. -* -*/ -rule "${policyName}.EVENT.MANAGER.AAINQF199REQUEST" - when - $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) - $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) - $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) - $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID) - then - System.out.println("rule EVENT.MANAGER.AAINQF199REQUEST is triggered."); - // - // send the request - // - AAINQF199Response aainqf199response = AAINQF199Manager.postQuery($params.getAaiURL(), $params.getAaiUsername(), $params.getAaiPassword(), - $aainqf199RequestWrapper.aainqf199request, $event.requestID); - // - // Check AAI response - // - if (aainqf199response == null) { - System.err.println("Failed to get AAI response"); - // - // Fail and retract everything - // - retract($event); - retract($manager); - retract($aainqf199RequestWrapper); - } else { - // - // Create AAINQF199ResponseWrapper - // - AAINQF199ResponseWrapper aainqf199ResponseWrapper = new AAINQF199ResponseWrapper($event.requestID, aainqf199response); - // - // insert aainqf199ResponseWrapper to memeory - // - insert(aainqf199ResponseWrapper); - } -end - -/* -* -* This rule happens when we got a valid AAI response. We can start sending request to APPC or MSO now. -* -*/ -rule "${policyName}.EVENT.MANAGER.AAINQF199RESPONSE" - when - $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) - $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) - $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) - $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID) - $aainqf199ResponseWrapper : AAINQF199ResponseWrapper(requestID == $event.requestID) - then - System.out.println("rule EVENT.MANAGER.AAINQF199RESPONSE is triggered."); - // - // Extract related fields out of AAINQF199RESPONSE - // - String vnfItemVnfId, vnfItemVnfType, vnfItemPersonaModelId, vnfItemPersonaModelVersion, vnfItemModelName, - vnfItemModelVersion, vnfItemModelNameVersionId, serviceItemServiceInstanceId, serviceItemPersonaModelId, - serviceItemModelName, serviceItemModelType, serviceItemModelVersion, serviceItemModelNameVersionId, - vfModuleItemVfModuleName, vfModuleItemPersonaModelId, vfModuleItemPersonaModelVersion, vfModuleItemModelName, - vfModuleItemModelNameVersionId, tenantItemTenantId, cloudRegionItemCloudRegionId; - try { - // - // vnfItem - // - vnfItemVnfId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfID; - vnfItemVnfType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfType; - vnfItemVnfType = vnfItemVnfType.substring(vnfItemVnfType.lastIndexOf("/")+1); - vnfItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelId; - vnfItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelVersion; - vnfItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue; - vnfItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(2).propertyValue; - vnfItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue; - // - // serviceItem - // - serviceItemServiceInstanceId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.serviceInstanceID; - serviceItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelId; - serviceItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue; - serviceItemModelType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(1).propertyValue; - serviceItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelVersion; - serviceItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue; - // - // Find the index for base vf module and non-base vf module - // - int baseIndex = -1; - int nonBaseIndex = -1; - List inventoryItems = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems; - for (AAINQF199InventoryResponseItem m : inventoryItems) { - if (m.vfModule != null && m.vfModule.isBaseVfModule == true) { - baseIndex = inventoryItems.indexOf(m); - } else if (m.vfModule != null && m.vfModule.isBaseVfModule == false && m.vfModule.orchestrationStatus == null) { - nonBaseIndex = inventoryItems.indexOf(m); - } - // - if (baseIndex != -1 && nonBaseIndex != -1) { - break; - } - } - // - // Report the error if either base vf module or non-base vf module is not found - // - if (baseIndex == -1 || nonBaseIndex == -1) { - System.err.println("Either base or non-base vf module is not found from AAI response."); - retract($aainqf199RequestWrapper); - retract($aainqf199ResponseWrapper); - retract($manager); - retract($event); - return; - } - // - // This comes from the base module - // - vfModuleItemVfModuleName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(baseIndex).vfModule.vfModuleName; - vfModuleItemVfModuleName = vfModuleItemVfModuleName.replace("Vfmodule", "vDNS"); - // - // vfModuleItem - NOT the base module - // - vfModuleItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelId; - vfModuleItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelVersion; - vfModuleItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(0).propertyValue; - vfModuleItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(4).propertyValue; - // - // tenantItem - // - tenantItemTenantId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).tenant.tenantId; - // - // cloudRegionItem - // - cloudRegionItemCloudRegionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).items.inventoryResponseItems.get(0).cloudRegion.cloudRegionId; - // - } catch (Exception e) { - e.printStackTrace(); - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.notification = ControlLoopNotificationType.REJECTED; - notification.message = "Exception occurred " + e.getMessage(); - notification.policyName = drools.getRule().getName(); - notification.policyScope = "${policyScope}"; - notification.policyVersion = "${policyVersion}"; - // - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e1) { - System.out.println("Can't deliver notification: " + notification); - e1.printStackTrace(); - } - // - notification.notification = ControlLoopNotificationType.FINAL_FAILURE; - notification.message = "Invalid named-query response from AAI"; - // - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e1) { - System.out.println("Can't deliver notification: " + notification); - e1.printStackTrace(); - } - // - // Retract everything - // - retract($aainqf199RequestWrapper); - retract($aainqf199ResponseWrapper); - retract($manager); - retract($event); - return; - } - // - // Extracted fields should not be null - // - if ((vnfItemVnfId == null) || (vnfItemVnfType == null) || - (vnfItemPersonaModelId == null) || (vnfItemModelName == null) || - (vnfItemModelVersion == null) || (vnfItemModelNameVersionId == null) || - (serviceItemServiceInstanceId == null) || (serviceItemModelName == null) || - (serviceItemModelType == null) || (serviceItemModelVersion == null) || - (serviceItemModelNameVersionId == null) || (vfModuleItemVfModuleName == null) || - (vfModuleItemPersonaModelId == null) || (vfModuleItemPersonaModelVersion == null) || - (vfModuleItemModelName == null) || (vfModuleItemModelNameVersionId == null) || - (tenantItemTenantId == null) || (cloudRegionItemCloudRegionId == null)) { - // - System.err.println("some fields are missing from AAI response."); - // - // Fail and retract everything - // - retract($aainqf199RequestWrapper); - retract($aainqf199ResponseWrapper); - retract($manager); - retract($event); - return; - } - // - // We don't need them any more - // - retract($aainqf199ResponseWrapper); - retract($aainqf199RequestWrapper); - // - // check the actor of this closed loop - // - switch ($params.getActor()) { - case "APPC": - { - // - // Construct an APPC request - // - ControlLoopOperation operation = new ControlLoopOperation(); - operation.actor = $params.getActor(); - operation.operation = "ModifyConfig"; - operation.target = $event.target; - // - // Create operationWrapper - // - ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); - // - // insert operationWrapper into memory - // - insert(operationWrapper); - // - Request request = new Request(); - request.CommonHeader = new CommonHeader(); - request.CommonHeader.RequestID = $event.requestID; - request.Action = operation.operation; - request.Payload = new HashMap(); - // - // Fill in the payload - // Hardcode genericVNF for now since AAI has not been ready for vFirewall demo case - // - String genericVNF = "zdfw1fwl01pgn02"; - request.Payload.put("generic-vnf.vnf-id", genericVNF); - // - PGRequest pgRequest = new PGRequest(); - pgRequest.pgStreams = new PGStreams(); - - PGStream pgStream; - for(int i = 0; i < 5; i++){ - pgStream = new PGStream(); - pgStream.streamId = "fw_udp"+(i+1); - pgStream.isEnabled = "true"; - pgRequest.pgStreams.pgStream.add(pgStream); - } - request.Payload.put("pg-streams", pgRequest.pgStreams); - - if (request != null) { - // - // Insert request into memory - // - insert(request); - // - // Tell interested parties we are performing this Operation - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.notification = ControlLoopNotificationType.OPERATION; - // message and history ?? - notification.from = "policy"; - notification.policyName = drools.getRule().getName(); - notification.policyScope = "${policyScope}"; - notification.policyVersion = "${policyVersion}"; - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - System.out.println("Can't deliver notification: " + notification); - e.printStackTrace(); - } - // - // Now send the operation request - // - if (request instanceof Request) { - try { - System.out.println("APPC request sent:"); - System.out.println(Serialization.gsonPretty.toJson(request)); - PolicyEngine.manager.deliver($params.getAppcTopic(), request); - } catch (Exception e) { - e.printStackTrace(); - System.out.println("Can't deliver request: " + request); - } - } - } else { - // - // what happens if it is null - // - } - } - break; - case "MSO": - { - // - // Construct an operation - // - ControlLoopOperation operation = new ControlLoopOperation(); - operation.actor = $params.getActor(); - operation.operation = "createModuleInstance"; - operation.target = $event.target; - // - // Create operationWrapper - // - ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); - // - // Construct an MSO request - // - MSORequest request = new MSORequest(); - request.requestDetails = new MSORequestDetails(); - request.requestDetails.modelInfo = new MSOModelInfo(); - request.requestDetails.cloudConfiguration = new MSOCloudConfiguration(); - request.requestDetails.requestInfo = new MSORequestInfo(); - request.requestDetails.requestParameters = new MSORequestParameters(); - request.requestDetails.requestParameters.userParams = null; - // - // cloudConfiguration - // - request.requestDetails.cloudConfiguration.lcpCloudRegionId = cloudRegionItemCloudRegionId; - request.requestDetails.cloudConfiguration.tenantId = tenantItemTenantId; - // - // modelInfo - // - request.requestDetails.modelInfo.modelType = "vfModule"; - request.requestDetails.modelInfo.modelInvariantId = vfModuleItemPersonaModelId; - request.requestDetails.modelInfo.modelNameVersionId = vfModuleItemModelNameVersionId; - request.requestDetails.modelInfo.modelName = vfModuleItemModelName; - request.requestDetails.modelInfo.modelVersion = vfModuleItemPersonaModelVersion; - // - // requestInfo - // - request.requestDetails.requestInfo.instanceName = vfModuleItemVfModuleName; - request.requestDetails.requestInfo.source = "POLICY"; - request.requestDetails.requestInfo.suppressRollback = false; - // - // relatedInstanceList - // - MSORelatedInstanceListElement relatedInstanceListElement1 = new MSORelatedInstanceListElement(); - MSORelatedInstanceListElement relatedInstanceListElement2 = new MSORelatedInstanceListElement(); - relatedInstanceListElement1.relatedInstance = new MSORelatedInstance(); - relatedInstanceListElement2.relatedInstance = new MSORelatedInstance(); - // - relatedInstanceListElement1.relatedInstance.instanceId = serviceItemServiceInstanceId; - relatedInstanceListElement1.relatedInstance.modelInfo = new MSOModelInfo(); - relatedInstanceListElement1.relatedInstance.modelInfo.modelType = "service"; - relatedInstanceListElement1.relatedInstance.modelInfo.modelInvariantId = serviceItemPersonaModelId; - relatedInstanceListElement1.relatedInstance.modelInfo.modelNameVersionId = serviceItemModelNameVersionId; - relatedInstanceListElement1.relatedInstance.modelInfo.modelName = serviceItemModelName; - relatedInstanceListElement1.relatedInstance.modelInfo.modelVersion = serviceItemModelVersion; - // - relatedInstanceListElement2.relatedInstance.instanceId = vnfItemVnfId; - relatedInstanceListElement2.relatedInstance.modelInfo = new MSOModelInfo(); - relatedInstanceListElement2.relatedInstance.modelInfo.modelType = "vnf"; - relatedInstanceListElement2.relatedInstance.modelInfo.modelInvariantId = vnfItemPersonaModelId; - relatedInstanceListElement2.relatedInstance.modelInfo.modelNameVersionId = vnfItemModelNameVersionId; - relatedInstanceListElement2.relatedInstance.modelInfo.modelName = vnfItemModelName; - relatedInstanceListElement2.relatedInstance.modelInfo.modelVersion = vnfItemModelVersion; - relatedInstanceListElement2.relatedInstance.modelInfo.modelCustomizationName = vnfItemVnfType; - // - request.requestDetails.relatedInstanceList.add(relatedInstanceListElement1); - request.requestDetails.relatedInstanceList.add(relatedInstanceListElement2); - // - // print MSO request for debug - // - System.out.println("MSO request sent:"); - System.out.println(Serialization.gsonPretty.toJson(request)); - // - // - // - if (request != null) { - // - // Tell interested parties we are performing this Operation - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.notification = ControlLoopNotificationType.OPERATION; - notification.from = "policy"; - notification.policyName = drools.getRule().getName(); - notification.policyScope = "${policyScope}"; - notification.policyVersion = "${policyVersion}"; - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - System.out.println("Can't deliver notification: " + notification); - e.printStackTrace(); - } - // - // Concatenate serviceItemServiceInstanceId and vnfItemVnfId to msoURL - // - String MSOUrl = $params.getMsoURL() + "/serviceInstances/v2/" + serviceItemServiceInstanceId + "/vnfs/" + vnfItemVnfId + "/vfModules"; - // - // Call MSO - // - MSOResponse response = MSOManager.createModuleInstance(MSOUrl, $params.getMsoURL(), $params.getMsoUsername(), $params.getMsoPassword(), request); - // - if (response != null) { - // - // Assign requestId - // - request.requestId = $event.requestID.toString(); - response.request.requestId = $event.requestID.toString(); - // - // Insert facts - // - insert(operationWrapper); - insert(request); - insert(response); - } else { - // - // MSO request not even accepted - // - notification.message = operationWrapper.operation.toMessage(); - operationWrapper.operation.message = operationWrapper.operation.toMessage(); - operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; - $manager.setControlLoopResult("FAILURE_EXCEPTION"); - notification.history.add(operationWrapper.operation); - notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; - // - // Let interested parties know - // - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - System.out.println("Can't deliver notification: " + notification); - e.printStackTrace(); - } - notification.notification = ControlLoopNotificationType.FINAL_FAILURE; - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - System.out.println("Can't deliver notification: " + notification); - e.printStackTrace(); - } - // - // Retract everything - // - retract($event); - retract($manager); - } - } else { - System.err.println("constructed MSO request is invalid."); - } - } - break; - } -end - -/* -* -* This rule responds to APPC Response Events -* -*/ -rule "${policyName}.APPC.RESPONSE" - when - $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) - $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) - $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) - $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID ) - $request : Request( getCommonHeader().RequestID == $event.requestID ) - $response : Response( getCommonHeader().RequestID == $event.requestID ) - then - System.out.println("rule APPC.RESPONSE is triggered."); - if ($response.Status == null) { - $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; - $manager.setControlLoopResult("FAILURE_EXCEPTION"); - } - // - // Get the Response Code - // - ResponseCode code = ResponseCode.toResponseCode($response.Status.Code); - if (code == null) { - $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; - $manager.setControlLoopResult("FAILURE_EXCEPTION"); - } - // - // Construct notification - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.from = "policy"; - notification.policyName = drools.getRule().getName(); - notification.policyScope = "${policyScope}"; - notification.policyVersion = "${policyVersion}"; - notification.message = $operationWrapper.operation.toMessage(); - $operationWrapper.operation.message = $operationWrapper.operation.toMessage(); - // - // Ok, let's figure out what APP-C's response is - // - switch (code) { - case ACCEPT: - $operationWrapper.operation.outcome = "PROCESSING"; - break; - case ERROR: - case REJECT: - $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; - $manager.setControlLoopResult("FAILURE_EXCEPTION"); - break; - case SUCCESS: - $operationWrapper.operation.outcome = "SUCCESS"; - $manager.setControlLoopResult("SUCCESS"); - break; - case FAILURE: - $operationWrapper.operation.outcome = "FAILURE"; - $manager.setControlLoopResult("FAILURE"); - break; - } - if ($operationWrapper.operation.outcome.equals("SUCCESS")) { - notification.history.add($operationWrapper.operation); - notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS; - // - // Let interested parties know - // - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - System.out.println("Can't deliver notification: " + notification); - e.printStackTrace(); - } - notification.notification = ControlLoopNotificationType.FINAL_SUCCESS; - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - System.out.println("Can't deliver notification: " + notification); - e.printStackTrace(); - } - - // - // We are going to retract these objects from memory - // - System.out.println("Retracting everything"); - retract($operationWrapper); - retract($request); - retract($response); - retract($event); - retract($manager); - } else if ($operationWrapper.operation.outcome.equals("PROCESSING")) { - retract($response); - } else { - notification.history.add($operationWrapper.operation); - notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; - // - // Let interested parties know - // - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - System.out.println("Can't deliver notification: " + notification); - e.printStackTrace(); - } - notification.notification = ControlLoopNotificationType.FINAL_FAILURE; - // - // Let interested parties know - // - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - System.out.println("Can't deliver notification: " + notification); - e.printStackTrace(); - } - // - // We are going to retract these objects from memory - // - System.out.println("Retracting everything"); - retract($operationWrapper); - retract($request); - retract($response); - retract($event); - retract($manager); - } - -end - -/* -* -* This rule is used to clean up APPC response -* -*/ -rule "${policyName}.APPC.RESPONSE.CLEANUP" - when - $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) - $response : Response($id : getCommonHeader().RequestID ) - not ( VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) - then - System.out.println("rule APPC.RESPONSE.CLEANUP is triggered."); - retract($response); -end - -/* -* -* This rule responds to MSO Response Events -* -*/ -rule "${policyName}.MSO.RESPONSE" - when - $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) - $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) - $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) - $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID ) - $request : MSORequest( requestId == $event.requestID.toString() ) - $response : MSOResponse( request.requestId == $event.requestID.toString() ) - then - System.out.println("rule MSO.RESPONSE is triggered."); - // - // Construct notification - // - VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); - notification.from = "policy"; - notification.policyName = drools.getRule().getName(); - notification.policyScope = "${policyScope}"; - notification.policyVersion = "${policyVersion}"; - notification.message = $operationWrapper.operation.toMessage(); - $operationWrapper.operation.message = $operationWrapper.operation.toMessage(); - // - // The operation can either be succeeded or failed - // - if($response.request.requestStatus.requestState.equals("Completed")) { - $operationWrapper.operation.outcome = "SUCCESS"; - $manager.setControlLoopResult("SUCCESS"); - notification.history.add($operationWrapper.operation); - notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS; - // - // Let interested parties know - // - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - System.out.println("Can't deliver notification: " + notification); - e.printStackTrace(); - } - notification.notification = ControlLoopNotificationType.FINAL_SUCCESS; - // - // Let interested parties know - // - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - System.out.println("Can't deliver notification: " + notification); - e.printStackTrace(); - } - // - // We are going to retract these objects from memory - // - System.out.println("Retracting everything"); - retract($operationWrapper); - retract($request); - retract($response); - retract($event); - retract($manager); - } else { - $operationWrapper.operation.outcome = "FAILURE"; - $manager.setControlLoopResult("FAILURE"); - notification.history.add($operationWrapper.operation); - notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; - // - // Let interested parties know - // - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - System.out.println("Can't deliver notification: " + notification); - e.printStackTrace(); - } - notification.notification = ControlLoopNotificationType.FINAL_FAILURE; - // - // Let interested parties know - // - try { - System.out.println(Serialization.gsonPretty.toJson(notification)); - PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); - } catch (Exception e) { - System.out.println("Can't deliver notification: " + notification); - e.printStackTrace(); - } - // - // We are going to retract these objects from memory - // - System.out.println("Retracting everything"); - retract($operationWrapper); - retract($request); - retract($response); - retract($event); - retract($manager); - } - -end diff --git a/ECOMP-PDP-REST/xacml.pdp.properties b/ECOMP-PDP-REST/xacml.pdp.properties deleted file mode 100644 index 7631d00e7..000000000 --- a/ECOMP-PDP-REST/xacml.pdp.properties +++ /dev/null @@ -1,172 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP-REST -# ================================================================================ -# 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========================================================= -### - -# Default XACML Properties File for PDP RESTful servlet -# -# Standard API Factories -# -xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory -xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory -xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory -# NOT USED SEE BELOW xacml.pipFinderFactory=org.openecomp.policy.xacml.std.pip.StdPIPFinderFactory -xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory -# -# AT&T PDP Implementation Factories -# -xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory -xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory -xacml.att.functionDefinitionFactory=org.openecomp.policy.xacml.custom.EcompFunctionDefinitionFactory -# NOT USED SEE BELOW xacml.att.policyFinderFactory=org.openecomp.policy.pdp.std.StdPolicyFinderFactory -# creteUpdate Policy Implementation Class details. -createUpdatePolicy.impl.className=org.openecomp.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl -# AAF Implementation class details -aafClient.impl.className=org.openecomp.policy.utils.AAFPolicyClientImpl -# -# AT&T RESTful PDP Implementation Factories -# -xacml.pipFinderFactory=org.openecomp.policy.pdp.rest.impl.XACMLPdpPIPFinderFactory -xacml.att.policyFinderFactory=org.openecomp.policy.pdp.rest.XACMLPdpPolicyFinderFactory -# -# When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into -# into one PolicySet and use the given Policy Algorithm. -# -xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides -# -# PDP RESTful API properties -# -# Set this to the address where the XACML-PAP-REST servlet is running -xacml.rest.pap.url=http://localhost:8070/pap/ - -#if multiple paps exist, the xacml.rest.pap.url can be removed and they can be defined like this: -#xacml.rest.pap.urls=http://localhost:9090/pap/,http://localhost:9091/pap/ - -# -# Give the running PDP an ID for the PAP. The url that its running as is a good choice. -# The PAP identifies PDP's using the URL of the PDP. -# -xacml.rest.pdp.id=http://localhost:8082/pdp/ - -# Give the port number used for the PDP - -xacml.jmx.port=0 - - -# Notification Properties -# Notifcation type: websocket, ueb or dmaap... if left blank websocket is the default -NOTIFICATION_TYPE=websocket -NOTIFICATION_SERVERS= -NOTIFICATION_TOPIC= -NOTIFICATION_DELAY= -UEB_API_KEY= -UEB_API_SECRET= -DMAAP_AAF_LOGIN= -DMAAP_AAF_PASSWORD= - -# -# Set the directory where the PDP holds its Policy Cache and PIP Configuration -# -xacml.rest.pdp.config=config - -xacml.rest.pdp.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ -# -# Initialize register with PAP servlet -# -xacml.rest.pdp.register=true -# -# Sleep period in seconds between register attempts -# -xacml.rest.pdp.register.sleep=15 -# -# number of attempts to register. -1 means keep trying forever. -# -xacml.rest.pdp.register.retries=-1 -# -# max number of bytes in a POST of a XML/JSON request -# old value #32767 -xacml.rest.pdp.maxcontent=99999999 -# -# Set UserID here -xacml.rest.pdp.userid=testpdp -# Set Password here -xacml.rest.pdp.password=alpha456 - -# id PAP -xacml.rest.pap.userid=testpap -#if multiple paps have different logins, they can be defined like this: -#http\://localhost\:9090/pap/.xacml.rest.pap.userid=testpap - -# pass PAP -xacml.rest.pap.password=alpha123 -#http\://localhost\:9090/pap/.xacml.rest.pap.password=alpha123 - -# Delay for Notifications Don't change this. Value in milliSec. -xacml.rest.notification.delay=30 -# Buffer Size. -REQUEST_BUFFER_SIZE=15 - -#properties for MySql xacml database: PLEASE DO NOT REMOVE... NEEDED FOR APIs -javax.persistence.jdbc.driver=com.mysql.jdbc.Driver -javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/ecomp_sdk -javax.persistence.jdbc.user=policy_user -javax.persistence.jdbc.password=policy_user - - -#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java*** - -#The name of the PDP. Must be unique across the system -xacml.rest.pdp.resource.name=site_1.pdp_1 - -#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** - -#Interval between forward progress counter updates in seconds -fp_monitor_interval=30 - -#Number of forward progress counter failures before failover -failed_counter_threshold=3 - -#Interval in seconds between test transactions if there is no other traffic -test_trans_interval=10 - -#Interval in seconds between updates of the forward progress counter in the DB -write_fpc_interval=5 - -#Name of the site -site_name=site_1 - -#Node type -node_type=pdp_xacml - -#Dependency groups are groups of resources upon which a node operational state is dependent upon). -#Each group is a comma-separated list of resource names and groups are separated by a semicolon. -#A group may contain one or more members. Resource names must match the resource names defined -#in the respective servers' properties files -dependency_groups=site_1.pdplp_1;site_1.astragw_1;site_1.brmsgw_1 - -# this can be DEVL, TEST, PROD -ENVIRONMENT=DEVL -xacml.rest.pep.idfile = client.properties - -#AAF Policy Name space -#Not Mandatory for Open Ecomp -policy.aaf.namespace = -policy.aaf.resource = -# Decision Response settings. -# can be either PERMIT or DENY. -decision.indeterminate.response=PERMIT \ No newline at end of file diff --git a/ECOMP-PDP/config_testing/test_PolicyEngine.xml b/ECOMP-PDP/config_testing/test_PolicyEngine.xml deleted file mode 100644 index e168ca2ab..000000000 --- a/ECOMP-PDP/config_testing/test_PolicyEngine.xml +++ /dev/null @@ -1,595 +0,0 @@ - - - - - Test Policies for the ProtoType PolicyEngineAPI - - - - Check if the CPU Utilization or Memory reach the threshold values. - - CPU - - - - 95 - - - Memory - - - - 95 - - - - - - Spinoff if the VM if CPU or memory value reaches the threshold - - CPU - - - - 90 - - - Memory - - - - 90 - - - - - Json Test - - - - - JSON - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_json.json - - - - - - Json + Config test - - - - - JSON - - - - JSONconfig - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_json.json - - - - - - XML test - - - - - XML - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_xml.xml - - - - - - XML + Config test - - - - - XML - - - - XMLConfig - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_xml.xml - - - - - - Properties Test - - - - - Properties - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_prop.properties - - - - - - Properties + Config Test - - - - - Properties - - - - PropConfig - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_prop.properties - - - - - - Other Test - - - - - Other - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_other.txt - - - - - - Other + Config Test - - - - - Other - - - - OtherConfig - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_other.txt - - - - - - JSON + Attributes - - - - - JSON - - - - JSONconfig - - - - TestSubject - - - - ACCESS - - - - TestJSON - - - - Config - - - - Test - - - - - - - - - Configuration - - - http://localhost:5443/config/test_json.json - - - - - - XML + Attributes - - - - - XML - - - - XMLConfig - - - - TestSubject - - - - ACCESS - - - - TestJSON - - - - Config - - - - Test - - - - - - - - - Configuration - - - http://localhost:5443/config/test_xml.xml - - - - - - Prop + Attributes - - - - - Properties - - - - PropConfig - - - - TestSubject - - - - ACCESS - - - - TestJSON - - - - Config - - - - Test - - - - - - - - - Configuration - - - http://localhost:5443/config/test_prop.properties - - - - - - Other + Attributes - - - - - Other - - - - Otherconfig - - - - TestSubject - - - - ACCESS - - - - TestJSON - - - - Config - - - - Test - - - - - - - - - Configuration - - - http://localhost:5443/config/test_other.txt - - - - - - - Permit to RESET VM if the values reach the threshold settings. - - - - - Restart - - - - - - - - Restart VM if this condition is met - - true - - - - - - Restart - - - - - - - - - Permit to SpinOff VM if the values reach the threshold settings. - - - - - SpinOff - - - - - - - - SpinOff VM if this condition is met - - true - - - - - - SpinOff - - - PDPAction - - - REST - - - - - - GET - - - http://localhost:8635/RESTjson/PDP/VM/$com.att.labs.ecomp.obligation.spinoff/$com.att.labs.ecomp.obligation.server - - - - - - Deny all the other requests. - - - diff --git a/ECOMP-PDP/config_testing/xacml.pip.properties b/ECOMP-PDP/config_testing/xacml.pip.properties deleted file mode 100644 index 27b5b3e9b..000000000 --- a/ECOMP-PDP/config_testing/xacml.pip.properties +++ /dev/null @@ -1,19 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP -# ================================================================================ -# 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========================================================= -### diff --git a/ECOMP-PDP/config_testing/xacml.policy.properties b/ECOMP-PDP/config_testing/xacml.policy.properties deleted file mode 100644 index 9990d375d..000000000 --- a/ECOMP-PDP/config_testing/xacml.policy.properties +++ /dev/null @@ -1,23 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP -# ================================================================================ -# 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========================================================= -### - -xacml.referencedPolicies=test_PolicyEngine.xml -xacml.rootPolicies=test_PolicyEngine.xml -test_PolicyEngine.xml.file=config_testing\\test_PolicyEngine.xml diff --git a/ECOMP-PDP/logging.properties b/ECOMP-PDP/logging.properties deleted file mode 100644 index 747d39b30..000000000 --- a/ECOMP-PDP/logging.properties +++ /dev/null @@ -1,29 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP -# ================================================================================ -# 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========================================================= -### - -handlers = java.util.logging.ConsoleHandler, java.util.logging.FileHandler - -.level = ALL - -java.util.logging.ConsoleHandler.level = INFO -java.util.logging.FileHandler.level = INFO -java.util.logging.FileHandler.pattern=%h/xacml_log%u.log -java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter -java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter diff --git a/ECOMP-PDP/policyLogger.properties b/ECOMP-PDP/policyLogger.properties deleted file mode 100644 index 0e9957442..000000000 --- a/ECOMP-PDP/policyLogger.properties +++ /dev/null @@ -1,44 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP -# ================================================================================ -# 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========================================================= -### - -################################### Set concurrentHashMap and timer info ####################### -#Timer initial delay and the delay between in milliseconds before task is to be execute. -timer.delay.time=1000 -#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. -check.interval= 30000 -#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. -event.expired.time=86400 -#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed -#to remove all expired records from this concurrentHashMap. -concurrentHashMap.limit=5000 -#Size of the concurrentHashMap - when its size drops to this point, stop the Timer -stop.check.point=2500 -################################### Set logging format ############################################# -# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println -logger.type=EELF -#################################### Set level for EELF or SYSTEMOUT logging ################################## -# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all -debugLogger.level=INFO -# Set level for metrics file. Set OFF to disable; set ON to enable -metricsLogger.level=ON -# Set level for error file. Set OFF to disable; set ON to enable -error.level=ON -# Set level for audit file. Set OFF to disable; set ON to enable -audit.level=ON diff --git a/ECOMP-PDP/pom.xml b/ECOMP-PDP/pom.xml deleted file mode 100644 index 9aa5d6fd7..000000000 --- a/ECOMP-PDP/pom.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - - 4.0.0 - ECOMP-PDP - ECOMP-PDP - jar - - org.openecomp.policy.engine - PolicyEngineSuite - 1.1.0-SNAPSHOT - - - - org.openecomp.policy.engine - ${project.version} - ECOMP-REST - - - org.apache.httpcomponents - httpclient - 4.4.1 - - - org.apache.httpcomponents - httpcore - 4.4.4 - - - org.glassfish - javax.json - 1.0.4 - - - commons-codec - commons-codec - 1.10 - - - commons-logging - commons-logging - 1.2 - - - javax.servlet - servlet-api - - - - - com.google.guava - guava - 19.0 - - - com.att.research.xacml - xacml-pdp - 1.0.0 - - - junit - junit - 4.11 - - - diff --git a/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/action/FindAction.java b/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/action/FindAction.java deleted file mode 100644 index 5419b8946..000000000 --- a/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/action/FindAction.java +++ /dev/null @@ -1,356 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.xacml.action; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.URL; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.json.Json; -import javax.json.JsonReader; - -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.rest.XACMLRestProperties; - -import com.att.research.xacml.api.Advice; -import com.att.research.xacml.api.Attribute; -import com.att.research.xacml.api.AttributeAssignment; -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.api.Obligation; -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.RequestAttributes; -import com.att.research.xacml.api.Result; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.StdAdvice; -import com.att.research.xacml.std.StdAttributeAssignment; -import com.att.research.xacml.std.StdAttributeValue; -import com.att.research.xacml.std.StdMutableResponse; -import com.att.research.xacml.std.StdMutableResult; -import com.att.research.xacml.std.StdObligation; -import com.att.research.xacml.util.XACMLProperties; - -@SuppressWarnings("deprecation") -public class FindAction { - private Logger LOGGER = FlexLogger.getLogger(this.getClass()); - private Boolean changeIt = false; - private String configURL = null; - private StdMutableResponse newResponse = new StdMutableResponse(); - private StdMutableResult addResult = new StdMutableResult(); - - public StdMutableResponse run(StdMutableResponse stdResponse, Request pepRequest) { - int count = 0; - boolean config = false; - boolean decide = false; - Collection requestAttributes = pepRequest.getRequestAttributes(); - for(RequestAttributes requestAttribute : requestAttributes){ - Collection attributes = requestAttribute.getAttributes(); - for(Attribute attribute : attributes){ - if(attribute.getAttributeId().stringValue().equals("urn:oasis:names:tc:xacml:1.0:action:action-id")){ - for(AttributeValue attributeValue : attribute.getValues()){ - if(attributeValue.getValue().toString().equalsIgnoreCase("ACCESS")){ - count++; - } - if(attributeValue.getValue().toString().equalsIgnoreCase("DECIDE")){ - decide = true; - } - } - } - if(attribute.getAttributeId().stringValue().equals("urn:oasis:names:tc:xacml:1.0:resource:resource-id")){ - for(AttributeValue attributeValue : attribute.getValues()){ - if(attributeValue.getValue().toString().equalsIgnoreCase("Config")){ - count++; - } - } - } - } - } - if(count==2){ - config = true; - } - if(!config){ - search(stdResponse); - } - addResults(stdResponse, config , decide); - LOGGER.info("Original Result is " + stdResponse.toString()); - LOGGER.info("Generated Result is " + addResult.toString()); - return newResponse; - } - - private Collection obligations = new ArrayList<>(); - private Map matchValues = new HashMap<>(); - private Map headers = new HashMap<>(); - private boolean header = false; - - private void search(StdMutableResponse stdResponse) { - for (Result result : stdResponse.getResults()) { - if (!result.getObligations().isEmpty()) { - System.out.println("Obligation Received"); - // Is there any action that PDP needs to take - for (Obligation obligation : result.getObligations()) { - int count = 0, uri = 0, PEP = 0; - header = false; - changeIt = false; - Collection afterRemoveAssignments = new ArrayList<>(); - Identifier oblId = new IdentifierImpl(obligation.getId().stringValue()); - StdAttributeAssignment attributeURI = null; - for (AttributeAssignment attribute : obligation.getAttributeAssignments()) { - matchValues.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString()); - if (attribute.getAttributeId().stringValue().equalsIgnoreCase("performer")) { - if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("PEPACTION")) { - PEP++; - } else if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("PDPACTION")) { - count++; - } - } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("URL")) { - uri++; - if (uri == 1) { - configURL = attribute.getAttributeValue().getValue().toString(); - attributeURI = new StdAttributeAssignment(attribute); - } - } else if (attribute.getAttributeId().stringValue().startsWith("headers")) { - LOGGER.info("Headers are : "+ attribute.getAttributeValue().getValue().toString()); - header = true; - headers.put(attribute.getAttributeId().stringValue().replaceFirst("(headers).", ""), - attribute.getAttributeValue().getValue().toString()); - afterRemoveAssignments.add(attribute); - } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("body")) { - String papPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); - papPath= papPath.replace("/pap", ""); - matchValues.put("body",attribute.getAttributeValue().getValue().toString().replace("$URL", papPath)); - }else { - StdAttributeAssignment attributeObligation = new StdAttributeAssignment(attribute); - afterRemoveAssignments.add(attributeObligation); - } - } - if (count == 1 && uri == 1 && PEP == 0) { - // Remove Obligation and add Advice - changeIt = true; - takeAction(stdResponse, oblId, afterRemoveAssignments); - } else if (PEP == 1 && count == 0) { - // Strip the PEPACTION if available - if (uri == 1) { - afterRemoveAssignments.add(attributeURI); - } - Obligation afterRemoveObligation = new StdObligation( - oblId, afterRemoveAssignments); - obligations.add(afterRemoveObligation); - } else { - obligations.add(obligation); - } - } - } - } - } - - private void takeAction(StdMutableResponse stdResponse, Identifier advId, - Collection afterRemoveAssignments) { - if (changeIt) { - LOGGER.info("the URL is :" + configURL); - // Calling Rest URL.. - callRest(); - // Including the Results in an Advice - Identifier id = new IdentifierImpl( - "org:openecomp:policy:pdp:reply"); - Identifier statId = new IdentifierImpl( - "org:openecomp:ecomp:policy:pdp:reply:status"); - Identifier statCategory = new IdentifierImpl( - "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject"); - Identifier strId = new IdentifierImpl( - "http://www.w3.org/2001/XMLSchema#string"); - Identifier resId = new IdentifierImpl( - "org:openecomp:ecomp:policy:pdp:reply:resource"); - Identifier resCategory = new IdentifierImpl( - "urn:oasis:names:tc:xacml:3.0:attribute-category:resource"); - Identifier urlId = new IdentifierImpl( - "http://www.w3.org/2001/XMLSchema#anyURI"); - AttributeValue attributeStatusValue = new StdAttributeValue<>( - strId, status + response); - AttributeValue attributeResourceValue = new StdAttributeValue<>( - urlId, configURL); - StdAttributeAssignment attributeStatus = new StdAttributeAssignment( - statCategory, statId, "PDP", attributeStatusValue); - StdAttributeAssignment attributeResouce = new StdAttributeAssignment( - resCategory, resId, "PDP", attributeResourceValue); - afterRemoveAssignments.add(attributeStatus); - afterRemoveAssignments.add(attributeResouce); - Advice advice = new StdAdvice(id, afterRemoveAssignments); - addResult.addAdvice(advice); - } - } - - private void addResults(StdMutableResponse stdResponse, boolean config, boolean decide) { - if(decide){ - newResponse = stdResponse; - return; - } - for (Result result : stdResponse.getResults()) { - if(config){ - addResult.addAdvice(result.getAssociatedAdvice()); - } - addResult.addAttributeCategories(result.getAttributes()); - addResult.addPolicyIdentifiers(result.getPolicyIdentifiers()); - addResult.addPolicySetIdentifiers(result.getPolicySetIdentifiers()); - addResult.setStatus(result.getStatus()); - addResult.setDecision(result.getDecision()); - if(!config){ - addResult.addObligations(obligations); - } - } - newResponse.add(addResult); - } - - private int status; - private String response; - private DefaultHttpClient httpClient; - - private void callRest() { - // Finding the Macros in the URL.. - Pattern pattern = Pattern.compile("\\$([a-zA-Z0-9.:]*)"); - Matcher match = pattern.matcher(configURL); - StringBuffer sb = new StringBuffer(); - while (match.find()) { - LOGGER.info("Found Macro : " + match.group(1)); - String replaceValue = matchValues.get(match.group(1)); - LOGGER.info("Replacing with :" + replaceValue); - match.appendReplacement(sb, replaceValue); - } - match.appendTail(sb); - LOGGER.info("URL is : " + sb.toString()); - configURL = sb.toString(); - // Calling the Requested service. - if (matchValues.get("method").equalsIgnoreCase("GET")) { - httpClient = new DefaultHttpClient(); - try { - HttpGet getRequest = new HttpGet(configURL); - // Adding Headers here - if (header) { - for (String key : headers.keySet()) { - getRequest.addHeader(key, headers.get(key)); - } - } - HttpResponse result = httpClient.execute(getRequest); - status = result.getStatusLine().getStatusCode(); - BufferedReader br = new BufferedReader(new InputStreamReader( - (result.getEntity().getContent()))); - String output = " "; - String out; - while ((out = br.readLine()) != null) { - output = output + out; - } - response = output; - } catch (Exception e) { - LOGGER.error(e.getMessage()+e); - response = e.getMessage(); - } finally { - httpClient.getConnectionManager().shutdown(); - } - } else if(matchValues.get("method").equalsIgnoreCase("POST")) { - httpClient = new DefaultHttpClient(); - try { - HttpPost postRequest = new HttpPost(configURL); - // Adding Headers here - if (header) { - for (String key : headers.keySet()) { - postRequest.addHeader(key, headers.get(key)); - } - } - // Adding the Body. - URL configURL = new URL(matchValues.get("body")); - URLConnection connection = null; - connection = configURL.openConnection(); - // InputStream in = connection.getInputStrem(); - // LOGGER.info("The Body Content is : " + IOUtils.toString(in)); - JsonReader jsonReader = Json.createReader(connection.getInputStream()); - StringEntity input = new StringEntity(jsonReader.readObject().toString()); - input.setContentType("application/json"); - postRequest.setEntity(input); - // Executing the Request. - HttpResponse result = httpClient.execute(postRequest); - LOGGER.info("Result Headers are : " + result.getAllHeaders()); - status = result.getStatusLine().getStatusCode(); - BufferedReader br = new BufferedReader(new InputStreamReader( - (result.getEntity().getContent()))); - String output = " "; - String out; - while ((out = br.readLine()) != null) { - output = output + out; - } - response = output; - }catch (Exception e) { - LOGGER.error(e.getMessage() +e); - response = e.getMessage(); - } finally { - httpClient.getConnectionManager().shutdown(); - } - } else if(matchValues.get("method").equalsIgnoreCase("PUT")) { - httpClient = new DefaultHttpClient(); - try { - HttpPut putRequest = new HttpPut(configURL); - // Adding Headers here - if (header) { - for (String key : headers.keySet()) { - putRequest.addHeader(key, headers.get(key)); - } - } - // Adding the Body. - URL configURL = new URL(matchValues.get("body")); - URLConnection connection = null; - connection = configURL.openConnection(); - //InputStream in = connection.getInputStream(); - //LOGGER.info("The Body Content is : " + IOUtils.toString(in)); - JsonReader jsonReader = Json.createReader(connection.getInputStream()); - StringEntity input = new StringEntity(jsonReader.readObject().toString()); - input.setContentType("application/json"); - putRequest.setEntity(input); - // Executing the Request. - HttpResponse result = httpClient.execute(putRequest); - status = result.getStatusLine().getStatusCode(); - BufferedReader br = new BufferedReader(new InputStreamReader( - (result.getEntity().getContent()))); - String output = " "; - String out; - while ((out = br.readLine()) != null) { - output = output + out; - } - response = output; - } catch (Exception e) { - LOGGER.error(e.getMessage() +e); - response = e.getMessage(); - }finally { - httpClient.getConnectionManager().shutdown(); - } - } - } -} \ No newline at end of file diff --git a/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/action/package-info.java b/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/action/package-info.java deleted file mode 100644 index 88ecc78c2..000000000 --- a/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/action/package-info.java +++ /dev/null @@ -1,30 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.xacml.action; - -/** - * org.openecomp.policy.xacml.action contains the implementation of the PDP Actions. - * Changes: - * Now PDP supports actions based on PUT, GET, POST methods - * - * @version 0.2 - * - */ diff --git a/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/custom/EcompFunctionDefinitionFactory.java b/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/custom/EcompFunctionDefinitionFactory.java deleted file mode 100644 index 2cb8e67ae..000000000 --- a/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/custom/EcompFunctionDefinitionFactory.java +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.xacml.custom; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.HashMap; -import java.util.Map; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.xacml.pdp.std.functions.FunctionDefinitionCustomRegexpMatch; - -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.FunctionDefinition; -import com.att.research.xacmlatt.pdp.policy.FunctionDefinitionFactory; -import com.att.research.xacmlatt.pdp.std.StdFunctions; - -public class EcompFunctionDefinitionFactory extends FunctionDefinitionFactory { - private static Logger logger = FlexLogger.getLogger(EcompFunctionDefinitionFactory.class); - private static Map mapFunctionDefinitions = new HashMap<>(); - private static boolean needMapInit = true; - - public static final Identifier ID_FUNCTION_CUSTOM_REGEXP_MATCH = new IdentifierImpl("org.openecomp.function.regex-match"); - - private static final FunctionDefinition FD_CUSTOM_REGEXP_MATCH = new FunctionDefinitionCustomRegexpMatch<>(ID_FUNCTION_CUSTOM_REGEXP_MATCH, DataTypes.DT_STRING); - - private static void register(FunctionDefinition functionDefinition) { - mapFunctionDefinitions.put(functionDefinition.getId(), functionDefinition); - } - - private static void initMap() { - if (needMapInit) { - synchronized(mapFunctionDefinitions) { - if (needMapInit) { - needMapInit = false; - Field[] declaredFields = StdFunctions.class.getDeclaredFields(); - for (Field field : declaredFields) { - if (Modifier.isStatic(field.getModifiers()) && - field.getName().startsWith(StdFunctions.FD_PREFIX) && - FunctionDefinition.class.isAssignableFrom(field.getType()) && - Modifier.isPublic(field.getModifiers()) - ) { - try { - register((FunctionDefinition)(field.get(null))); - } catch (IllegalAccessException ex) { - logger.error(ex.getMessage() +ex); - } - } - } - // - // Our custom function - // - //register(FunctionDefinitionCustomRegexpMatch); - register(FD_CUSTOM_REGEXP_MATCH); - } - } - } - } - - public EcompFunctionDefinitionFactory() { - initMap(); - } - - @Override - public FunctionDefinition getFunctionDefinition(Identifier functionId) { - return mapFunctionDefinitions.get(functionId); - } -} diff --git a/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/pdp/ECOMPPDPEngine.java b/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/pdp/ECOMPPDPEngine.java deleted file mode 100644 index 34dee4fbb..000000000 --- a/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/pdp/ECOMPPDPEngine.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.xacml.pdp; - -import java.util.Properties; - -import org.openecomp.policy.xacml.action.FindAction; - -import com.att.research.xacml.api.Decision; -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.Response; -import com.att.research.xacml.api.pdp.PDPException; -import com.att.research.xacml.api.pdp.ScopeResolver; -import com.att.research.xacml.std.StdMutableResponse; -import com.att.research.xacmlatt.pdp.ATTPDPEngine; -import com.att.research.xacmlatt.pdp.eval.EvaluationContextFactory; - -public class ECOMPPDPEngine extends ATTPDPEngine { - - public ECOMPPDPEngine(EvaluationContextFactory evaluationContextFactoryIn, Decision defaultDecisionIn, - ScopeResolver scopeResolverIn, Properties properties) { - super(evaluationContextFactoryIn, defaultDecisionIn, scopeResolverIn, properties); - } - - public ECOMPPDPEngine(EvaluationContextFactory evaluationContextFactoryIn, Decision defaultDecisionIn, - ScopeResolver scopeResolverIn) { - super(evaluationContextFactoryIn, defaultDecisionIn, scopeResolverIn); - } - - public ECOMPPDPEngine(EvaluationContextFactory evaluationContextFactoryIn, ScopeResolver scopeResolverIn) { - super(evaluationContextFactoryIn, scopeResolverIn); - } - - @Override - public Response decide(Request pepRequest) throws PDPException { - Response response = super.decide(pepRequest); - - FindAction findAction = new FindAction(); - return findAction.run((StdMutableResponse) response, pepRequest); - } - - -} diff --git a/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/pdp/ECOMPPDPEngineFactory.java b/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/pdp/ECOMPPDPEngineFactory.java deleted file mode 100644 index 437eb69b5..000000000 --- a/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/pdp/ECOMPPDPEngineFactory.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.xacml.pdp; - -import java.util.Properties; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import com.att.research.xacml.api.pdp.PDPEngine; -import com.att.research.xacml.api.pdp.PDPEngineFactory; -import com.att.research.xacml.util.FactoryException; -import com.att.research.xacmlatt.pdp.eval.EvaluationContextFactory; - -public class ECOMPPDPEngineFactory extends PDPEngineFactory { - private Logger logger = FlexLogger.getLogger(this.getClass()); - - @Override - public PDPEngine newEngine() throws FactoryException { - EvaluationContextFactory evaluationContextFactory = EvaluationContextFactory.newInstance(); - if (evaluationContextFactory == null) { - this.logger.error("Null EvaluationContextFactory"); - throw new FactoryException("Null EvaluationContextFactory"); - } - return new ECOMPPDPEngine(evaluationContextFactory, this.getDefaultBehavior(), this.getScopeResolver()); - } - - @Override - public PDPEngine newEngine(Properties properties) throws FactoryException { - EvaluationContextFactory evaluationContextFactory = EvaluationContextFactory.newInstance(properties); - if (evaluationContextFactory == null) { - this.logger.error("Null EvaluationContextFactory"); - throw new FactoryException("Null EvaluationContextFactory"); - } - return new ECOMPPDPEngine(evaluationContextFactory, this.getDefaultBehavior(), this.getScopeResolver(), properties); - } - -} diff --git a/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatch.java b/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatch.java deleted file mode 100644 index 5c11f8c43..000000000 --- a/ECOMP-PDP/src/main/java/org/openecomp/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatch.java +++ /dev/null @@ -1,130 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.xacml.pdp.std.functions; - - -import java.util.List; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -import com.att.research.xacml.api.DataType; -import com.att.research.xacml.api.DataTypeException; -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.std.StdStatus; -import com.att.research.xacml.std.StdStatusCode; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.eval.EvaluationContext; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.std.functions.ConvertedArgument; -import com.att.research.xacmlatt.pdp.std.functions.FunctionDefinitionBase; - -/** - * FunctionDefinitionCustomRegexMatch implements {@link com.att.research.xacmlatt.pdp.policy.FunctionDefinition} to - * implement the custom 'type'-regex-match predicates as functions taking two arguments, the first of String, - * and the second of the type for that specific predicate as a regular expression, - * and returning a Boolean for whether the regular expression matches the string representation of the first argument. - * - * - * @version $Revision: 0.2 $ - * - * @param the java class for the data type of the function Input arguments - */ -public class FunctionDefinitionCustomRegexpMatch extends FunctionDefinitionBase { - private static Logger logger = FlexLogger.getLogger(FunctionDefinitionCustomRegexpMatch.class); - - /** - * Constructor - need dataTypeArgs input because of java Generic type-erasure during compilation. - * - * @param idIn - * @param dataTypeArgsIn - */ - public FunctionDefinitionCustomRegexpMatch(Identifier idIn, DataType dataTypeArgsIn) { - super(idIn, DataTypes.DT_BOOLEAN, dataTypeArgsIn, false); - } - - - @Override - public ExpressionResult evaluate(EvaluationContext evaluationContext, List arguments) { - - if (arguments == null || arguments.size() != 2) { - return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, this.getShortFunctionId() + " Expected 2 arguments, got " + - ((arguments == null) ? "null" : arguments.size()) )); - } - - // get the regular expression - FunctionArgument regexpArgument = arguments.get(0); - - ConvertedArgument convertedArgument = new ConvertedArgument<>(regexpArgument, DataTypes.DT_STRING, false); - if ( ! convertedArgument.isOk()) { - return ExpressionResult.newError(getFunctionStatus(convertedArgument.getStatus())); - } - - // String regexpValue = (String)regexpArgument.getValue().getValue(); - String regexpValue = convertedArgument.getValue(); - - - // now get the element to match - FunctionArgument elementArgument = arguments.get(1); - - ConvertedArgument convertedElement = new ConvertedArgument<>(elementArgument, this.getDataTypeArgs(), false); - if ( ! convertedElement.isOk()) { - return ExpressionResult.newError(getFunctionStatus(convertedElement.getStatus())); - } - - I elementValueObject = convertedElement.getValue(); - - String elementValueString; - try { - elementValueString = this.getDataTypeArgs().toStringValue(elementValueObject); - } catch (DataTypeException e) { - logger.error(e.getMessage() +e); - String message = e.getMessage(); - if (e.getCause() != null) { - message = e.getCause().getMessage(); - } - return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, this.getShortFunctionId() + " " + message)); - } - - // ConvertedArgument checks for null value, so do not need to do again here - - // Adding this code will Change the Functionality which allows to retrieve Multiple-policy using single request. - elementValueString = elementValueString + regexpValue ; - regexpValue = elementValueString.substring(0,(elementValueString.length()- regexpValue.length())); - elementValueString = elementValueString.substring(regexpValue.length(),(elementValueString.length())); - // - // Supporting multiple values in the element and be able to query them. - if(elementValueString.contains(",")){ - String[] elements = elementValueString.split(","); - for(int i=0; i policyList = new ArrayList<>(); - - - public static List getpolicyList(){ - return policyList; - } - - public static void addPolicyID(String policyID){ - if (!policyList.contains(policyID)){ - policyList.add(policyID); - } - } - - public static void clearPolicyList(){ - if (!policyList.isEmpty()){ - policyList.clear(); - } - } -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionAccessPermittedTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionAccessPermittedTest.java deleted file mode 100644 index a94c110d8..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionAccessPermittedTest.java +++ /dev/null @@ -1,521 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.xml.namespace.NamespaceContext; - -import org.junit.Ignore; - -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.StdMutableRequest; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacml.std.dom.DOMRequest; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.std.StdEvaluationContext; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.FunctionDefinitionAccessPermitted; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * NOT IMPLEMENTED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - * This function is not yet implemented so these tests intentionally fail. - * - * - */ -public class FunctionDefinitionAccessPermittedTest { - - // - // Strings for the Request contents - // - - String reqStrMainStart = "" - + "" - + " " - + " " - + " Julius Hibbert" - + " " - + " " - + " This is IT! " - + " " - + " " - + " This is IT! " - + " " - + ""; - - String reqStrResourceStart = ""; - - String reqStrMdRecordSimpson = - "" + - "" + - "ABC Hospital" + - "Surgery" + - "" + - "" + - "Bart Simpson" + - "60" + - "male" + - "123456" + - "" + - "" + - "" + - "Gastric Cancer" + - "Hyper tension" + - "" + - "" + - "" + - "Well differentiated adeno carcinoma" + - "" + - "2000-10-05" + - "" + - "" + - "" + - " "; - String reqStrContentMdRecordSimpson = "" + reqStrMdRecordSimpson + ""; - String reqStrMalformedContent = - " " + - "" + - "" + - "ABC Hospital" + - "" + - ""; - String reqStrMdRecordSpringer = - "" + - "" + - "XYZ Hospital" + - "Surgery" + - "" + - "" + - "Jerry Springer" + - "65" + - "male" + - "765432" + - "" + - "" + - "" + - "Hyatal Hernia" + - "Diabetes" + - "Neuronal Collapse" + - "" + - "" + - "" + - "We have no idea" + - "" + - "2012-07-22" + - "" + - "" + - "" + - " "; - String reqStrContentMdRecordSpringer = - "" + reqStrMdRecordSpringer + ""; - - String reqStrResourceEnd = " " - + " http://medico.com/record/patient/BartSimpson" - + " " - + " "; - String reqStrActionStart = ""; - - String reqStrActionEnd = "" - + "read" - + "" - + " "; - String reqStrEnvironmentStartEnd = " "; - String reqStrMainEnd = " "; - - - // combined strings for convenience - String reqStrMainResourceStart = reqStrMainStart + reqStrResourceStart; - String reqStrResourceAllEnd = reqStrResourceEnd + reqStrActionStart + reqStrActionEnd + reqStrEnvironmentStartEnd + reqStrMainEnd; - - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - - - // Name Spaces used in the XML as part of these examples - needed for compiling XPaths - NamespaceContext nameSpaceContext = new NamespaceContext() { - @Override - public Iterator getPrefixes(String arg0) { return null;} - - @Override - public String getPrefix(String arg0) {return null;} - - @Override - public String getNamespaceURI(String arg0) { - if("md".equals(arg0)) { - return "http://www.medico.com/schemas/record"; - } else if ("xacml-context".equals(arg0)) { - return "urn:oasis:names:tc:xacml:3.0:context:schema:os"; - } else if ("xsi".equals(arg0)) { - return "http://www.w3.org/2001/XMLSchema-instance"; - } - return null; - } - }; - - - - // - // URIs for attribute categroies - // - - FunctionArgumentAttributeValue attrUriNull = null; - FunctionArgumentAttributeValue attrUriEmpty = null; - FunctionArgumentAttributeValue attrUriResources = null; - FunctionArgumentAttributeValue attrUriAction = null; - FunctionArgumentAttributeValue attrUriNotInRequest = null; - FunctionArgumentAttributeValue attrUriNotCategory = null; - - - - // - // XML Contents - // - - FunctionArgumentAttributeValue attrXnull = null; - FunctionArgumentAttributeValue attrXEmpty = null; - FunctionArgumentAttributeValue attrXSimpson = null; - FunctionArgumentAttributeValue attrXSpringer = null; - FunctionArgumentAttributeValue attrXContentSimpson = null; - FunctionArgumentAttributeValue attrXContentSpringer = null; - FunctionArgumentAttributeValue attrXBadXML = null; - - - - - - - // - // REQUEST objects available for use in tests - // - Request requestEmpty = new StdMutableRequest(); - Request requestMdRecord = null; - Request requestDoubleResources = null; - Request requestDoubleContent = null; - Request requestResourceActionContent = null; - Request requestContentInAction = null; - - - - - /** - * Set up all variables in one place because it is complicated (lots of steps needed for each attribute) - */ - public FunctionDefinitionAccessPermittedTest() { - try { - - - // create Function Attributes for URIs - attrUriNull = null; - attrUriEmpty = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("")); - attrUriResources = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("urn:oasis:names:tc:xacml:3.0:attribute-category:resource")); - attrUriAction = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("urn:oasis:names:tc:xacml:3.0:attribute-category:action")); - attrUriNotInRequest = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("NoSuchURI")); - attrUriNotCategory = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("urn:oasis:names:tc:xacml:1.0:resource:resource-id")); - - // create Function Attributes for XML Strings - attrXnull = new FunctionArgumentAttributeValue(null); - attrXEmpty = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); - attrXSimpson = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(reqStrMdRecordSimpson)); - attrXSpringer = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(reqStrMdRecordSpringer)); - attrXContentSimpson = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(reqStrContentMdRecordSimpson)); - attrXContentSpringer = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(reqStrContentMdRecordSpringer)); - attrXBadXML = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(reqStrMalformedContent)); - - - - // Request objects - // to create a Request object the easiest way is to put the xml into a file and use the DOMRequest to load it. - - // single Content in the Resources section (normal valid request) - String reqString = reqStrMainResourceStart + reqStrContentMdRecordSimpson + reqStrResourceAllEnd; - File tFile = File.createTempFile("functionJunit", "request"); - BufferedWriter bw = new BufferedWriter(new FileWriter(tFile)); - bw.append(reqString); - bw.flush(); - bw.close(); - requestMdRecord = DOMRequest.load(tFile); - tFile.delete(); - - // Resources included twice - reqString = reqStrMainResourceStart + reqStrContentMdRecordSimpson + reqStrResourceEnd + reqStrResourceStart + reqStrContentMdRecordSimpson +reqStrResourceAllEnd; - tFile = File.createTempFile("functionJunit", "request"); - bw = new BufferedWriter(new FileWriter(tFile)); - bw.append(reqString); - bw.flush(); - bw.close(); - requestDoubleResources = DOMRequest.load(tFile); - tFile.delete(); - - // Content included twice - error - reqString = reqStrMainResourceStart + reqStrContentMdRecordSimpson + reqStrContentMdRecordSimpson +reqStrResourceAllEnd; - tFile = File.createTempFile("functionJunit", "request"); - bw = new BufferedWriter(new FileWriter(tFile)); - bw.append(reqString); - bw.flush(); - bw.close(); - try { - requestDoubleContent = DOMRequest.load(tFile); - tFile.delete(); - } catch (com.att.research.xacml.std.dom.DOMStructureException e) { - // this is what it should do, so just continue - } catch (Exception e) { - fail("Unexpected exception for bad XML, e="+e); - } - - // content included in both Resource and Action - ok - reqString = reqStrMainResourceStart + reqStrContentMdRecordSimpson + reqStrResourceEnd + reqStrActionStart + reqStrContentMdRecordSimpson + reqStrActionEnd + reqStrMainEnd; - tFile = File.createTempFile("functionJunit", "request"); - bw = new BufferedWriter(new FileWriter(tFile)); - bw.append(reqString); - bw.flush(); - bw.close(); - requestResourceActionContent = DOMRequest.load(tFile); - tFile.delete(); - - // Content included only in Action - missing content produces non-error result according to spec - reqString = reqStrMainResourceStart + reqStrResourceEnd + reqStrActionStart + reqStrContentMdRecordSimpson + reqStrActionEnd + reqStrMainEnd; - tFile = File.createTempFile("functionJunit", "request"); - bw = new BufferedWriter(new FileWriter(tFile)); - bw.append(reqString); - bw.flush(); - bw.close(); - requestContentInAction = DOMRequest.load(tFile); - tFile.delete(); - - - - // Test that Bad XML is caught - @SuppressWarnings("unused") - Request requestContentMisplaced = null; - @SuppressWarnings("unused") - Request requestMalformedContent = null; - - - // Bad XML - Content not under a Category - reqString = reqStrMainStart + reqStrContentMdRecordSimpson + reqStrResourceStart + reqStrResourceEnd + reqStrActionStart + reqStrActionEnd + reqStrMainEnd; - tFile = File.createTempFile("functionJunit", "request"); - bw = new BufferedWriter(new FileWriter(tFile)); - bw.append(reqString); - bw.flush(); - bw.close(); - try { - requestContentMisplaced = DOMRequest.load(tFile); - tFile.delete(); - } catch (com.att.research.xacml.std.dom.DOMStructureException e) { - // this is what it should do, so just continue - } catch (Exception e) { - fail("Unexpected exception for bad XML, e="+e); - } - - // Bad XML - Content is not valid XML - reqString = reqStrMainResourceStart + reqStrMalformedContent + reqStrResourceAllEnd; - tFile = File.createTempFile("functionJunit", "request"); - bw = new BufferedWriter(new FileWriter(tFile)); - bw.append(reqString); - bw.flush(); - bw.close(); - try { - requestMalformedContent = DOMRequest.load(tFile); - tFile.delete(); - } catch (com.att.research.xacml.std.dom.DOMStructureException e) { - // this is what it should do, so just continue - } catch (Exception e) { - fail("Unexpected exception for bad XML, e="+e); - } - - } catch (Exception e) { - fail("Constructor initializing variables, e="+ e + " cause="+e.getCause()); - } - - } - - - - - - - - - @Ignore //@Test - public void testAccess_permitted() { - - ExpressionResult res = null; - Boolean resValue = null; - - FunctionDefinitionAccessPermitted fd = (FunctionDefinitionAccessPermitted) StdFunctions.FD_ACCESS_PERMITTED; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_ACCESS_PERMITTED, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - - // successful invoke returns true - arguments.clear(); - arguments.add(attrUriResources); - arguments.add(attrXEmpty); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - - - // successful invoke returns false - - - // URI not in Request (ok - evaluate anyway) - - // test for infinite loop - - // second arg ok both with and without tag - arguments.clear(); - arguments.add(attrUriResources); - arguments.add(attrXContentSpringer); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - arguments.clear(); - arguments.add(attrUriResources); - arguments.add(attrXSpringer); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // second arg not valid XML - arguments.clear(); - arguments.add(attrUriResources); - arguments.add(attrXBadXML); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:access-permitted Parsing of XML string failed. Cause='The element type \"md:hospital_info\" must be terminated by the matching end-tag \"\".'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null Evaluation Context - arguments.clear(); - arguments.add(attrUriNotCategory); - arguments.add(attrXContentSimpson); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:access-permitted First argument must be a urn for an attribute-category, not 'urn:oasis:names:tc:xacml:1.0:resource:resource-id", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null Request - arguments.clear(); - arguments.add(attrUriAction); - arguments.add(attrXContentSimpson); - res = fd.evaluate(new StdEvaluationContext(null, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:access-permitted Got null Request in EvaluationContext", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // first arg not uri - arguments.clear(); - arguments.add(attrUriNotCategory); - arguments.add(attrXContentSimpson); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:access-permitted First argument must be a urn for an attribute-category, not 'urn:oasis:names:tc:xacml:1.0:resource:resource-id", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // first arg not attribute-category urn - arguments.clear(); - arguments.add(attrXContentSimpson); - arguments.add(attrXContentSimpson); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:access-permitted Expected data type 'anyURI' saw 'string'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second arg not string - arguments.clear(); - arguments.add(attrUriAction); - arguments.add(attrUriAction); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:access-permitted Expected data type 'string' saw 'anyURI'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // too few args - arguments.clear(); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:access-permitted Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrXContentSimpson); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:access-permitted Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // too many args - arguments.clear(); - arguments.add(attrUriEmpty); - arguments.add(attrXContentSimpson); - arguments.add(attrXContentSimpson); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:access-permitted Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionArithmeticTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionArithmeticTest.java deleted file mode 100644 index 69e8744f7..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionArithmeticTest.java +++ /dev/null @@ -1,717 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionArithmeticTest { - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - @Test - public void testInteger_add() { - - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - FunctionArgumentAttributeValue attrBadType = null; - try { - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); - attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.1)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_INTEGER_ADD; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_INTEGER_ADD, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - - // test normal add - arguments.add(attr1); - arguments.add(attr2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - BigInteger resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("2"), resValue); - - arguments.clear(); - arguments.add(attr1); - arguments.add(attrBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:integer-add Expected data type 'integer' saw 'double' at arg index 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - @Test - public void testDouble_add() { - - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - - try { - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.5)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(2.5)); - } catch (Exception e) { - fail("creating attributes e="+e); - } - - FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_DOUBLE_ADD; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DOUBLE_ADD, fd.getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - - // test normal add - arguments.add(attr1); - arguments.add(attr2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Double resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(4.0), resValue); - - } - - - @Test - public void testInteger_subtract() { - - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - try { - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(6)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_INTEGER_SUBTRACT; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_INTEGER_SUBTRACT, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - - // test normal - arguments.add(attr1); - arguments.add(attr2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - BigInteger resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("5"), resValue); - - } - - - @Test - public void testDouble_subtract() { - - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - - try { - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(8.5)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(2.3)); - } catch (Exception e) { - fail("creating attributes e="+e); - } - - FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_DOUBLE_SUBTRACT; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DOUBLE_SUBTRACT, fd.getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - - // test normal - arguments.add(attr1); - arguments.add(attr2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Double resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(6.2), resValue); - - } - - - @Test - public void testInteger_multiply() { - - FunctionArgumentAttributeValue attr0 = null; - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - try { - attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(5)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(2)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_INTEGER_MULTIPLY; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_INTEGER_MULTIPLY, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - - // test normal - arguments.add(attr1); - arguments.add(attr2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - BigInteger resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("10"), resValue); - - - // test 0 - arguments.clear(); - arguments.add(attr1); - arguments.add(attr0); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("0"), resValue); - } - - - @Test - public void testDouble_multiply() { - - FunctionArgumentAttributeValue attr0 = null; - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - - try { - attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(0)); - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.5)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(2.5)); - } catch (Exception e) { - fail("creating attributes e="+e); - } - - FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_DOUBLE_MULTIPLY; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DOUBLE_MULTIPLY, fd.getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - - // test normal add - arguments.add(attr1); - arguments.add(attr2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Double resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(3.75), resValue); - - // test multiply by 0 - arguments.clear(); - arguments.add(attr1); - arguments.add(attr0); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(0), resValue); - } - - - @Test - public void testInteger_divide() { - - FunctionArgumentAttributeValue attr0 = null; - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - try { - attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(5)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(2)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_INTEGER_DIVIDE; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_INTEGER_DIVIDE, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - - // test normal - arguments.add(attr1); - arguments.add(attr2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - BigInteger resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("2"), resValue); - - - // test 0 - arguments.clear(); - arguments.add(attr1); - arguments.add(attr0); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:integer-divide Divide by 0 error: 5, 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - @Test - public void testDouble_divide() { - - FunctionArgumentAttributeValue attr0 = null; - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - - try { - attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(0)); - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.5)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(2.5)); - - } catch (Exception e) { - fail("creating attributes e="+e); - } - FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_DOUBLE_DIVIDE; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DOUBLE_DIVIDE, fd.getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - - // test normal - arguments.add(attr1); - arguments.add(attr2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Double resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(0.6), resValue); - - // test multiply by 0 - arguments.clear(); - arguments.add(attr1); - arguments.add(attr0); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:double-divide Divide by 0 error: 1.5, 0.0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - - - @Test - public void testInteger_mod() { - - FunctionArgumentAttributeValue attr0 = null; - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - try { - attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(28)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(5)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_INTEGER_MOD; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_INTEGER_MOD, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - - // test normal - arguments.add(attr1); - arguments.add(attr2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - BigInteger resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("3"), resValue); - - - // test 0 - arguments.clear(); - arguments.add(attr1); - arguments.add(attr0); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:integer-mod Divide by 0 error: 28, 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - @Test - public void testInteger_abs() { - - FunctionArgumentAttributeValue attr0 = null; - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attrM1 = null; - try { - attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(5)); - attrM1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(-7)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_INTEGER_ABS; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_INTEGER_ABS, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - - // test normal - arguments.add(attr1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - BigInteger resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("5"), resValue); - - arguments.clear(); - arguments.add(attrM1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("7"), resValue); - - arguments.clear(); - arguments.add(attr0); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("0"), resValue); - } - - - @Test - public void testDouble_abs() { - - FunctionArgumentAttributeValue attr0 = null; - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - - try { - attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(0)); - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.5)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-2.5)); - - } catch (Exception e) { - fail("creating attributes e="+e); - } - - FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_DOUBLE_ABS; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DOUBLE_ABS, fd.getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - - // test normal - arguments.add(attr1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Double resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(1.5), resValue); - - arguments.clear(); - arguments.add(attr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(2.5), resValue); - - arguments.clear(); - arguments.add(attr0); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(0), resValue); - - } - - - @Test - public void testDouble_round() { - - FunctionArgumentAttributeValue attr0 = null; - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - FunctionArgumentAttributeValue attr3 = null; - FunctionArgumentAttributeValue attr4 = null; - FunctionArgumentAttributeValue attr5 = null; - FunctionArgumentAttributeValue attr6 = null; - try { - attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(0)); - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.5)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.49)); - attr3 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.51)); - attr4 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-2.5)); - attr5 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-2.49)); - attr6 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-2.51)); - } catch (Exception e) { - fail("creating attributes e="+e); - } - - - - FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_ROUND; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_ROUND, fd.getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - - // test normal - arguments.add(attr0); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Double resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(0), resValue); - - arguments.clear(); - arguments.add(attr1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(2), resValue); - - arguments.clear(); - arguments.add(attr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(1), resValue); - - arguments.clear(); - arguments.add(attr3); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(2), resValue); - - arguments.clear(); - arguments.add(attr4); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(-2), resValue); - - arguments.clear(); - arguments.add(attr5); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(-2), resValue); - - arguments.clear(); - arguments.add(attr6); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(-3), resValue); - } - - - @Test - public void testDouble_floor() { - FunctionArgumentAttributeValue attr0 = null; - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - FunctionArgumentAttributeValue attr3 = null; - FunctionArgumentAttributeValue attr4 = null; - FunctionArgumentAttributeValue attr5 = null; - FunctionArgumentAttributeValue attr6 = null; - try { - attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(0)); - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.5)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.49)); - attr3 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.51)); - attr4 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-2.5)); - attr5 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-2.49)); - attr6 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-2.51)); - } catch (Exception e) { - fail("creating attributes e="+e); - } - - FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_FLOOR; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_FLOOR, fd.getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - - // test normal - arguments.add(attr0); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Double resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(0), resValue); - - arguments.clear(); - arguments.add(attr1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(1), resValue); - - arguments.clear(); - arguments.add(attr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(1), resValue); - - arguments.clear(); - arguments.add(attr3); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(1), resValue); - - arguments.clear(); - arguments.add(attr4); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(-3), resValue); - - arguments.clear(); - arguments.add(attr5); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(-3), resValue); - - arguments.clear(); - arguments.add(attr6); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(-3), resValue); - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagIsInTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagIsInTest.java deleted file mode 100644 index ecb870164..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagIsInTest.java +++ /dev/null @@ -1,221 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.StdAttributeValue; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.Bag; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentBag; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionBagIsInTest { - - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - - @Test - public void testString() { - String v1 = new String("abc"); - String v2 = new String("def"); - String notInBag = new String("lmnop"); - String sameValueV1 = new String("abc"); - Integer vOtherType = new Integer(11); - - - FunctionArgumentAttributeValue attrV1 = null; - FunctionArgumentAttributeValue attrV2 = null; - FunctionArgumentAttributeValue attrNotInBag = null; - FunctionArgumentAttributeValue attrSameValueV1 = null; - FunctionArgumentAttributeValue attrOtherType = null; - try { - attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); - attrV2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v2)); - attrNotInBag = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(notInBag)); - attrSameValueV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(sameValueV1)); - attrOtherType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(vOtherType)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - Bag bag0 = new Bag(); - Bag bag1 = new Bag(); - bag1.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v1)); - Bag bag2 = new Bag(); - bag2.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v1)); - bag2.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v2));; - - - - FunctionArgumentBag attrBag0 = new FunctionArgumentBag(bag0); - FunctionArgumentBag attrBag1 = new FunctionArgumentBag(bag1); - FunctionArgumentBag attrBag2 = new FunctionArgumentBag(bag2); - - - - FunctionDefinitionBagIsIn fd = (FunctionDefinitionBagIsIn) StdFunctions.FD_STRING_IS_IN; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_IS_IN, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // element is in bag - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBag2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // element not in bag - arguments.clear(); - arguments.add(attrNotInBag); - arguments.add(attrBag2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // different element with the same value is in bag - arguments.clear(); - arguments.add(attrSameValueV1); - arguments.add(attrBag2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // empty bag - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBag0); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // missing arg - arguments.clear(); - arguments.add(attrSameValueV1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-is-in Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // 1st arg is bag - arguments.clear(); - arguments.add(attrBag1); - arguments.add(attrBag2); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-is-in Expected a simple value, saw a bag", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // 2nd arg not bag - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrV2); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-is-in Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // first arg null - arguments.clear(); - arguments.add(null); - arguments.add(attrBag2); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-is-in Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // 2nd arg null - arguments.clear(); - arguments.add(attrV1); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-is-in Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // first arg type does not match bag elements - arguments.clear(); - arguments.add(attrOtherType); - arguments.add(attrBag2); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-is-in Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bag has mixed element types -// behavior not specified for this case in spec. It ASSUMES that all elements in bag are same type. - - } - - - - - // - // - // REST OF DATA TYPES OMITTED - // because they "should" all work the same - // - // - - - - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagOneAndOnlyTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagOneAndOnlyTest.java deleted file mode 100644 index e45dfb99c..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagOneAndOnlyTest.java +++ /dev/null @@ -1,224 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.ArrayList; -import java.util.List; -import java.math.BigInteger; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.StdAttributeValue; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.Bag; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentBag; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionBagOneAndOnlyTest { - - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - - @Test - public void testString() { - String v1 = new String("abc"); - String v2 = new String("def"); - BigInteger vOtherType = BigInteger.valueOf(11); - - Bag bag0 = new Bag(); - Bag bag1 = new Bag(); - bag1.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v1)); - Bag bag2 = new Bag(); - bag2.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v1)); - bag2.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v2)); - Bag bagOtherType = new Bag(); - bagOtherType.add(new StdAttributeValue(DataTypes.DT_INTEGER.getId(), vOtherType)); - - FunctionArgumentBag attrBag0 = new FunctionArgumentBag(bag0); - FunctionArgumentBag attrBag1 = new FunctionArgumentBag(bag1); - FunctionArgumentBag attrBag2 = new FunctionArgumentBag(bag2); - FunctionArgumentBag attrBagOtherType = new FunctionArgumentBag(bagOtherType); - - - FunctionDefinitionBagOneAndOnly fd = (FunctionDefinitionBagOneAndOnly) StdFunctions.FD_STRING_ONE_AND_ONLY; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_ONE_AND_ONLY, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - - - // bag with only one - arguments.clear(); - arguments.add(attrBag1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - String resValue = (String)res.getValue().getValue(); - assertEquals(v1, resValue); - - // null bag - arguments.clear(); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-one-and-only Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bag with exactly one but of other type in it - arguments.clear(); - arguments.add(attrBagOtherType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-one-and-only Element in bag of wrong type. Expected string got integer", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bag with none - arguments.clear(); - arguments.add(attrBag0); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-one-and-only Expected 1 but Bag has 0 elements", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bag with multiple - arguments.clear(); - arguments.add(attrBag2); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-one-and-only Expected 1 but Bag has 2 elements", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - @Test - public void testBoolean() { - Boolean v1 = new Boolean(true); - Boolean v2 = new Boolean(false); - BigInteger vOtherType = BigInteger.valueOf(11); - - Bag bag0 = new Bag(); - Bag bag1 = new Bag(); - bag1.add(new StdAttributeValue(DataTypes.DT_BOOLEAN.getId(), v1)); - Bag bag2 = new Bag(); - bag2.add(new StdAttributeValue(DataTypes.DT_BOOLEAN.getId(), v1)); - bag2.add(new StdAttributeValue(DataTypes.DT_BOOLEAN.getId(), v2)); - Bag bagOtherType = new Bag(); - bagOtherType.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), vOtherType)); - - - FunctionArgumentBag attrBag0 = new FunctionArgumentBag(bag0); - FunctionArgumentBag attrBag1 = new FunctionArgumentBag(bag1); - FunctionArgumentBag attrBag2 = new FunctionArgumentBag(bag2); - FunctionArgumentBag attrBagOtherType = new FunctionArgumentBag(bagOtherType); - - - FunctionDefinitionBagOneAndOnly fd = (FunctionDefinitionBagOneAndOnly) StdFunctions.FD_BOOLEAN_ONE_AND_ONLY; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_BOOLEAN_ONE_AND_ONLY, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - - - // bag with only one - arguments.clear(); - arguments.add(attrBag1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(true), resValue); - - // null bag - arguments.clear(); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:boolean-one-and-only Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bag with exactly one but of other type in it - arguments.clear(); - arguments.add(attrBagOtherType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:boolean-one-and-only Element in bag of wrong type. Expected boolean got string", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bag with none - arguments.clear(); - arguments.add(attrBag0); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:boolean-one-and-only Expected 1 but Bag has 0 elements", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bag with multiple - arguments.clear(); - arguments.add(attrBag2); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:boolean-one-and-only Expected 1 but Bag has 2 elements", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - // - // - // REST OF DATA TYPES OMITTED - // because they "should" all work the same - // - // - - - - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagSizeTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagSizeTest.java deleted file mode 100644 index 7cb3e0488..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagSizeTest.java +++ /dev/null @@ -1,158 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.StdAttributeValue; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.Bag; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentBag; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionBagSizeTest { - - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - - @Test - public void testString() { - String v1 = new String("abc"); - String v2 = new String("def"); - Integer vOtherType = new Integer(11); - - - - Bag bag0 = new Bag(); - Bag bag1 = new Bag(); - bag1.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v1)); - Bag bag2 = new Bag(); - bag2.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v1)); - bag2.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v2)); - Bag bagOtherType = new Bag(); - bagOtherType.add(new StdAttributeValue(DataTypes.DT_INTEGER.getId(), vOtherType)); - - - FunctionArgumentBag attrBag0 = new FunctionArgumentBag(bag0); - FunctionArgumentBag attrBag1 = new FunctionArgumentBag(bag1); - FunctionArgumentBag attrBag2 = new FunctionArgumentBag(bag2); - FunctionArgumentBag attrBagOtherType = new FunctionArgumentBag(bagOtherType); - - - FunctionDefinitionBagSize fd = (FunctionDefinitionBagSize) StdFunctions.FD_STRING_BAG_SIZE; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_BAG_SIZE, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - - - // bag with only one - arguments.clear(); - arguments.add(attrBag1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.math.BigInteger.class, res.getValue().getValue().getClass()); - BigInteger resValue = (BigInteger)res.getValue().getValue(); - assertEquals(BigInteger.valueOf(1), resValue); - - // null bag - arguments.clear(); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-bag-size Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bag with exactly one but of other type in it - arguments.clear(); - arguments.add(attrBagOtherType); - res = fd.evaluate(null, arguments); - // NOTE: Size does not care about content type! - assertTrue(res.isOk()); - assertEquals(java.math.BigInteger.class, res.getValue().getValue().getClass()); - resValue = (BigInteger)res.getValue().getValue(); - assertEquals(BigInteger.valueOf(1), resValue); - - // bag with none - arguments.clear(); - arguments.add(attrBag0); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.math.BigInteger.class, res.getValue().getValue().getClass()); - resValue = (BigInteger)res.getValue().getValue(); - assertEquals(BigInteger.valueOf(0), resValue); - - // bag with multiple - arguments.clear(); - arguments.add(attrBag2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.math.BigInteger.class, res.getValue().getValue().getClass()); - resValue = (BigInteger)res.getValue().getValue(); - assertEquals(BigInteger.valueOf(2), resValue); - } - - - - - - - - // - // - // REST OF DATA TYPES OMITTED - // because they "should" all work the same - // - // - - - - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagTest.java deleted file mode 100644 index 0f1a6009c..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBagTest.java +++ /dev/null @@ -1,547 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.junit.Test; - -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.Bag; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionBagTest { - - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - - FunctionArgumentAttributeValue attrInteger = null; - FunctionArgumentAttributeValue attrString = null; - - public FunctionDefinitionBagTest() { - try { - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1111111111)); - attrString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("a string value")); - } catch (Exception e) { - fail("creating attributes e="+e); - } - } - - @Test - public void testString() { - - String s1 = "abc"; - String s2 = "def"; - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - try { - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(s1)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(s2)); - } catch (Exception e) { - fail("creating attributes e="+e); - } - - FunctionDefinitionBag fd = (FunctionDefinitionBag) StdFunctions.FD_STRING_BAG; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_BAG, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertTrue(fd.returnsBag()); - - // bag with only one - arguments.clear(); - arguments.add(attr1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Bag bag = res.getBag(); - assertNotNull(bag); - Iterator> it = bag.getAttributeValues(); - assertEquals(1, bag.size()); - AttributeValue attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - - // zero args => empty bag - arguments.clear(); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - assertEquals(0, bag.size()); - - - // null argument - arguments.clear(); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-bag Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // argument of other type - arguments.clear(); - arguments.add(attrInteger); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-bag Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // 2 args (check response is correct) - arguments.clear(); - arguments.add(attr1); - arguments.add(attr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(2, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(s2, attrValueObject.getValue()); - - // duplicate args (verify return) - arguments.clear(); - arguments.add(attr1); - arguments.add(attr2); - arguments.add(attr1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(3, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(s2, attrValueObject.getValue()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - - // lots of args - arguments.clear(); - for (int i = 0; i < 1000; i++) { - arguments.add(attr1); - } - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(1000, bag.size()); - - } - - - @Test - public void testBoolean() { - - Boolean s1 = true; - Boolean s2 = false; - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - try { - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(s1)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(s2)); - } catch (Exception e) { - fail("creating attributes e="+e); - } - - FunctionDefinitionBag fd = (FunctionDefinitionBag) StdFunctions.FD_BOOLEAN_BAG; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_BOOLEAN_BAG, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertTrue(fd.returnsBag()); - - // bag with only one - arguments.clear(); - arguments.add(attr1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Bag bag = res.getBag(); - assertNotNull(bag); - Iterator> it = bag.getAttributeValues(); - assertEquals(1, bag.size()); - AttributeValue attrValueObject = it.next(); - assertEquals(DataTypes.DT_BOOLEAN.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - - // zero args => empty bag - arguments.clear(); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - assertEquals(0, bag.size()); - - - // null argument - arguments.clear(); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:boolean-bag Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // argument of other type - arguments.clear(); - arguments.add(attrInteger); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:boolean-bag Expected data type 'boolean' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // 2 args (check response is correct) - arguments.clear(); - arguments.add(attr1); - arguments.add(attr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(2, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_BOOLEAN.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_BOOLEAN.getId(), attrValueObject.getDataTypeId()); - assertEquals(s2, attrValueObject.getValue()); - - // duplicate args (verify return) - arguments.clear(); - arguments.add(attr1); - arguments.add(attr2); - arguments.add(attr1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(3, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_BOOLEAN.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_BOOLEAN.getId(), attrValueObject.getDataTypeId()); - assertEquals(s2, attrValueObject.getValue()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_BOOLEAN.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - - // lots of args - arguments.clear(); - for (int i = 0; i < 1000; i++) { - arguments.add(attr1); - } - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(1000, bag.size()); - - } - - - - @Test - public void testInteger() { - - BigInteger s1 = new BigInteger("123"); - BigInteger s2 = new BigInteger("456"); - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - try { - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(s1)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(s2)); - } catch (Exception e) { - fail("creating attributes e="+e); - } - - FunctionDefinitionBag fd = (FunctionDefinitionBag) StdFunctions.FD_INTEGER_BAG; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_INTEGER_BAG, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertTrue(fd.returnsBag()); - - // bag with only one - arguments.clear(); - arguments.add(attr1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Bag bag = res.getBag(); - assertNotNull(bag); - Iterator> it = bag.getAttributeValues(); - assertEquals(1, bag.size()); - AttributeValue attrValueObject = it.next(); - assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - - // zero args => empty bag - arguments.clear(); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - assertEquals(0, bag.size()); - - - // null argument - arguments.clear(); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:integer-bag Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // argument of other type - arguments.clear(); - arguments.add(attrString); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:integer-bag Expected data type 'integer' saw 'string'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // 2 args (check response is correct) - arguments.clear(); - arguments.add(attr1); - arguments.add(attr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(2, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); - assertEquals(s2, attrValueObject.getValue()); - - // duplicate args (verify return) - arguments.clear(); - arguments.add(attr1); - arguments.add(attr2); - arguments.add(attr1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(3, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); - assertEquals(s2, attrValueObject.getValue()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - - // lots of args - arguments.clear(); - for (int i = 0; i < 1000; i++) { - arguments.add(attr1); - } - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(1000, bag.size()); - - } - - - - - @Test - public void testDouble() { - - Double s1 = 123.45; - Double s2 = 678.901; - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr2 = null; - try { - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(s1)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(s2)); - } catch (Exception e) { - fail("creating attributes e="+e); - } - - FunctionDefinitionBag fd = (FunctionDefinitionBag) StdFunctions.FD_DOUBLE_BAG; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DOUBLE_BAG, fd.getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertTrue(fd.returnsBag()); - - // bag with only one - arguments.clear(); - arguments.add(attr1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Bag bag = res.getBag(); - assertNotNull(bag); - Iterator> it = bag.getAttributeValues(); - assertEquals(1, bag.size()); - AttributeValue attrValueObject = it.next(); - assertEquals(DataTypes.DT_DOUBLE.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - - // zero args => empty bag - arguments.clear(); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - assertEquals(0, bag.size()); - - - // null argument - arguments.clear(); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:double-bag Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // argument of other type - arguments.clear(); - arguments.add(attrInteger); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:double-bag Expected data type 'double' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // 2 args (check response is correct) - arguments.clear(); - arguments.add(attr1); - arguments.add(attr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(2, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_DOUBLE.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_DOUBLE.getId(), attrValueObject.getDataTypeId()); - assertEquals(s2, attrValueObject.getValue()); - - // duplicate args (verify return) - arguments.clear(); - arguments.add(attr1); - arguments.add(attr2); - arguments.add(attr1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(3, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_DOUBLE.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_DOUBLE.getId(), attrValueObject.getDataTypeId()); - assertEquals(s2, attrValueObject.getValue()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_DOUBLE.getId(), attrValueObject.getDataTypeId()); - assertEquals(s1, attrValueObject.getValue()); - - // lots of args - arguments.clear(); - for (int i = 0; i < 1000; i++) { - arguments.add(attr1); - } - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(1000, bag.size()); - - } - - - - - - // - // - // REST OF DATA TYPES OMITTED - // because they "should" all work the same - // - // - - - - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBaseTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBaseTest.java deleted file mode 100644 index 10975f469..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionBaseTest.java +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.api.XACML3; -import com.att.research.xacmlatt.pdp.policy.FunctionDefinition; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test functions in the abstract FunctionDefinitionSimpleTest class. - * Functions are tested by creating instances of other classes that should have appropriate properties to verify all variations of the responses expected. - * - * Note: we do not test getDataTypeId() because all it does is get the String out of the Identity object and we assume that the Data Type Identity objects - * are tested enough in everything else that any errors in them will be found and fixed quickly. - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionBaseTest { - /** - * getId() is pretty trivial, so verifying one should be enough to check that the mechanism is working ok - */ - @Test - public void testGetId() { - FunctionDefinition fd = StdFunctions.FD_STRING_EQUAL; - Identifier id = fd.getId(); - assertTrue(XACML3.ID_FUNCTION_STRING_EQUAL.stringValue().equals(id.stringValue()) ); - } - - /** - * check an instance of every result type that we can deal with - */ - @Test - public void testGetDataType() { - -//?? Need functions that return each of these data types except for Boolean which is returned by any of the EQUAL functions - FunctionDefinition fdstring = StdFunctions.FD_STRING_NORMALIZE_SPACE; - assertEquals(XACML3.ID_DATATYPE_STRING, fdstring.getDataTypeId()); - - FunctionDefinition fdboolean = StdFunctions.FD_STRING_EQUAL; - assertEquals(XACML3.ID_DATATYPE_BOOLEAN, fdboolean.getDataTypeId()); - - FunctionDefinition fdinteger = StdFunctions.FD_INTEGER_ADD; - assertEquals(XACML3.ID_DATATYPE_INTEGER, fdinteger.getDataTypeId()); - - FunctionDefinition fddouble = StdFunctions.FD_DOUBLE_ADD; - assertEquals(XACML3.ID_DATATYPE_DOUBLE, fddouble.getDataTypeId()); - - FunctionDefinition fddate = StdFunctions.FD_DATE_BAG; - assertEquals(XACML3.ID_DATATYPE_DATE, fddate.getDataTypeId()); - - FunctionDefinition fdtime = StdFunctions.FD_TIME_BAG; - assertEquals(XACML3.ID_DATATYPE_TIME, fdtime.getDataTypeId()); - - FunctionDefinition fddateTime = StdFunctions.FD_DATETIME_BAG; - assertEquals(XACML3.ID_DATATYPE_DATETIME, fddateTime.getDataTypeId()); - - FunctionDefinition fddayTimeDuration = StdFunctions.FD_DAYTIMEDURATION_FROM_STRING; - assertEquals(XACML3.ID_DATATYPE_DAYTIMEDURATION, fddayTimeDuration.getDataTypeId()); - - FunctionDefinition fdyearMonthDuration = StdFunctions.FD_YEARMONTHDURATION_FROM_STRING; - assertEquals(XACML3.ID_DATATYPE_YEARMONTHDURATION, fdyearMonthDuration.getDataTypeId()); - - FunctionDefinition fdanyURI = StdFunctions.FD_ANYURI_FROM_STRING; - assertEquals(XACML3.ID_DATATYPE_ANYURI, fdanyURI.getDataTypeId()); - - FunctionDefinition fdhexBinary = StdFunctions.FD_HEXBINARY_UNION; - assertEquals(XACML3.ID_DATATYPE_HEXBINARY, fdhexBinary.getDataTypeId()); - - FunctionDefinition fdbase64Binary = StdFunctions.FD_BASE64BINARY_UNION; - assertEquals(XACML3.ID_DATATYPE_BASE64BINARY, fdbase64Binary.getDataTypeId()); - - FunctionDefinition fdrfc822Name = StdFunctions.FD_RFC822NAME_FROM_STRING; - assertEquals(XACML3.ID_DATATYPE_RFC822NAME, fdrfc822Name.getDataTypeId()); - - FunctionDefinition fdx500Name = StdFunctions.FD_X500NAME_FROM_STRING; - assertEquals(XACML3.ID_DATATYPE_X500NAME, fdx500Name.getDataTypeId()); - -//TODO - There are currently no functions that return XPathExpression objects -// FunctionDefinition fdxpathExpression = StdFunctions.FD_XPATHEXPRESSION_FROM_STRING; -// assertEquals(XACML3.ID_DATATYPE_XPATHEXPRESSION, fdxpathExpression.getDataTypeId()); - - FunctionDefinition fdipAddress = StdFunctions.FD_IPADDRESS_FROM_STRING; - assertEquals(XACML3.ID_DATATYPE_IPADDRESS, fdipAddress.getDataTypeId()); - - FunctionDefinition fddnsName = StdFunctions.FD_DNSNAME_FROM_STRING; - assertEquals(XACML3.ID_DATATYPE_DNSNAME, fddnsName.getDataTypeId()); - } - - /** - * check the type of return, single vs multiple values - */ - @Test - public void testReturnsBag() { - FunctionDefinition fdNotBag = StdFunctions.FD_BOOLEAN_EQUAL; - assertFalse(fdNotBag.returnsBag()); - - FunctionDefinitionBag fdBag = (FunctionDefinitionBag) StdFunctions.FD_STRING_BAG; - assertTrue(fdBag.returnsBag()); - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionComparisonTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionComparisonTest.java deleted file mode 100644 index 9c3cc7faf..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionComparisonTest.java +++ /dev/null @@ -1,1366 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacml.std.datatypes.ISO8601Date; -import com.att.research.xacml.std.datatypes.ISO8601DateTime; -import com.att.research.xacml.std.datatypes.ISO8601Time; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test FunctionDefinitionComparison - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionComparisonTest { - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - FunctionArgumentAttributeValue stringAttr1 = null; - FunctionArgumentAttributeValue stringAttr1a = null; - FunctionArgumentAttributeValue stringAttr2 = null; - FunctionArgumentAttributeValue stringAttrNeg1 = null; - - - FunctionArgumentAttributeValue intAttr1 = null; - FunctionArgumentAttributeValue intAttr1a = null; - FunctionArgumentAttributeValue intAttr2 = null; - FunctionArgumentAttributeValue intAttr0 = null; - FunctionArgumentAttributeValue intAttrNeg1 = null; - - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr1a = null; - FunctionArgumentAttributeValue attr2 = null; - FunctionArgumentAttributeValue attrNeg1 = null; - - FunctionArgumentAttributeValue attrDateToday = null; - FunctionArgumentAttributeValue attrDateSameDay = null; - FunctionArgumentAttributeValue attrDateTommorrow = null; - FunctionArgumentAttributeValue attrDateYesterday = null; - FunctionArgumentAttributeValue attrDateWithTimeZone = null; - FunctionArgumentAttributeValue attrDateNoTimeZone = null; - - - FunctionArgumentAttributeValue attrTimeToday = null; - FunctionArgumentAttributeValue attrTimeSameDay = null; - FunctionArgumentAttributeValue attrTimeTommorrow = null; - FunctionArgumentAttributeValue attrTimeYesterday = null; - FunctionArgumentAttributeValue attrTimeWithTimeZone = null; - FunctionArgumentAttributeValue attrTimeNoTimeZone = null; - - FunctionArgumentAttributeValue attrDateTimeToday = null; - FunctionArgumentAttributeValue attrDateTimeSameDay = null; - FunctionArgumentAttributeValue attrDateTimeTommorrow = null; - FunctionArgumentAttributeValue attrDateTimeYesterday = null; - FunctionArgumentAttributeValue attrDateTimeWithTimeZone = null; - FunctionArgumentAttributeValue attrDateTimeNoTimeZone = null; - - /** - * Set up some common variables on startup - */ - public FunctionDefinitionComparisonTest() { - try { - stringAttr1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc")); - stringAttr1a = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc")); - stringAttr2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("def")); - stringAttrNeg1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("AAA")); - - - intAttr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); - intAttr1a = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); - intAttr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(2)); - intAttr0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); - intAttrNeg1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(-1)); - - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.0)); - attr1a = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.0)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(2.4)); - attrNeg1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-1.0)); - - // create dates - Calendar calendar = Calendar.getInstance(); - Date today = calendar.getTime(); - Date longAgo = new Date(1234); - // create a date that is different than "today" but within the same day (i.e. has a different hour) - if (calendar.get(Calendar.HOUR_OF_DAY) > 3) { - calendar.set(Calendar.HOUR_OF_DAY, 3); - } else { - calendar.set(Calendar.HOUR_OF_DAY, 5); - } - Date todayPlus = calendar.getTime(); - calendar.add(Calendar.DATE, 1); - Date tommorrow = calendar.getTime(); - attrDateToday = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(today)); - attrDateSameDay = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(todayPlus)); - attrDateTommorrow = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(tommorrow)); - attrDateYesterday = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(longAgo)); - ISO8601Date isoDate = new ISO8601Date(1920, 5, 8); - attrDateNoTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(isoDate)); - isoDate = new ISO8601Date("GMT+00:02", 1920, 5, 8); - attrDateWithTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(isoDate)); - - // create Times - ISO8601Time isoTime = new ISO8601Time(14, 43, 12, 145); - attrTimeToday = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(isoTime)); - attrTimeSameDay = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(isoTime)); - isoTime = new ISO8601Time(18, 53, 34, 423); - attrTimeTommorrow = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(isoTime)); - isoTime = new ISO8601Time(7, 34, 6,543); - attrTimeYesterday = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(isoTime)); - isoTime = new ISO8601Time(12, 12, 12, 12); - attrTimeNoTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(isoTime)); - isoTime = new ISO8601Time("GMT:+00:03", 12, 12, 12, 12); - attrTimeWithTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(isoTime)); - - // create DateTimes - isoDate = new ISO8601Date(1920, 5, 8); - isoTime = new ISO8601Time( 18, 53, 34, 423); - ISO8601DateTime isoDateTime = new ISO8601DateTime((String)null, 1920, 5, 8, 18, 53, 34, 423); - attrDateTimeToday = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(isoDateTime)); - attrDateTimeSameDay = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(isoDateTime)); - isoTime = new ISO8601Time(20, 53, 34, 423); - isoDateTime = new ISO8601DateTime((String)null, 1920, 5, 8, 20, 53, 34, 423); - attrDateTimeTommorrow = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(isoDateTime)); - isoTime = new ISO8601Time(7, 34, 6,543); - isoDateTime = new ISO8601DateTime((String)null, 1920, 5, 8, 7, 34, 6, 543); - attrDateTimeYesterday = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(isoDateTime)); - isoTime = new ISO8601Time(12, 12, 12, 12); - isoDateTime = new ISO8601DateTime((String)null, 1920, 5, 8, 12, 12, 12, 12); - attrDateTimeNoTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(isoDateTime)); - isoTime = new ISO8601Time("GMT:+00:03", 12, 12, 12, 12); - isoDate = new ISO8601Date("GMT:+00:03", 1920, 5, 8); - isoDateTime = new ISO8601DateTime("GMT:+00:03", 1920, 5, 8, 12, 12, 12, 12); - attrDateTimeWithTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(isoDateTime)); - - - - - } catch (Exception e) { - fail("Error creating values e="+ e); - } - } - - /** - * String - */ - @Test - public void testString_GT() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_STRING_GREATER_THAN; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_GREATER_THAN, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(stringAttr1); - arguments.add(stringAttr1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // check first < second - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(stringAttr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first > second - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(stringAttrNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(intAttr1); - arguments.add(stringAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - } - - @Test - public void testString_GTE() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_STRING_GREATER_THAN_OR_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_GREATER_THAN_OR_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(stringAttr1); - arguments.add(stringAttr1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check first < second - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(stringAttr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first > second - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(stringAttrNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - } - - @Test - public void testString_LT() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_STRING_LESS_THAN; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_LESS_THAN, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(stringAttr1); - arguments.add(stringAttr1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // check first < second - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(stringAttr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first > second - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(stringAttrNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - } - - @Test - public void testString_LTE() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_STRING_LESS_THAN_OR_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_LESS_THAN_OR_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(stringAttr1); - arguments.add(stringAttr1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check first < second - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(stringAttr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first > second - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(stringAttrNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - } - - - - /** - * Integer - */ - @Test - public void testInteger_GT() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_INTEGER_GREATER_THAN; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_INTEGER_GREATER_THAN, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(intAttr1); - arguments.add(intAttr1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // check first < second - arguments.clear(); - arguments.add(intAttr1); - arguments.add(intAttr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first > second - arguments.clear(); - arguments.add(intAttr1); - arguments.add(intAttrNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - } - - @Test - public void testInteger_GTE() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_INTEGER_GREATER_THAN_OR_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_INTEGER_GREATER_THAN_OR_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(intAttr1); - arguments.add(intAttr1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check first < second - arguments.clear(); - arguments.add(intAttr1); - arguments.add(intAttr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first > second - arguments.clear(); - arguments.add(intAttr1); - arguments.add(intAttrNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - } - - @Test - public void testInteger_LT() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_INTEGER_LESS_THAN; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_INTEGER_LESS_THAN, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(intAttr1); - arguments.add(intAttr1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // check first < second - arguments.clear(); - arguments.add(intAttr1); - arguments.add(intAttr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first > second - arguments.clear(); - arguments.add(intAttr1); - arguments.add(intAttrNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - } - - @Test - public void testInteger_LTE() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_INTEGER_LESS_THAN_OR_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_INTEGER_LESS_THAN_OR_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(intAttr1); - arguments.add(intAttr1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check first < second - arguments.clear(); - arguments.add(intAttr1); - arguments.add(intAttr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first > second - arguments.clear(); - arguments.add(intAttr1); - arguments.add(intAttrNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - } - - - - - /** - * Double - */ - @Test - public void testDouble_GT() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DOUBLE_GREATER_THAN; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DOUBLE_GREATER_THAN, fd.getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attr1); - arguments.add(attr1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first < second - arguments.clear(); - arguments.add(attr1); - arguments.add(attr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first > second - arguments.clear(); - arguments.add(attr1); - arguments.add(attrNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - @Test - public void testDouble_GTE() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DOUBLE_GREATER_THAN_OR_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DOUBLE_GREATER_THAN_OR_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attr1); - arguments.add(attr1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first < second - arguments.clear(); - arguments.add(attr1); - arguments.add(attr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first > second - arguments.clear(); - arguments.add(attr1); - arguments.add(attrNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - } - - @Test - public void testDouble_LT() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DOUBLE_LESS_THAN; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DOUBLE_LESS_THAN, fd.getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attr1); - arguments.add(attr1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first < second - arguments.clear(); - arguments.add(attr1); - arguments.add(attr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first > second - arguments.clear(); - arguments.add(attr1); - arguments.add(attrNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - } - - @Test - public void testDouble_LTE() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DOUBLE_LESS_THAN_OR_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DOUBLE_LESS_THAN_OR_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attr1); - arguments.add(attr1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first < second - arguments.clear(); - arguments.add(attr1); - arguments.add(attr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first > second - arguments.clear(); - arguments.add(attr1); - arguments.add(attrNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - } - - - - /** - * Date - */ - - @Test - public void testDate_GT() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATE_GREATER_THAN; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATE_GREATER_THAN, fd.getId()); - assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attrDateToday); - arguments.add(attrDateSameDay); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first < second - arguments.clear(); - arguments.add(attrDateToday); - arguments.add(attrDateTommorrow); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first > second - arguments.clear(); - arguments.add(attrDateToday); - arguments.add(attrDateYesterday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // test bad args data types? One with TimeZone and one without - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - // test with TimeZone vs without - arguments.clear(); - arguments.add(attrDateWithTimeZone); - arguments.add(attrDateNoTimeZone); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-greater-than Cannot compare this ISO8601DateTime with non-time-zoned ISO8601DateTime", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - } - - @Test - public void testDate_GTE() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATE_GREATER_THAN_OR_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATE_GREATER_THAN_OR_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attrDateToday); - arguments.add(attrDateSameDay); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first < second - arguments.clear(); - arguments.add(attrDateToday); - arguments.add(attrDateTommorrow); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first > second - arguments.clear(); - arguments.add(attrDateToday); - arguments.add(attrDateYesterday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - } - - @Test - public void testDate_LT() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATE_LESS_THAN; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATE_LESS_THAN, fd.getId()); - assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attrDateToday); - arguments.add(attrDateSameDay); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first < second - arguments.clear(); - arguments.add(attrDateToday); - arguments.add(attrDateTommorrow); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first > second - arguments.clear(); - arguments.add(attrDateToday); - arguments.add(attrDateYesterday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - } - - @Test - public void testDate_LTE() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATE_LESS_THAN_OR_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATE_LESS_THAN_OR_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attrDateToday); - arguments.add(attrDateSameDay); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first < second - arguments.clear(); - arguments.add(attrDateToday); - arguments.add(attrDateTommorrow); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first > second - arguments.clear(); - arguments.add(attrDateToday); - arguments.add(attrDateYesterday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - } - - - - - - - - /** - * Time - */ - - @Test - public void testTime_GT() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_TIME_GREATER_THAN; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_TIME_GREATER_THAN, fd.getId()); - assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attrTimeToday); - arguments.add(attrTimeSameDay); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first < second - arguments.clear(); - arguments.add(attrTimeToday); - arguments.add(attrTimeTommorrow); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first > second - arguments.clear(); - arguments.add(attrTimeToday); - arguments.add(attrTimeYesterday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // test bad args data types? One with TimeZone and one without - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - // test with TimeZone vs without - arguments.clear(); - arguments.add(attrTimeWithTimeZone); - arguments.add(attrTimeNoTimeZone); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:time-greater-than Cannot compare this ISO8601DateTime with non-time-zoned ISO8601DateTime", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - } - - @Test - public void testTime_GTE() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_TIME_GREATER_THAN_OR_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_TIME_GREATER_THAN_OR_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attrTimeToday); - arguments.add(attrTimeSameDay); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first < second - arguments.clear(); - arguments.add(attrTimeToday); - arguments.add(attrTimeTommorrow); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first > second - arguments.clear(); - arguments.add(attrTimeToday); - arguments.add(attrTimeYesterday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - } - - @Test - public void testTime_LT() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_TIME_LESS_THAN; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_TIME_LESS_THAN, fd.getId()); - assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attrTimeToday); - arguments.add(attrTimeSameDay); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first < second - arguments.clear(); - arguments.add(attrTimeToday); - arguments.add(attrTimeTommorrow); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first > second - arguments.clear(); - arguments.add(attrTimeToday); - arguments.add(attrTimeYesterday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - } - - @Test - public void testTime_LTE() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_TIME_LESS_THAN_OR_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_TIME_LESS_THAN_OR_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attrTimeToday); - arguments.add(attrTimeSameDay); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first < second - arguments.clear(); - arguments.add(attrTimeToday); - arguments.add(attrTimeTommorrow); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first > second - arguments.clear(); - arguments.add(attrTimeToday); - arguments.add(attrTimeYesterday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - } - - - - - - /** - * Time-in-range - */ - @Test - public void testTime_in_range() { - - FunctionDefinitionTimeInRange fd = (FunctionDefinitionTimeInRange) StdFunctions.FD_TIME_IN_RANGE; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_TIME_IN_RANGE, fd.getId()); - assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(3), fd.getNumArgs()); - - // arg 0 in range of others - arguments.add(attrTimeToday); - arguments.add(attrTimeYesterday); - arguments.add(attrTimeTommorrow); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // below range - arguments.clear(); - arguments.add(attrTimeYesterday); - arguments.add(attrTimeToday); - arguments.add(attrTimeTommorrow); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // above range - arguments.clear(); - arguments.add(attrTimeTommorrow); - arguments.add(attrTimeYesterday); - arguments.add(attrTimeToday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // range bad - arguments.clear(); - arguments.add(attrTimeToday); - arguments.add(attrTimeTommorrow); - arguments.add(attrTimeYesterday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // bad types - arguments.clear(); - arguments.add(attrDateTimeWithTimeZone); - arguments.add(attrDateTimeNoTimeZone); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:time-in-range Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrDateTimeWithTimeZone); - arguments.add(attrDateTimeNoTimeZone); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:time-in-range Expected data type 'time' saw 'dateTime' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - - - /** - * DateTime - */ - - @Test - public void testDateTime_GT() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATETIME_GREATER_THAN; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATETIME_GREATER_THAN, fd.getId()); - assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attrDateTimeToday); - arguments.add(attrDateTimeSameDay); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first < second - arguments.clear(); - arguments.add(attrDateTimeToday); - arguments.add(attrDateTimeTommorrow); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first > second - arguments.clear(); - arguments.add(attrDateTimeToday); - arguments.add(attrDateTimeYesterday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // test bad args data types? One with TimeZone and one without - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - // test with TimeZone vs without - arguments.clear(); - arguments.add(attrDateTimeWithTimeZone); - arguments.add(attrDateTimeNoTimeZone); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-greater-than Cannot compare this ISO8601DateTime with non-time-zoned ISO8601DateTime", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - } - - @Test - public void testDateTime_GTE() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATETIME_GREATER_THAN_OR_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATETIME_GREATER_THAN_OR_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attrDateTimeToday); - arguments.add(attrDateTimeSameDay); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first < second - arguments.clear(); - arguments.add(attrDateTimeToday); - arguments.add(attrDateTimeTommorrow); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first > second - arguments.clear(); - arguments.add(attrDateTimeToday); - arguments.add(attrDateTimeYesterday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - } - - @Test - public void testDateTime_LT() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATETIME_LESS_THAN; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATETIME_LESS_THAN, fd.getId()); - assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attrDateTimeToday); - arguments.add(attrDateTimeSameDay); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first < second - arguments.clear(); - arguments.add(attrDateTimeToday); - arguments.add(attrDateTimeTommorrow); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first > second - arguments.clear(); - arguments.add(attrDateTimeToday); - arguments.add(attrDateTimeYesterday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - } - - @Test - public void testDateTime_LTE() { - - FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATETIME_LESS_THAN_OR_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATETIME_LESS_THAN_OR_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // first == second - arguments.add(attrDateTimeToday); - arguments.add(attrDateTimeSameDay); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first < second - arguments.clear(); - arguments.add(attrDateTimeToday); - arguments.add(attrDateTimeTommorrow); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first > second - arguments.clear(); - arguments.add(attrDateTimeToday); - arguments.add(attrDateTimeYesterday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - } - - - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionDateTimeArithmeticTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionDateTimeArithmeticTest.java deleted file mode 100644 index a4a6a425b..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionDateTimeArithmeticTest.java +++ /dev/null @@ -1,1602 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacml.std.datatypes.ISO8601Date; -import com.att.research.xacml.std.datatypes.ISO8601DateTime; -import com.att.research.xacml.std.datatypes.ISO8601Time; -import com.att.research.xacml.std.datatypes.ISO8601TimeZone; -import com.att.research.xacml.std.datatypes.XPathDayTimeDuration; -import com.att.research.xacml.std.datatypes.XPathYearMonthDuration; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionDateTimeArithmeticTest { - - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - ExpressionResult res; - - - @Test - public void testDateTime_add_dayTimeDuration() { - // Date objects to be adjusted - ISO8601DateTime dateTimeStdExample1 = new ISO8601DateTime(null, - new ISO8601Date(2000, 1, 12), - new ISO8601Time(12, 13, 14, 0)); - ISO8601DateTime dateTimeMsecs = new ISO8601DateTime(null, - new ISO8601Date(2000, 1, 12), - new ISO8601Time(12, 13, 14, 777)); - ISO8601DateTime dateTimeCrossover = new ISO8601DateTime(null, - new ISO8601Date(2000, 12, 31), - new ISO8601Time(23, 59, 30, 1)); - ISO8601DateTime dateTimeBC = new ISO8601DateTime(null, - new ISO8601Date(-2000, 1, 12), - new ISO8601Time(12, 13, 14, 0)); - ISO8601TimeZone timeZone0 = new ISO8601TimeZone(0); - ISO8601TimeZone timeZone5 = new ISO8601TimeZone(5 * 60); - ISO8601DateTime dateTimeTimeZone0 = new ISO8601DateTime(timeZone0, - new ISO8601Date(timeZone0, 2000, 1, 12), - new ISO8601Time(timeZone0, 12, 13, 14, 0)); - ISO8601DateTime dateTimeTimeZone5 = new ISO8601DateTime(timeZone5, - new ISO8601Date(timeZone5, 2000, 1, 12), - new ISO8601Time(timeZone5, 12, 13, 14, 0)); - ISO8601DateTime dateTimeIIC102Result = null; - - // Durations - XPathDayTimeDuration duration0 = new XPathDayTimeDuration(1, 0, 0, 0, 0); - XPathDayTimeDuration durationStdExample1 = new XPathDayTimeDuration(1, 5, 7, 10, 3.3); - XPathDayTimeDuration durationNStdExample1 = new XPathDayTimeDuration(-1, 5, 7, 10, 3.3); - XPathDayTimeDuration durationMsecs = new XPathDayTimeDuration(1, 5, 7, 10, 3.223); - XPathDayTimeDuration durationCrossover = new XPathDayTimeDuration(1, 0, 0, 0, 29.999); - - // ARGS declarations - // Dates - FunctionArgumentAttributeValue attrDateTimeStdExample1 = null; - FunctionArgumentAttributeValue attrDateTimeMsecs = null; - FunctionArgumentAttributeValue attrDateTimeCrossover = null; - FunctionArgumentAttributeValue attrDateTimeBC = null; - FunctionArgumentAttributeValue attrDateTimeTimeZone0 = null; - FunctionArgumentAttributeValue attrDateTimeTimeZone5 = null; - FunctionArgumentAttributeValue attrDateTimeIIC102 = null; - - // Durations - FunctionArgumentAttributeValue attrDuration0 = null; - FunctionArgumentAttributeValue attrDurationStdExample1 = null; - FunctionArgumentAttributeValue attrDurationNStdExample1 = null; - FunctionArgumentAttributeValue attrDurationMsecs = null; - FunctionArgumentAttributeValue attrDurationCrossover = null; - FunctionArgumentAttributeValue attrDurationIIC102 = null; - - // misc bad - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrBlank = null; - FunctionArgumentAttributeValue attrInteger = null; - // set values - try { - // Date attrs - attrDateTimeStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeStdExample1)); - attrDateTimeMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeMsecs)); - attrDateTimeCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeCrossover)); - attrDateTimeBC = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeBC)); - attrDateTimeTimeZone0 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone0)); - attrDateTimeTimeZone5 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone5)); - attrDateTimeIIC102 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(DataTypes.DT_DATETIME.convert("2002-03-22T08:23:47-05:00"))); - - dateTimeIIC102Result = DataTypes.DT_DATETIME.convert("2002-03-27T10:23:47-05:00"); - - // Duration attrs - attrDuration0 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(duration0)); - attrDurationStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationStdExample1)); - attrDurationNStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationNStdExample1)); - attrDurationMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationMsecs)); - attrDurationCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationCrossover)); - attrDurationIIC102 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue("P5DT2H0M0S")); - - // misc bad - attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue("")); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(null)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionDateTimeArithmetic fd = (FunctionDefinitionDateTimeArithmetic) StdFunctions.FD_DATETIME_ADD_DAYTIMEDURATION; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATETIME_ADD_DAYTIMEDURATION, fd.getId()); - assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - // Duration = 0 => same as original - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDuration0); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - ISO8601DateTime resValue = (ISO8601DateTime)res.getValue().getValue(); - assertEquals(dateTimeStdExample1, resValue); - - - // simple positive operation - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - ISO8601DateTime testResponse = new ISO8601DateTime( - null, - new ISO8601Date(2000, 1, 17), - new ISO8601Time(19, 23, 17, 300) ); - assertEquals(testResponse, resValue); - - // negative operation - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDurationNStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(2000, 1, 7), - new ISO8601Time(5, 3, 10, 700) ); - assertEquals(testResponse, resValue); - - // millisecs work correctly - arguments.clear(); - arguments.add(attrDateTimeMsecs); - arguments.add(attrDurationMsecs); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(2000, 1, 17), - new ISO8601Time(19, 23, 18, 0) ); - assertEquals(testResponse, resValue); - - // cross minute => cross day => cross month => cross year - arguments.clear(); - arguments.add(attrDateTimeCrossover); - arguments.add(attrDurationCrossover); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(2001, 1, 1), - new ISO8601Time(0, 0, 0, 0) ); - assertEquals(testResponse, resValue); - - // negative (BC) original date add goes the right direction - arguments.clear(); - arguments.add(attrDateTimeBC); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(-2000, 1, 17), - new ISO8601Time(19, 23, 17, 300) ); - assertEquals(testResponse, resValue); - - // non-null timezone not changed - // original has timezone offset = 0 - arguments.clear(); - arguments.add(attrDateTimeTimeZone0); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - timeZone0, - new ISO8601Date(timeZone0, 2000, 1, 17), - new ISO8601Time(timeZone0, 19, 23, 17, 300) ); - assertEquals(testResponse, resValue); - - // original has timezone offset not 0 - arguments.clear(); - arguments.add(attrDateTimeTimeZone5); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - timeZone5, - new ISO8601Date(timeZone5, 2000, 1, 17), - new ISO8601Time(timeZone5, 19, 23, 17, 300) ); - assertEquals(testResponse, resValue); - - // conformance test IIC102 - arguments.clear(); - arguments.add(attrDateTimeIIC102); - arguments.add(attrDurationIIC102); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - assertEquals(dateTimeIIC102Result, resValue); - - // empty non-null first arg - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-add-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // empty non-null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-add-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // two blanks - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-add-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null firat arg - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-add-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-add-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrInteger); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-add-dayTimeDuration Expected data type 'dateTime' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-add-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - @Test - public void testDateTime_subtract_dayTimeDuration() { - // Date objects to be adjusted - ISO8601DateTime dateTimeStdExample1 = new ISO8601DateTime(null, - new ISO8601Date(2000, 1, 12), - new ISO8601Time(12, 13, 14, 0)); - ISO8601DateTime dateTimeMsecs = new ISO8601DateTime(null, - new ISO8601Date(2000, 1, 12), - new ISO8601Time(12, 13, 14, 777)); - ISO8601DateTime dateTimeCrossover = new ISO8601DateTime(null, - new ISO8601Date(2001, 1, 1), - new ISO8601Time(0, 0, 0, 0) ); - ISO8601DateTime dateTimeBC = new ISO8601DateTime(null, - new ISO8601Date(-2000, 1, 12), - new ISO8601Time(12, 13, 14, 0)); - ISO8601TimeZone timeZone0 = new ISO8601TimeZone(0); - ISO8601TimeZone timeZone5 = new ISO8601TimeZone(5 * 60); - ISO8601DateTime dateTimeTimeZone0 = new ISO8601DateTime(timeZone0, - new ISO8601Date(timeZone0, 2000, 1, 12), - new ISO8601Time(timeZone0, 12, 13, 14, 0)); - ISO8601DateTime dateTimeTimeZone5 = new ISO8601DateTime(timeZone5, - new ISO8601Date(timeZone5, 2000, 1, 12), - new ISO8601Time(timeZone5, 12, 13, 14, 0)); - - // Durations - XPathDayTimeDuration duration0 = new XPathDayTimeDuration(1, 0, 0, 0, 0); - XPathDayTimeDuration durationStdExample1 = new XPathDayTimeDuration(1, 5, 7, 10, 3.3); - XPathDayTimeDuration durationNStdExample1 = new XPathDayTimeDuration(-1, 5, 7, 10, 3.3); - XPathDayTimeDuration durationMsecs = new XPathDayTimeDuration(1, 5, 7, 10, 14.778); - XPathDayTimeDuration durationCrossover = new XPathDayTimeDuration(1, 0, 0, 0, 29.999); - - // ARGS declarations - // Dates - FunctionArgumentAttributeValue attrDateTimeStdExample1 = null; - FunctionArgumentAttributeValue attrDateTimeMsecs = null; - FunctionArgumentAttributeValue attrDateTimeCrossover = null; - FunctionArgumentAttributeValue attrDateTimeBC = null; - FunctionArgumentAttributeValue attrDateTimeTimeZone0 = null; - FunctionArgumentAttributeValue attrDateTimeTimeZone5 = null; - - // Durations - FunctionArgumentAttributeValue attrDuration0 = null; - FunctionArgumentAttributeValue attrDurationStdExample1 = null; - FunctionArgumentAttributeValue attrDurationNStdExample1 = null; - FunctionArgumentAttributeValue attrDurationMsecs = null; - FunctionArgumentAttributeValue attrDurationCrossover = null; - - // misc bad - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrBlank = null; - FunctionArgumentAttributeValue attrInteger = null; - // set values - try { - // Date attrs - attrDateTimeStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeStdExample1)); - attrDateTimeMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeMsecs)); - attrDateTimeCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeCrossover)); - attrDateTimeBC = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeBC)); - attrDateTimeTimeZone0 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone0)); - attrDateTimeTimeZone5 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone5)); - - // Duration attrs - attrDuration0 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(duration0)); - attrDurationStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationStdExample1)); - attrDurationNStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationNStdExample1)); - attrDurationMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationMsecs)); - attrDurationCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationCrossover)); - - // misc bad - attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue("")); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(null)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionDateTimeArithmetic fd = (FunctionDefinitionDateTimeArithmetic) StdFunctions.FD_DATETIME_SUBTRACT_DAYTIMEDURATION; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATETIME_SUBTRACT_DAYTIMEDURATION, fd.getId()); - assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - // Duration = 0 => same as original - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDuration0); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - ISO8601DateTime resValue = (ISO8601DateTime)res.getValue().getValue(); - assertEquals(dateTimeStdExample1, resValue); - - - // simple positive operation - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - ISO8601DateTime testResponse = new ISO8601DateTime( - null, - new ISO8601Date(2000, 1, 7), - new ISO8601Time(5, 3, 10, 700) ); - assertEquals(testResponse, resValue); - - - // negative operation - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDurationNStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(2000, 1, 17), - new ISO8601Time(19, 23, 17, 300) ); - assertEquals(testResponse, resValue); - - // millisecs work correctly - arguments.clear(); - arguments.add(attrDateTimeMsecs); - arguments.add(attrDurationMsecs); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(2000, 1, 7), - new ISO8601Time(5, 2, 59, 999) ); - assertEquals(testResponse, resValue); - - // cross minute => cross day => cross month => cross year - arguments.clear(); - arguments.add(attrDateTimeCrossover); - arguments.add(attrDurationCrossover); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(2000, 12, 31), - new ISO8601Time(23, 59, 30, 1)); - assertEquals(testResponse, resValue); - - // negative (BC) original date add goes the right direction - arguments.clear(); - arguments.add(attrDateTimeBC); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(-2000, 1, 7), - new ISO8601Time(5, 3, 10, 700) ); - assertEquals(testResponse, resValue); - - // non-null timezone not changed - // original has timezone offset = 0 - arguments.clear(); - arguments.add(attrDateTimeTimeZone0); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - timeZone0, - new ISO8601Date(timeZone0, 2000, 1, 7), - new ISO8601Time(timeZone0, 5, 3, 10, 700) ); - assertEquals(testResponse, resValue); - - // original has timezone offset not 0 - arguments.clear(); - arguments.add(attrDateTimeTimeZone5); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - timeZone5, - new ISO8601Date(timeZone5, 2000, 1, 7), - new ISO8601Time(timeZone5, 5, 3, 10, 700) ); - assertEquals(testResponse, resValue); - - // empty non-null first arg - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-subtract-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // empty non-null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-subtract-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // two blanks - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-subtract-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null firat arg - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-subtract-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-subtract-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrInteger); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-subtract-dayTimeDuration Expected data type 'dateTime' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-subtract-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - - - - - - - @Test - public void testDateTime_add_yearMonthDuration() { - // Date objects to be adjusted - ISO8601DateTime dateTimeStdExample1 = new ISO8601DateTime(null, - new ISO8601Date(2000, 1, 12), - new ISO8601Time(12, 13, 14, 0)); - ISO8601DateTime dateTimeMsecs = new ISO8601DateTime(null, - new ISO8601Date(2000, 1, 12), - new ISO8601Time(12, 13, 14, 777)); - ISO8601DateTime dateTimeCrossover = new ISO8601DateTime(null, - new ISO8601Date(2000, 12, 31), - new ISO8601Time(23, 59, 30, 1)); - ISO8601DateTime dateTimeBC = new ISO8601DateTime(null, - new ISO8601Date(-2000, 1, 12), - new ISO8601Time(12, 13, 14, 0)); - ISO8601TimeZone timeZone0 = new ISO8601TimeZone(0); - ISO8601TimeZone timeZone5 = new ISO8601TimeZone(5 * 60); - ISO8601DateTime dateTimeTimeZone0 = new ISO8601DateTime(timeZone0, - new ISO8601Date(timeZone0, 2000, 1, 12), - new ISO8601Time(timeZone0, 12, 13, 14, 0)); - ISO8601DateTime dateTimeTimeZone5 = new ISO8601DateTime(timeZone5, - new ISO8601Date(timeZone5, 2000, 1, 12), - new ISO8601Time(timeZone5, 12, 13, 14, 0)); - - // Durations - XPathYearMonthDuration duration0 = new XPathYearMonthDuration(1, 0, 0); - XPathYearMonthDuration durationStdExample1 = new XPathYearMonthDuration(1, 5, 7); - XPathYearMonthDuration durationNStdExample1 = new XPathYearMonthDuration(-1, 5, 7); - XPathYearMonthDuration durationMsecs = new XPathYearMonthDuration(1, 5, 7); - XPathYearMonthDuration durationCrossover = new XPathYearMonthDuration(1, 0, 1); - - // ARGS declarations - // Dates - FunctionArgumentAttributeValue attrDateTimeStdExample1 = null; - FunctionArgumentAttributeValue attrDateTimeMsecs = null; - FunctionArgumentAttributeValue attrDateTimeCrossover = null; - FunctionArgumentAttributeValue attrDateTimeBC = null; - FunctionArgumentAttributeValue attrDateTimeTimeZone0 = null; - FunctionArgumentAttributeValue attrDateTimeTimeZone5 = null; - - // Durations - FunctionArgumentAttributeValue attrDuration0 = null; - FunctionArgumentAttributeValue attrDurationStdExample1 = null; - FunctionArgumentAttributeValue attrDurationNStdExample1 = null; - FunctionArgumentAttributeValue attrDurationMsecs = null; - FunctionArgumentAttributeValue attrDurationCrossover = null; - - // misc bad - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrBlank = null; - FunctionArgumentAttributeValue attrInteger = null; - // set values - try { - // Date attrs - attrDateTimeStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeStdExample1)); - attrDateTimeMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeMsecs)); - attrDateTimeCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeCrossover)); - attrDateTimeBC = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeBC)); - attrDateTimeTimeZone0 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone0)); - attrDateTimeTimeZone5 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone5)); - - // Duration attrs - attrDuration0 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(duration0)); - attrDurationStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationStdExample1)); - attrDurationNStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationNStdExample1)); - attrDurationMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationMsecs)); - attrDurationCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationCrossover)); - - // misc bad - attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue("")); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(null)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionDateTimeArithmetic fd = (FunctionDefinitionDateTimeArithmetic) StdFunctions.FD_DATETIME_ADD_YEARMONTHDURATION; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATETIME_ADD_YEARMONTHDURATION, fd.getId()); - assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - // Duration = 0 => same as original - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDuration0); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - ISO8601DateTime resValue = (ISO8601DateTime)res.getValue().getValue(); - assertEquals(dateTimeStdExample1, resValue); - - - // simple positive operation - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - ISO8601DateTime testResponse = new ISO8601DateTime( - null, - new ISO8601Date(2005, 8, 12), - new ISO8601Time(12, 13, 14, 0) ); - assertEquals(testResponse, resValue); - - // negative operation - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDurationNStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(1994, 6, 12), - new ISO8601Time(12, 13, 14, 0) ); - assertEquals(testResponse, resValue); - - // millisecs work correctly (not relevant to YearMonth, but should not break - arguments.clear(); - arguments.add(attrDateTimeMsecs); - arguments.add(attrDurationMsecs); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(2005, 8, 12), - new ISO8601Time(12, 13, 14, 777) ); - assertEquals(testResponse, resValue); - - // cross minute => cross day => cross month => cross year - arguments.clear(); - arguments.add(attrDateTimeCrossover); - arguments.add(attrDurationCrossover); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(2001, 1, 31), - new ISO8601Time(23, 59, 30, 1) ); - assertEquals(testResponse, resValue); - - // negative (BC) original date add goes the right direction - arguments.clear(); - arguments.add(attrDateTimeBC); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(-1995, 8, 12), - new ISO8601Time(12, 13, 14, 0) ); - assertEquals(testResponse, resValue); - - // non-null timezone not changed - // original has timezone offset = 0 - arguments.clear(); - arguments.add(attrDateTimeTimeZone0); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - timeZone0, - new ISO8601Date(timeZone0, 2005, 8, 12), - new ISO8601Time(timeZone0, 12, 13, 14, 0) ); - assertEquals(testResponse, resValue); - - // original has timezone offset not 0 - arguments.clear(); - arguments.add(attrDateTimeTimeZone5); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - timeZone5, - new ISO8601Date(timeZone5, 2005, 8, 12), - new ISO8601Time(timeZone5, 12, 13, 14, 0) ); - assertEquals(testResponse, resValue); - - // empty non-null first arg - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // empty non-null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // two blanks - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null firat arg - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrInteger); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-add-yearMonthDuration Expected data type 'dateTime' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - - @Test - public void testDateTime_subtract_yearMonthDuration() { - // Date objects to be adjusted - ISO8601DateTime dateTimeStdExample1 = new ISO8601DateTime(null, - new ISO8601Date(2000, 1, 12), - new ISO8601Time(12, 13, 14, 0)); - ISO8601DateTime dateTimeMsecs = new ISO8601DateTime(null, - new ISO8601Date(2000, 1, 12), - new ISO8601Time(12, 13, 14, 777)); - ISO8601DateTime dateTimeCrossover = new ISO8601DateTime(null, - new ISO8601Date(2000, 1, 1), - new ISO8601Time(23, 59, 30, 1)); - ISO8601DateTime dateTimeBC = new ISO8601DateTime(null, - new ISO8601Date(-2000, 1, 12), - new ISO8601Time(12, 13, 14, 0)); - ISO8601TimeZone timeZone0 = new ISO8601TimeZone(0); - ISO8601TimeZone timeZone5 = new ISO8601TimeZone(5 * 60); - ISO8601DateTime dateTimeTimeZone0 = new ISO8601DateTime(timeZone0, - new ISO8601Date(timeZone0, 2000, 1, 12), - new ISO8601Time(timeZone0, 12, 13, 14, 0)); - ISO8601DateTime dateTimeTimeZone5 = new ISO8601DateTime(timeZone5, - new ISO8601Date(timeZone5, 2000, 1, 12), - new ISO8601Time(timeZone5, 12, 13, 14, 0)); - - // Durations - XPathYearMonthDuration duration0 = new XPathYearMonthDuration(1, 0, 0); - XPathYearMonthDuration durationStdExample1 = new XPathYearMonthDuration(1, 5, 7); - XPathYearMonthDuration durationNStdExample1 = new XPathYearMonthDuration(-1, 5, 7); - XPathYearMonthDuration durationMsecs = new XPathYearMonthDuration(1, 5, 7); - XPathYearMonthDuration durationCrossover = new XPathYearMonthDuration(1, 0, 1); - - // ARGS declarations - // Dates - FunctionArgumentAttributeValue attrDateTimeStdExample1 = null; - FunctionArgumentAttributeValue attrDateTimeMsecs = null; - FunctionArgumentAttributeValue attrDateTimeCrossover = null; - FunctionArgumentAttributeValue attrDateTimeBC = null; - FunctionArgumentAttributeValue attrDateTimeTimeZone0 = null; - FunctionArgumentAttributeValue attrDateTimeTimeZone5 = null; - - // Durations - FunctionArgumentAttributeValue attrDuration0 = null; - FunctionArgumentAttributeValue attrDurationStdExample1 = null; - FunctionArgumentAttributeValue attrDurationNStdExample1 = null; - FunctionArgumentAttributeValue attrDurationMsecs = null; - FunctionArgumentAttributeValue attrDurationCrossover = null; - - // misc bad - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrBlank = null; - FunctionArgumentAttributeValue attrInteger = null; - // set values - try { - // Date attrs - attrDateTimeStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeStdExample1)); - attrDateTimeMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeMsecs)); - attrDateTimeCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeCrossover)); - attrDateTimeBC = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeBC)); - attrDateTimeTimeZone0 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone0)); - attrDateTimeTimeZone5 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone5)); - - // Duration attrs - attrDuration0 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(duration0)); - attrDurationStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationStdExample1)); - attrDurationNStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationNStdExample1)); - attrDurationMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationMsecs)); - attrDurationCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationCrossover)); - - // misc bad - attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue("")); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(null)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionDateTimeArithmetic fd = (FunctionDefinitionDateTimeArithmetic) StdFunctions.FD_DATETIME_SUBTRACT_YEARMONTHDURATION; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATETIME_SUBTRACT_YEARMONTHDURATION, fd.getId()); - assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - // Duration = 0 => same as original - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDuration0); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - ISO8601DateTime resValue = (ISO8601DateTime)res.getValue().getValue(); - assertEquals(dateTimeStdExample1, resValue); - - - // simple positive operation - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - ISO8601DateTime testResponse = new ISO8601DateTime( - null, - new ISO8601Date(1994, 6, 12), - new ISO8601Time(12, 13, 14, 0) ); - assertEquals(testResponse, resValue); - - // negative operation - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDurationNStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(2005, 8, 12), - new ISO8601Time(12, 13, 14, 0) ); - assertEquals(testResponse, resValue); - - // millisecs work correctly (not relevant to YearMonth, but should not break - arguments.clear(); - arguments.add(attrDateTimeMsecs); - arguments.add(attrDurationMsecs); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(1994, 6, 12), - new ISO8601Time(12, 13, 14, 777) ); - assertEquals(testResponse, resValue); - - // cross minute => cross day => cross month => cross year - arguments.clear(); - arguments.add(attrDateTimeCrossover); - arguments.add(attrDurationCrossover); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(1999, 12, 1), - new ISO8601Time(23, 59, 30, 1) ); - assertEquals(testResponse, resValue); - - // negative (BC) original date add goes the right direction - arguments.clear(); - arguments.add(attrDateTimeBC); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - null, - new ISO8601Date(-2006, 6, 12), - new ISO8601Time(12, 13, 14, 0) ); - assertEquals(testResponse, resValue); - - // non-null timezone not changed - // original has timezone offset = 0 - arguments.clear(); - arguments.add(attrDateTimeTimeZone0); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - timeZone0, - new ISO8601Date(timeZone0, 1994, 6, 12), - new ISO8601Time(timeZone0, 12, 13, 14, 0) ); - assertEquals(testResponse, resValue); - - // original has timezone offset not 0 - arguments.clear(); - arguments.add(attrDateTimeTimeZone5); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - testResponse = new ISO8601DateTime( - timeZone5, - new ISO8601Date(timeZone5, 1994, 6, 12), - new ISO8601Time(timeZone5, 12, 13, 14, 0) ); - assertEquals(testResponse, resValue); - - // empty non-null first arg - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // empty non-null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // two blanks - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null firat arg - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrInteger); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-subtract-yearMonthDuration Expected data type 'dateTime' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - - - - - - - - - @Test - public void testDate_add_yearMonthDuration() { - // Date objects to be adjusted - ISO8601Date dateTimeStdExample1 = new ISO8601Date(2000, 1, 12); - ISO8601Date dateTimeMsecs =new ISO8601Date(2000, 1, 12); - ISO8601Date dateTimeCrossover = new ISO8601Date(2000, 12, 31); - ISO8601Date dateTimeBC = new ISO8601Date(-2000, 1, 12); - ISO8601TimeZone timeZone0 = new ISO8601TimeZone(0); - ISO8601TimeZone timeZone5 = new ISO8601TimeZone(5 * 60); - ISO8601Date dateTimeTimeZone0 = new ISO8601Date(timeZone0, 2000, 1, 12); - ISO8601Date dateTimeTimeZone5 = new ISO8601Date(timeZone5, 2000, 1, 12); - - // Durations - XPathYearMonthDuration duration0 = new XPathYearMonthDuration(1, 0, 0); - XPathYearMonthDuration durationStdExample1 = new XPathYearMonthDuration(1, 5, 7); - XPathYearMonthDuration durationNStdExample1 = new XPathYearMonthDuration(-1, 5, 7); - XPathYearMonthDuration durationMsecs = new XPathYearMonthDuration(1, 5, 7); - XPathYearMonthDuration durationCrossover = new XPathYearMonthDuration(1, 0, 1); - - // ARGS declarations - // Dates - FunctionArgumentAttributeValue attrDateTimeStdExample1 = null; - FunctionArgumentAttributeValue attrDateTimeMsecs = null; - FunctionArgumentAttributeValue attrDateTimeCrossover = null; - FunctionArgumentAttributeValue attrDateTimeBC = null; - FunctionArgumentAttributeValue attrDateTimeTimeZone0 = null; - FunctionArgumentAttributeValue attrDateTimeTimeZone5 = null; - - // Durations - FunctionArgumentAttributeValue attrDuration0 = null; - FunctionArgumentAttributeValue attrDurationStdExample1 = null; - FunctionArgumentAttributeValue attrDurationNStdExample1 = null; - FunctionArgumentAttributeValue attrDurationMsecs = null; - FunctionArgumentAttributeValue attrDurationCrossover = null; - - // misc bad - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrBlank = null; - FunctionArgumentAttributeValue attrInteger = null; - // set values - try { - // Date attrs - attrDateTimeStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeStdExample1)); - attrDateTimeMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeMsecs)); - attrDateTimeCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeCrossover)); - attrDateTimeBC = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeBC)); - attrDateTimeTimeZone0 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeTimeZone0)); - attrDateTimeTimeZone5 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeTimeZone5)); - - // Duration attrs - attrDuration0 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(duration0)); - attrDurationStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationStdExample1)); - attrDurationNStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationNStdExample1)); - attrDurationMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationMsecs)); - attrDurationCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationCrossover)); - - // misc bad - attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue("")); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(null)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionDateTimeArithmetic fd = (FunctionDefinitionDateTimeArithmetic) StdFunctions.FD_DATE_ADD_YEARMONTHDURATION; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATE_ADD_YEARMONTHDURATION, fd.getId()); - assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - // Duration = 0 => same as original - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDuration0); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - ISO8601Date resValue = (ISO8601Date)res.getValue().getValue(); - assertEquals(dateTimeStdExample1, resValue); - - - // simple positive operation - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - resValue = (ISO8601Date)res.getValue().getValue(); - ISO8601Date testResponse = new ISO8601Date(2005, 8, 12); - assertEquals(testResponse, resValue); - - // negative operation - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDurationNStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - resValue = (ISO8601Date)res.getValue().getValue(); - testResponse = new ISO8601Date(1994, 6, 12); - assertEquals(testResponse, resValue); - - // millisecs work correctly (not relevant to YearMonth, but should not break - arguments.clear(); - arguments.add(attrDateTimeMsecs); - arguments.add(attrDurationMsecs); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - resValue = (ISO8601Date)res.getValue().getValue(); - testResponse = new ISO8601Date(2005, 8, 12); - assertEquals(testResponse, resValue); - - // cross minute => cross day => cross month => cross year - arguments.clear(); - arguments.add(attrDateTimeCrossover); - arguments.add(attrDurationCrossover); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - resValue = (ISO8601Date)res.getValue().getValue(); - testResponse = new ISO8601Date(2001, 1, 31); - assertEquals(testResponse, resValue); - - // negative (BC) original date add goes the right direction - arguments.clear(); - arguments.add(attrDateTimeBC); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - resValue = (ISO8601Date)res.getValue().getValue(); - testResponse = new ISO8601Date(-1995, 8, 12); - assertEquals(testResponse, resValue); - - // non-null timezone not changed - // original has timezone offset = 0 - arguments.clear(); - arguments.add(attrDateTimeTimeZone0); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - resValue = (ISO8601Date)res.getValue().getValue(); - testResponse = new ISO8601Date(timeZone0, 2005, 8, 12); - assertEquals(testResponse, resValue); - - // original has timezone offset not 0 - arguments.clear(); - arguments.add(attrDateTimeTimeZone5); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - resValue = (ISO8601Date)res.getValue().getValue(); - testResponse = new ISO8601Date(timeZone5, 2005, 8, 12); - assertEquals(testResponse, resValue); - - // empty non-null first arg - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // empty non-null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // two blanks - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null firat arg - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrInteger); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-add-yearMonthDuration Expected data type 'date' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - - - - @Test - public void testDate_subtract_yearMonthDuration() { - // Date objects to be adjusted - ISO8601Date dateTimeStdExample1 =new ISO8601Date(2000, 1, 12); - ISO8601Date dateTimeMsecs = new ISO8601Date(2000, 1, 12); - ISO8601Date dateTimeCrossover = new ISO8601Date(2000, 1, 1); - ISO8601Date dateTimeBC = new ISO8601Date(-2000, 1, 12); - ISO8601TimeZone timeZone0 = new ISO8601TimeZone(0); - ISO8601TimeZone timeZone5 = new ISO8601TimeZone(5 * 60); - ISO8601Date dateTimeTimeZone0 = new ISO8601Date(timeZone0, 2000, 1, 12); - ISO8601Date dateTimeTimeZone5 = new ISO8601Date(timeZone5, 2000, 1, 12); - - // Durations - XPathYearMonthDuration duration0 = new XPathYearMonthDuration(1, 0, 0); - XPathYearMonthDuration durationStdExample1 = new XPathYearMonthDuration(1, 5, 7); - XPathYearMonthDuration durationNStdExample1 = new XPathYearMonthDuration(-1, 5, 7); - XPathYearMonthDuration durationMsecs = new XPathYearMonthDuration(1, 5, 7); - XPathYearMonthDuration durationCrossover = new XPathYearMonthDuration(1, 0, 1); - - // ARGS declarations - // Dates - FunctionArgumentAttributeValue attrDateTimeStdExample1 = null; - FunctionArgumentAttributeValue attrDateTimeMsecs = null; - FunctionArgumentAttributeValue attrDateTimeCrossover = null; - FunctionArgumentAttributeValue attrDateTimeBC = null; - FunctionArgumentAttributeValue attrDateTimeTimeZone0 = null; - FunctionArgumentAttributeValue attrDateTimeTimeZone5 = null; - - // Durations - FunctionArgumentAttributeValue attrDuration0 = null; - FunctionArgumentAttributeValue attrDurationStdExample1 = null; - FunctionArgumentAttributeValue attrDurationNStdExample1 = null; - FunctionArgumentAttributeValue attrDurationMsecs = null; - FunctionArgumentAttributeValue attrDurationCrossover = null; - - // misc bad - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrBlank = null; - FunctionArgumentAttributeValue attrInteger = null; - // set values - try { - // Date attrs - attrDateTimeStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeStdExample1)); - attrDateTimeMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeMsecs)); - attrDateTimeCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeCrossover)); - attrDateTimeBC = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeBC)); - attrDateTimeTimeZone0 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeTimeZone0)); - attrDateTimeTimeZone5 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeTimeZone5)); - - // Duration attrs - attrDuration0 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(duration0)); - attrDurationStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationStdExample1)); - attrDurationNStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationNStdExample1)); - attrDurationMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationMsecs)); - attrDurationCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationCrossover)); - - // misc bad - attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue("")); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(null)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionDateTimeArithmetic fd = (FunctionDefinitionDateTimeArithmetic) StdFunctions.FD_DATE_SUBTRACT_YEARMONTHDURATION; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATE_SUBTRACT_YEARMONTHDURATION, fd.getId()); - assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - // Duration = 0 => same as original - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDuration0); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - ISO8601Date resValue = (ISO8601Date)res.getValue().getValue(); - assertEquals(dateTimeStdExample1, resValue); - - - // simple positive operation - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - resValue = (ISO8601Date)res.getValue().getValue(); - ISO8601Date testResponse = new ISO8601Date(1994, 6, 12); - assertEquals(testResponse, resValue); - - // negative operation - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrDurationNStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - resValue = (ISO8601Date)res.getValue().getValue(); - testResponse = new ISO8601Date(2005, 8, 12); - assertEquals(testResponse, resValue); - - // millisecs work correctly (not relevant to YearMonth, but should not break - arguments.clear(); - arguments.add(attrDateTimeMsecs); - arguments.add(attrDurationMsecs); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - resValue = (ISO8601Date)res.getValue().getValue(); - testResponse = new ISO8601Date(1994, 6, 12); - assertEquals(testResponse, resValue); - - // cross minute => cross day => cross month => cross year - arguments.clear(); - arguments.add(attrDateTimeCrossover); - arguments.add(attrDurationCrossover); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - resValue = (ISO8601Date)res.getValue().getValue(); - testResponse = new ISO8601Date(1999, 12, 1); - assertEquals(testResponse, resValue); - - // negative (BC) original date add goes the right direction - arguments.clear(); - arguments.add(attrDateTimeBC); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - resValue = (ISO8601Date)res.getValue().getValue(); - testResponse = new ISO8601Date(-2006, 6, 12); - assertEquals(testResponse, resValue); - - // non-null timezone not changed - // original has timezone offset = 0 - arguments.clear(); - arguments.add(attrDateTimeTimeZone0); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - resValue = (ISO8601Date)res.getValue().getValue(); - testResponse = new ISO8601Date(timeZone0, 1994, 6, 12); - assertEquals(testResponse, resValue); - - // original has timezone offset not 0 - arguments.clear(); - arguments.add(attrDateTimeTimeZone5); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); - resValue = (ISO8601Date)res.getValue().getValue(); - testResponse = new ISO8601Date(timeZone5, 1994, 6, 12); - assertEquals(testResponse, resValue); - - // empty non-null first arg - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // empty non-null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // two blanks - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null firat arg - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrInteger); - arguments.add(attrDurationStdExample1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-subtract-yearMonthDuration Expected data type 'date' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrDateTimeStdExample1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionEqualityTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionEqualityTest.java deleted file mode 100644 index 53762264c..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionEqualityTest.java +++ /dev/null @@ -1,1192 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -import javax.security.auth.x500.X500Principal; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML1; -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.Base64Binary; -import com.att.research.xacml.std.datatypes.DataTypeRFC822Name; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacml.std.datatypes.HexBinary; -import com.att.research.xacml.std.datatypes.RFC822Name; -import com.att.research.xacml.std.datatypes.XPathDayTimeDuration; -import com.att.research.xacml.std.datatypes.XPathYearMonthDuration; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test FunctionDefinitionEquality, all of its super-classes, and all XACML functions supported by that class. - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * In the first implementation of XACML we had separate files for each XACML Function. - * This release combines multiple Functions in fewer files to minimize code duplication. - * This file supports the following XACML codes: - * string-equal - * boolean-equal - * integer-equal - * double-equal - * date-equal - * time-equal - * dateTime-equal - * dayTimeDuration-equal - * yearMonthDuration-equal - * - * Each of these is put into a separate test method just to keep things organized. - * - * - */ -public class FunctionDefinitionEqualityTest { - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - FunctionArgumentAttributeValue stringAttr1 = null; - FunctionArgumentAttributeValue stringAttr2 = null; - FunctionArgumentAttributeValue stringAttr3 = null; - FunctionArgumentAttributeValue stringAttr4 = null; - - FunctionArgumentAttributeValue booleanAttrT1 = null; - FunctionArgumentAttributeValue booleanAttrT2 = null; - FunctionArgumentAttributeValue booleanAttrF1 = null; - FunctionArgumentAttributeValue booleanAttrF2 = null; - - FunctionArgumentAttributeValue intAttr1 = null; - FunctionArgumentAttributeValue intAttr1a = null; - FunctionArgumentAttributeValue intAttr2 = null; - FunctionArgumentAttributeValue intAttr0 = null; - FunctionArgumentAttributeValue intAttrNeg1 = null; - - public FunctionDefinitionEqualityTest() { - try { - stringAttr1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc")); - stringAttr2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc")); - stringAttr3 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("ABC")); - stringAttr4 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("def")); - - booleanAttrT1 = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(true)); - booleanAttrT2 = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(true)); - booleanAttrF1 = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - booleanAttrF2 = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - - intAttr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); - intAttr1a = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); - intAttr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(2)); - intAttr0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); - intAttrNeg1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(-1)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - } - - - - - /** - * String (matching case) - */ - @Test - public void testString_Equal() { - - // String exact match - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_STRING_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check "abc" with "abc" - separate string objects with same value - arguments.add(stringAttr1); - arguments.add(stringAttr2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check "abc" with "ABC" (not same) - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(stringAttr3); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - - - /** - * Boolean - */ - @Test - public void testBoolean_Equal() { - - // String exact match - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_BOOLEAN_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_BOOLEAN_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check separate objects with same value - arguments.add(booleanAttrT1); - arguments.add(booleanAttrT2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check different values - arguments.clear(); - arguments.add(booleanAttrT1); - arguments.add(booleanAttrF1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - - /** - * Integer - */ - @Test - public void testInteger_Equal() { - - // String exact match - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_INTEGER_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_INTEGER_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check separate objects with same value - arguments.add(intAttr1); - arguments.add(intAttr1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check not same - arguments.clear(); - arguments.add(intAttr1); - arguments.add(intAttr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - arguments.clear(); - arguments.add(intAttr1); - arguments.add(intAttrNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - - - /** - * Double - */ - @Test - public void testDouble_Equal() { - FunctionArgumentAttributeValue attr1 = null; - FunctionArgumentAttributeValue attr1a = null; - FunctionArgumentAttributeValue attr2 = null; - FunctionArgumentAttributeValue attrNeg1 = null; - try { - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.0)); - attr1a = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.0)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(2.4)); - attrNeg1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-1.0)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - // String exact match - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_DOUBLE_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DOUBLE_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check separate objects with the same value - arguments.add(attr1); - arguments.add(attr1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check not same - arguments.clear(); - arguments.add(attr1); - arguments.add(attr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - arguments.clear(); - arguments.add(attr1); - arguments.add(attrNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - - - - - /** - * Date - */ - @Test - public void testDate_Equal() { - Calendar calendar = Calendar.getInstance(); - Date today = calendar.getTime(); - Date longAgo = new Date(1234); - // create a date that is different than "today" but within the same day (i.e. has a different hour) - if (calendar.get(Calendar.HOUR_OF_DAY) > 3) { - calendar.set(Calendar.HOUR_OF_DAY, 3); - } else { - calendar.set(Calendar.HOUR_OF_DAY, 5); - } - Date todayPlus = calendar.getTime(); - - - FunctionArgumentAttributeValue attrToday = null; - FunctionArgumentAttributeValue attrToday2 = null; - FunctionArgumentAttributeValue attrLaterToday = null; - FunctionArgumentAttributeValue attrYesterday = null; - try { - attrToday = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(today)); - attrToday2 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(today)); - attrLaterToday = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(todayPlus)); - attrYesterday = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(longAgo)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - // String exact match - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_DATE_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATE_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check separate objects with the same value - arguments.add(attrToday); - arguments.add(attrToday2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check not same - arguments.clear(); - arguments.add(attrToday); - arguments.add(attrYesterday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // Date objects with different times but within the same day should match - arguments.clear(); - arguments.add(attrToday); - arguments.add(attrLaterToday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - - - - /** - * Time - */ - @Test - public void testTime_Equal() { - - Date now = new Date(); - Date now2 = new Date(now.getTime()); - Date notNow = new Date(now.getTime() - 100000); - - FunctionArgumentAttributeValue attrNow = null; - FunctionArgumentAttributeValue attrNow2 = null; - FunctionArgumentAttributeValue attrNotNow = null; - try { - attrNow = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(now)); - attrNow2 = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(now2)); - attrNotNow = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(notNow)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - // String exact match - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_TIME_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_TIME_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check separate objects with the same value - arguments.add(attrNow); - arguments.add(attrNow2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check not same - arguments.clear(); - arguments.add(attrNow); - arguments.add(attrNotNow); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - - - - /** - * DateTime - */ - @Test - public void testDateTime_Equal() { - Calendar calendar = Calendar.getInstance(); - Date today = calendar.getTime(); - Date longAgo = new Date(1234); - // create a dateTime that is different than "today" changing only the Timezone - if (calendar.get(Calendar.ZONE_OFFSET) > 3) { - calendar.set(Calendar.ZONE_OFFSET, 3); - } else { - calendar.set(Calendar.ZONE_OFFSET, 5); - } - Date todayPlus = calendar.getTime(); - - - FunctionArgumentAttributeValue attrToday = null; - FunctionArgumentAttributeValue attrToday2 = null; - FunctionArgumentAttributeValue attrLaterToday = null; - FunctionArgumentAttributeValue attrYesterday = null; - try { - attrToday = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(today)); - attrToday2 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(today)); - attrLaterToday = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(todayPlus)); - attrYesterday = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(longAgo)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - // String exact match - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_DATETIME_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATETIME_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check separate objects with the same value - arguments.add(attrToday); - arguments.add(attrToday2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check not same - arguments.clear(); - arguments.add(attrToday); - arguments.add(attrYesterday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // DateTime with different Zones should not match - arguments.clear(); - arguments.add(attrToday); - arguments.add(attrLaterToday); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - - /** - * dayTimeDuration - Version1 - */ - @Test - public void testDayTimeDuration_Equal_V1() { - - XPathDayTimeDuration dur1 = new XPathDayTimeDuration(1, 3, 5, 12, 38); - XPathDayTimeDuration dur2 = new XPathDayTimeDuration(1, 3, 5, 12, 38); - XPathDayTimeDuration differentDur = new XPathDayTimeDuration(-1, 4, 7, 5, 33); - - FunctionArgumentAttributeValue attrDur1 = null; - FunctionArgumentAttributeValue attrDur2 = null; - FunctionArgumentAttributeValue attrDifferentDur = null; - try { - attrDur1 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(dur1)); - attrDur2 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(dur2)); - attrDifferentDur = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(differentDur)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_DAYTIMEDURATION_EQUAL_VERSION1; - - // check identity and type of the thing created - assertEquals(XACML1.ID_FUNCTION_DAYTIMEDURATION_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_DAYTIMEDURATION.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check separate objects with the same value - arguments.add(attrDur1); - arguments.add(attrDur2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check not same - arguments.clear(); - arguments.add(attrDur1); - arguments.add(attrDifferentDur); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - - /** - * dayTimeDuration - Current version - */ - @Test - public void testDayTimeDuration_Equal() { - - XPathDayTimeDuration dur1 = new XPathDayTimeDuration(1, 3, 5, 12, 38); - XPathDayTimeDuration dur2 = new XPathDayTimeDuration(1, 3, 5, 12, 38); - XPathDayTimeDuration differentDur = new XPathDayTimeDuration(-1, 4, 7, 5, 33); - - FunctionArgumentAttributeValue attrDur1 = null; - FunctionArgumentAttributeValue attrDur2 = null; - FunctionArgumentAttributeValue attrDifferentDur = null; - try { - attrDur1 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(dur1)); - attrDur2 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(dur2)); - attrDifferentDur = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(differentDur)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_DAYTIMEDURATION_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DAYTIMEDURATION_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_DAYTIMEDURATION.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check separate objects with the same value - arguments.add(attrDur1); - arguments.add(attrDur2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check not same - arguments.clear(); - arguments.add(attrDur1); - arguments.add(attrDifferentDur); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - - - /** - * dayTimeDuration - Version1 - */ - @Test - public void testYearMonthDuration_Equal_V1() { - - XPathYearMonthDuration dur1 = new XPathYearMonthDuration(1, 3, 5); - XPathYearMonthDuration dur2 = new XPathYearMonthDuration(1, 3, 5); - XPathYearMonthDuration differentDur = new XPathYearMonthDuration(-1, 4, 7); - - FunctionArgumentAttributeValue attrDur1 = null; - FunctionArgumentAttributeValue attrDur2 = null; - FunctionArgumentAttributeValue attrDifferentDur = null; - try { - attrDur1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(dur1)); - attrDur2 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(dur2)); - attrDifferentDur = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(differentDur)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_YEARMONTHDURATION_EQUAL_VERSION1; - - // check identity and type of the thing created - assertEquals(XACML1.ID_FUNCTION_YEARMONTHDURATION_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_YEARMONTHDURATION.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check separate objects with the same value - arguments.add(attrDur1); - arguments.add(attrDur2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check not same - arguments.clear(); - arguments.add(attrDur1); - arguments.add(attrDifferentDur); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - - - - /** - * dayTimeDuration - Current version - */ - @Test - public void testYearMonthDuration_Equal() { - - XPathYearMonthDuration dur1 = new XPathYearMonthDuration(1, 3, 5); - XPathYearMonthDuration dur2 = new XPathYearMonthDuration(1, 3, 5); - XPathYearMonthDuration differentDur = new XPathYearMonthDuration(-1, 4, 7); - - FunctionArgumentAttributeValue attrDur1 = null; - FunctionArgumentAttributeValue attrDur2 = null; - FunctionArgumentAttributeValue attrDifferentDur = null; - try { - attrDur1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(dur1)); - attrDur2 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(dur2)); - attrDifferentDur = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(differentDur)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_YEARMONTHDURATION_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_YEARMONTHDURATION_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_YEARMONTHDURATION.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check separate objects with the same value - arguments.add(attrDur1); - arguments.add(attrDur2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check not same - arguments.clear(); - arguments.add(attrDur1); - arguments.add(attrDifferentDur); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - - /** - * URI - */ - @Test - public void testAnyURI_Equal() { - - URI uri1 = null; - URI uri2 = null; - URI uriNotThere = null; - try { - uri1 = new URI("http://someplace.com/gothere"); - uri2 = new URI("http://someplace.com/gothere"); - uriNotThere = new URI("http://someplace.com/notGoingThere"); - } catch (Exception e) { - fail(e.toString()); - } - - FunctionArgumentAttributeValue attrUri1 = null; - FunctionArgumentAttributeValue attrUri2 = null; - FunctionArgumentAttributeValue attrUriNotThere = null; - try { - attrUri1 = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(uri1)); - attrUri2 = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(uri2)); - attrUriNotThere = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(uriNotThere)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_ANYURI_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_ANYURI_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_ANYURI.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check separate objects with the same value - arguments.add(attrUri1); - arguments.add(attrUri2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check not same - arguments.clear(); - arguments.add(attrUri1); - arguments.add(attrUriNotThere); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - - /** - * X500Name - */ - @Test - public void testX500Name_Equal() { - - X500Principal name1 = new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US"); - X500Principal name2 = new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US"); - X500Principal name3 = new X500Principal("CN=NotDuke, OU=NotThere, O=Oracle, C=US"); - - - FunctionArgumentAttributeValue attrName1 = null; - FunctionArgumentAttributeValue attrName1a = null; - FunctionArgumentAttributeValue attrNotSameName = null; - try { - attrName1 = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(name1)); - attrName1a = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(name2)); - attrNotSameName = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(name3)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_X500NAME_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_X500NAME_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_X500NAME.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check separate objects with the same value - arguments.add(attrName1); - arguments.add(attrName1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check not same - arguments.clear(); - arguments.add(attrName1); - arguments.add(attrNotSameName); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - - - /** - * RFC822Name - */ - @Test - public void testRfc822Name_Equal() { - - RFC822Name name1 = null; - RFC822Name name1a = null; - RFC822Name differentLocalName = null; - RFC822Name differentDomainName = null; - RFC822Name localCaseName = null; - RFC822Name domainCaseName = null; - @SuppressWarnings("unused") - RFC822Name noAtName = null; - - try { - name1 = RFC822Name.newInstance("localPart@DomainPart"); - name1a = RFC822Name.newInstance("localPart@DomainPart"); - differentLocalName = RFC822Name.newInstance("differentlocalPart@DomainPart"); - differentDomainName = RFC822Name.newInstance("localPart@differentDomainPart"); - localCaseName = RFC822Name.newInstance("LOCALPart@DomainPart"); - domainCaseName = RFC822Name.newInstance("localPart@DOMAINPart"); - - - } catch (Exception e) { - fail(e.toString()); - } - - // should not be able to create a name without an @. If you try, newInstance returns null - Exception exSeen = null; - try { - noAtName = RFC822Name.newInstance("nameWithoutAnAtSign"); - } catch (Exception e) { - exSeen = e; - } - assertNotNull(exSeen); - - - FunctionArgumentAttributeValue attrName1 = null; - FunctionArgumentAttributeValue attrName1a = null; - FunctionArgumentAttributeValue attrDifferentLocalName = null; - FunctionArgumentAttributeValue attrDifferentDomainName = null; - FunctionArgumentAttributeValue attrLocalCaseName = null; - FunctionArgumentAttributeValue attrDomainCaseName = null; - try { - attrName1 = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(name1)); - attrName1a = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(name1a)); - attrDifferentLocalName = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(differentLocalName)); - attrDifferentDomainName = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(differentDomainName)); - attrLocalCaseName = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(localCaseName)); - attrDomainCaseName = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(domainCaseName)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_RFC822NAME_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_RFC822NAME_EQUAL, fd.getId()); - assertEquals(DataTypeRFC822Name.newInstance().getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check separate objects with the same value - arguments.add(attrName1); - arguments.add(attrName1a); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check not same Local - arguments.clear(); - arguments.add(attrName1); - arguments.add(attrDifferentLocalName); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // check not same Domain - arguments.clear(); - arguments.add(attrName1); - arguments.add(attrDifferentDomainName); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // test case-sensitivity in local part - arguments.clear(); - arguments.add(attrName1); - arguments.add(attrLocalCaseName); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // test non-case-sensitivity in Domain part - arguments.clear(); - arguments.add(attrName1); - arguments.add(attrDomainCaseName); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - - /** - * Hex Binary - */ - @Test - public void testHexBinary_Equal() { - HexBinary binary = null; - HexBinary sameBinary = null; - HexBinary differentBinary = null; - try { - binary = HexBinary.newInstance("e04fd020ea3a6910a2d808002b30309d"); - sameBinary = HexBinary.newInstance("e04fd020ea3a6910a2d808002b30309d"); - differentBinary = HexBinary.newInstance("f123a890ee3d"); - } catch (Exception e) { - fail(e.toString()); - } - - FunctionArgumentAttributeValue attrBinary = null; - FunctionArgumentAttributeValue attrSameBinary = null; - FunctionArgumentAttributeValue attrDifferentBinary = null;; - try { - attrBinary = new FunctionArgumentAttributeValue(DataTypes.DT_HEXBINARY.createAttributeValue(binary)); - attrSameBinary = new FunctionArgumentAttributeValue(DataTypes.DT_HEXBINARY.createAttributeValue(sameBinary)); - attrDifferentBinary = new FunctionArgumentAttributeValue(DataTypes.DT_HEXBINARY.createAttributeValue(differentBinary)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_HEXBINARY_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_HEXBINARY_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_HEXBINARY.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check separate objects with the same value - arguments.add(attrBinary); - arguments.add(attrSameBinary); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check not same - arguments.clear(); - arguments.add(attrBinary); - arguments.add(attrDifferentBinary); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } - - - /** - * Base64 Binary - */ - @Test - public void testBase64Binary_Equal() { - Base64Binary binary = null; - Base64Binary sameBinary = null; - Base64Binary differentBinary = null; - try { - binary = Base64Binary.newInstance("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz"); - sameBinary = Base64Binary.newInstance("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz"); - differentBinary = Base64Binary.newInstance("f123a890ee3d"); - } catch (Exception e) { - fail(e.toString()); - } - - FunctionArgumentAttributeValue attrBinary = null; - FunctionArgumentAttributeValue attrSameBinary = null; - FunctionArgumentAttributeValue attrDifferentBinary = null; - try { - attrBinary = new FunctionArgumentAttributeValue(DataTypes.DT_BASE64BINARY.createAttributeValue(binary)); - attrSameBinary = new FunctionArgumentAttributeValue(DataTypes.DT_BASE64BINARY.createAttributeValue(sameBinary)); - attrDifferentBinary = new FunctionArgumentAttributeValue(DataTypes.DT_BASE64BINARY.createAttributeValue(differentBinary)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_BASE64BINARY_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_BASE64BINARY_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_BASE64BINARY.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - // test normal equals and non-equals - // check separate objects with the same value - arguments.add(attrBinary); - arguments.add(attrSameBinary); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check not same - arguments.clear(); - arguments.add(attrBinary); - arguments.add(attrDifferentBinary); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - } -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionHigherOrderBagTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionHigherOrderBagTest.java deleted file mode 100644 index 9e0c72ce0..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionHigherOrderBagTest.java +++ /dev/null @@ -1,2193 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.Bag; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentBag; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionHigherOrderBagTest { - - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - - - // - // ANY-OF tests - // - - - @Test - public void testAny_of() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String f = "f"; - String g = "g"; - String h = "h"; - String j = "j"; - - - Bag bagabcdefg = null; - Bag bagbdfhj = null; - Bag bagace = null; - Bag bagb = null; - Bag bagaaacccef = null; - Bag bagInt = null; - Bag bagStringInt = null; - Bag bagEmpty = null; - Bag bagStringBooleansTrue = null; - Bag bagStringBooleansFalse = null; - - - // primitive attrs - FunctionArgumentAttributeValue attra = null; - FunctionArgumentAttributeValue attrb = null; - FunctionArgumentAttributeValue attrh = null; - - - // predicates passed as arguments - FunctionArgumentAttributeValue attrPredicateStringEqual = null; - FunctionArgumentAttributeValue attrPredicateStringIntersection = null; - FunctionArgumentAttributeValue attrPredicateBooleanFromString = null; - - try { - - // Create Bag contents - bagabcdefg = new Bag(); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); - bagbdfhj = new Bag(); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); - bagace = new Bag(); - bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagb = new Bag(); - bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagaaacccef = new Bag(); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagInt = new Bag(); - bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagStringInt = new Bag(); - bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagEmpty = new Bag(); - bagStringBooleansTrue = new Bag(); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); - bagStringBooleansFalse = new Bag(); - bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); - - - // create primitive attrs - attra = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(a)); - attrb = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(b)); - attrh = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(h)); - - - // predicates passed as function arguments - attrPredicateStringEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_EQUAL)); - attrPredicateStringIntersection = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_INTERSECTION)); - attrPredicateBooleanFromString = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_BOOLEAN_FROM_STRING)); - - } catch (Exception ex) { - fail("creating attribute e="+ ex); - } - - // make into attributes - FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); - FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); - FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); - FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); - FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); - FunctionArgumentBag attrBagStringBooleansTrue = new FunctionArgumentBag(bagStringBooleansTrue); - FunctionArgumentBag attrBagStringBooleansFalse = new FunctionArgumentBag(bagStringBooleansFalse); - - FunctionDefinitionHigherOrderBag fd = (FunctionDefinitionHigherOrderBag) StdFunctions.FD_ANY_OF; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_ANY_OF, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - // normal match - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attra); - arguments.add(attrBagabcdefg); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // bag in first position - match - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrBagabcdefg); - arguments.add(attra); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // normal no-match - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attra); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // multiple primitives - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrh); - arguments.add(attrb); - arguments.add(attrBagace); - arguments.add(attra); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of Predicate error: function:string-equal Expected 2 arguments, got 4", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // no primitives - predicate function expects 2 - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of Predicate error: function:string-equal Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // no primitives - predicate expects only 1 arg - arguments.clear(); - arguments.add(attrPredicateBooleanFromString); - arguments.add(attrBagStringBooleansTrue); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - arguments.clear(); - arguments.add(attrPredicateBooleanFromString); - arguments.add(attrBagStringBooleansFalse); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // bag is empty - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrh); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // no bag - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrh); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of Did not get any Bag argument; must have at least 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // extra bag - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrh); - arguments.add(attrBagStringBooleansTrue); - arguments.add(attrh); - arguments.add(attrBagStringBooleansTrue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of must have only 1 bag; found one at index 2 and another at 4", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // bad predicate - arguments.clear(); - arguments.add(attrh); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of First argument expected URI, got http://www.w3.org/2001/XMLSchema#string", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // non-boolean predicate - arguments.clear(); - arguments.add(attrPredicateStringIntersection); - arguments.add(attrh); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of Predicate Function must return boolean, but 'urn:oasis:names:tc:xacml:1.0:function:string-intersection' returns 'string", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // predicate after first arg - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrPredicateStringIntersection); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of Predicate error: function:string-equal Expected data type 'string' saw 'anyURI' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bags of different types - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrh); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - // first null - arguments.clear(); - arguments.add(null); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of Predicate Function (first argument) was null", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second null - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrBagabcdefg); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of Got null argument at index 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - - @Test - public void testAll_of() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String f = "f"; - String g = "g"; - String h = "h"; - String j = "j"; - - String w = "w"; - - - Bag bagabcdefg = null; - Bag bagbdfhj = null; - Bag bagace = null; - Bag bagb = null; - Bag bagaaacccef = null; - Bag bagInt = null; - Bag bagStringInt = null; - Bag bagEmpty = null; - Bag bagStringBooleansFalse = null; - Bag bagStringBooleansTrue = null; - - - // primitive attrs - FunctionArgumentAttributeValue attra = null; - FunctionArgumentAttributeValue attrh = null; - FunctionArgumentAttributeValue attrw = null; - - - - // predicates passed as arguments - FunctionArgumentAttributeValue attrPredicateStringEqual = null; - FunctionArgumentAttributeValue attrPredicateStringIntersection = null; - FunctionArgumentAttributeValue attrPredicateStringGreaterThan = null; - FunctionArgumentAttributeValue attrPredicateBooleanFromString = null; - - try { - - // Create Bag contents - bagabcdefg = new Bag(); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); - bagbdfhj = new Bag(); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); - bagace = new Bag(); - bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagb = new Bag(); - bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagaaacccef = new Bag(); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagInt = new Bag(); - bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagStringInt = new Bag(); - bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagEmpty = new Bag(); - bagStringBooleansTrue = new Bag(); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); - bagStringBooleansFalse = new Bag(); - bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); - - - - // create primitive attrs - attra = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(a)); - attrh = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(h)); - attrw = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(w)); - - - // predicates passed as function arguments - attrPredicateStringEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_EQUAL)); - attrPredicateStringIntersection = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_INTERSECTION)); - attrPredicateStringGreaterThan = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_GREATER_THAN)); - attrPredicateBooleanFromString = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_BOOLEAN_FROM_STRING)); - - } catch (Exception ex) { - fail("creating attribute e="+ ex); - } - - // make into attributes - FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); - FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); - FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); - FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); - FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); - FunctionArgumentBag attrBagStringBooleansTrue = new FunctionArgumentBag(bagStringBooleansTrue); - FunctionArgumentBag attrBagStringBooleansFalse = new FunctionArgumentBag(bagStringBooleansFalse); - - FunctionDefinitionHigherOrderBag fd = (FunctionDefinitionHigherOrderBag) StdFunctions.FD_ALL_OF; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_ALL_OF, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - // normal match - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrw); - arguments.add(attrBagace); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // normal no-match - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attra); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // no primitives - predicate function expects 2 - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of Predicate error: function:string-equal Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // no primitives - predicate expects only 1 arg - arguments.clear(); - arguments.add(attrPredicateBooleanFromString); - arguments.add(attrBagStringBooleansTrue); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - arguments.clear(); - arguments.add(attrPredicateBooleanFromString); - arguments.add(attrBagStringBooleansFalse); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // bag is empty - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrh); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // no bag - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrh); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of Did not get any Bag argument; must have at least 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // extra bag - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrh); - arguments.add(attrBagStringBooleansTrue); - arguments.add(attrh); - arguments.add(attrBagStringBooleansTrue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of must have only 1 bag; found one at index 2 and another at 4", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // bad predicate - arguments.clear(); - arguments.add(attrh); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of First argument expected URI, got http://www.w3.org/2001/XMLSchema#string", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // non-boolean predicate - arguments.clear(); - arguments.add(attrPredicateStringIntersection); - arguments.add(attrh); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of Predicate Function must return boolean, but 'urn:oasis:names:tc:xacml:1.0:function:string-intersection' returns 'string", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // predicate after first arg - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrPredicateStringIntersection); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of Predicate error: function:string-greater-than Expected data type 'string' saw 'anyURI' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bags of different types - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrh); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - // first null - arguments.clear(); - arguments.add(null); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of Predicate Function (first argument) was null", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second null - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagabcdefg); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of Got null argument at index 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - - - - - - - - - - @Test - public void testAny_of_any() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String f = "f"; - String g = "g"; - String h = "h"; - String j = "j"; - - String w = "w"; - - - Bag bagabcdefg = null; - Bag bagbdfhj = null; - Bag bagace = null; - Bag bagb = null; - Bag bagaaacccef = null; - Bag bagInt = null; - Bag bagStringInt = null; - Bag bagEmpty = null; - Bag bagStringBooleansFalse = null; - Bag bagStringBooleansTrue = null; - Bag bagBooleansFalse = null; - Bag bagBooleansTrue = null; - - - // primitive attrs - FunctionArgumentAttributeValue attra = null; - FunctionArgumentAttributeValue attrh = null; - FunctionArgumentAttributeValue attrw = null; - - - FunctionArgumentAttributeValue attrInt4 = null; - - - // predicates passed as arguments - FunctionArgumentAttributeValue attrPredicateStringEqual = null; - FunctionArgumentAttributeValue attrPredicateStringIntersection = null; - FunctionArgumentAttributeValue attrPredicateStringGreaterThan = null; - FunctionArgumentAttributeValue attrPredicateBooleanFromString = null; - FunctionArgumentAttributeValue attrPredicateNof = null; - - try { - - // Create Bag contents - bagabcdefg = new Bag(); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); - bagbdfhj = new Bag(); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); - bagace = new Bag(); - bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagb = new Bag(); - bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagaaacccef = new Bag(); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagInt = new Bag(); - bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagStringInt = new Bag(); - bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagEmpty = new Bag(); - bagStringBooleansTrue = new Bag(); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); - bagStringBooleansFalse = new Bag(); - bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagBooleansTrue = new Bag(); - bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(true)); - bagBooleansFalse = new Bag(); - bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - - - // create primitive attrs - attra = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(a)); - attrh = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(h)); - attrw = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(w)); - - attrInt4 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(4)); - - - // predicates passed as function arguments - attrPredicateStringEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_EQUAL)); - attrPredicateStringIntersection = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_INTERSECTION)); - attrPredicateStringGreaterThan = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_GREATER_THAN)); - attrPredicateBooleanFromString = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_BOOLEAN_FROM_STRING)); - attrPredicateNof = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_N_OF)); - - } catch (Exception ex) { - fail("creating attribute e="+ ex); - } - - // make into attributes - FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); - FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); - FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); - FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); - FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); - FunctionArgumentBag attrBagStringBooleansTrue = new FunctionArgumentBag(bagStringBooleansTrue); - FunctionArgumentBag attrBagStringBooleansFalse = new FunctionArgumentBag(bagStringBooleansFalse); - FunctionArgumentBag attrBagBooleansTrue = new FunctionArgumentBag(bagBooleansTrue); - FunctionArgumentBag attrBagBooleansFalse = new FunctionArgumentBag(bagBooleansFalse); - - FunctionDefinitionHigherOrderBag fd = (FunctionDefinitionHigherOrderBag) StdFunctions.FD_ANY_OF_ANY; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_ANY_OF_ANY, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - // normal match - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrw); - arguments.add(attrBagace); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // normal no-match - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attra); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // no primitives - predicate function expects 2 - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-any Predicate error: function:string-equal Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrBagace); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // no primitives - predicate expects only 1 arg - arguments.clear(); - arguments.add(attrPredicateBooleanFromString); - arguments.add(attrBagStringBooleansTrue); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - arguments.clear(); - arguments.add(attrPredicateBooleanFromString); - arguments.add(attrBagStringBooleansFalse); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // n-of with lots of bags - success - arguments.clear(); - arguments.add(attrPredicateNof); - arguments.add(attrInt4); - arguments.add(attrBagBooleansTrue); - arguments.add(attrBagBooleansTrue); - arguments.add(attrBagBooleansTrue); - arguments.add(attrBagBooleansTrue); - arguments.add(attrBagBooleansTrue); - arguments.add(attrBagBooleansTrue); - arguments.add(attrBagBooleansTrue); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // n-of with lots of bags - fail - arguments.clear(); - arguments.add(attrPredicateNof); - arguments.add(attrInt4); - arguments.add(attrBagBooleansFalse); - arguments.add(attrBagBooleansFalse); - arguments.add(attrBagBooleansTrue); - arguments.add(attrBagBooleansTrue); - arguments.add(attrBagBooleansFalse); - arguments.add(attrBagBooleansFalse); - arguments.add(attrBagBooleansFalse); - arguments.add(attrBagBooleansFalse); - arguments.add(attrBagBooleansFalse); - arguments.add(attrBagBooleansFalse); - arguments.add(attrBagBooleansFalse); - arguments.add(attrBagBooleansFalse); - arguments.add(attrBagBooleansFalse); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - - // bag is empty - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrh); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-any Bag is empty at index 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // no bag - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrh); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-any Predicate error: function:string-greater-than Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrh); - arguments.add(attrh); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // bad predicate - arguments.clear(); - arguments.add(attrh); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-any First argument expected URI, got http://www.w3.org/2001/XMLSchema#string", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // non-boolean predicate - arguments.clear(); - arguments.add(attrPredicateStringIntersection); - arguments.add(attrh); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-any Predicate Function must return boolean, but 'urn:oasis:names:tc:xacml:1.0:function:string-intersection' returns 'string", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // predicate after first arg - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrPredicateStringIntersection); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-any Predicate error: function:string-greater-than Expected data type 'string' saw 'anyURI' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bags of different types - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrh); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first null - arguments.clear(); - arguments.add(null); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-any Predicate Function (first argument) was null", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second null - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagabcdefg); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-any Got null argument at index 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - - - - - - - - - - - - @Test - public void testAll_of_any() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String f = "f"; - String g = "g"; - String h = "h"; - String j = "j"; - - String w = "w"; - String x = "x"; - - - Bag bagabcdefg = null; - Bag bagbdfhj = null; - Bag bagace = null; - Bag bagb = null; - Bag bagaaacccef = null; - Bag bagawx = null; - Bag bagInt = null; - Bag bagStringInt = null; - Bag bagEmpty = null; - Bag bagStringBooleansFalse = null; - Bag bagStringBooleansTrue = null; - Bag bagBooleansFalse = null; - Bag bagBooleansTrue = null; - - - // primitive attrs - FunctionArgumentAttributeValue attra = null; - FunctionArgumentAttributeValue attrh = null; - - - - - // predicates passed as arguments - FunctionArgumentAttributeValue attrPredicateStringEqual = null; - FunctionArgumentAttributeValue attrPredicateStringIntersection = null; - FunctionArgumentAttributeValue attrPredicateStringLessThan = null; - FunctionArgumentAttributeValue attrPredicateStringGreaterThan = null; - FunctionArgumentAttributeValue attrPredicateBooleanFromString = null; - - try { - - // Create Bag contents - bagabcdefg = new Bag(); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); - bagbdfhj = new Bag(); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); - bagace = new Bag(); - bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagb = new Bag(); - bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagaaacccef = new Bag(); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagawx = new Bag(); - bagawx.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagawx.add(DataTypes.DT_STRING.createAttributeValue(w)); - bagawx.add(DataTypes.DT_STRING.createAttributeValue(x)); - bagInt = new Bag(); - bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagStringInt = new Bag(); - bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagEmpty = new Bag(); - bagStringBooleansTrue = new Bag(); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); - bagStringBooleansFalse = new Bag(); - bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagBooleansTrue = new Bag(); - bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(true)); - bagBooleansFalse = new Bag(); - bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - - - // create primitive attrs - attra = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(a)); - attrh = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(h)); - - - - // predicates passed as function arguments - attrPredicateStringEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_EQUAL)); - attrPredicateStringIntersection = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_INTERSECTION)); - attrPredicateStringLessThan = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_LESS_THAN)); - attrPredicateStringGreaterThan = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_GREATER_THAN)); - attrPredicateBooleanFromString = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_BOOLEAN_FROM_STRING)); - - } catch (Exception ex) { - fail("creating attribute e="+ ex); - } - - // make into attributes - FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); - FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); - FunctionArgumentBag attrBagawx = new FunctionArgumentBag(bagawx); - FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); - FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); - FunctionArgumentBag attrBagStringBooleansTrue = new FunctionArgumentBag(bagStringBooleansTrue); - - FunctionDefinitionHigherOrderBag fd = (FunctionDefinitionHigherOrderBag) StdFunctions.FD_ALL_OF_ANY; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_ALL_OF_ANY, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - // normal match - arguments.clear(); - arguments.add(attrPredicateStringLessThan); - arguments.add(attrBagabcdefg); - arguments.add(attrBagawx); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // normal no-match - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagace); - arguments.add(attrBagawx); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // primitive instead of bag - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attra); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-any 2nd argument must be bag, got 'string'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrBagace); - arguments.add(attra); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-any 3rd argument must be bag, got 'string'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // no primitives - predicate expects only 1 arg - arguments.clear(); - arguments.add(attrPredicateBooleanFromString); - arguments.add(attrBagStringBooleansTrue); - arguments.add(attrBagStringBooleansTrue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-any Predicate error: function:boolean-from-string Expected 1 arguments, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - - // bag is empty - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagace); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagEmpty); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // no bag - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrh); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-any Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // bad predicate - arguments.clear(); - arguments.add(attrh); - arguments.add(attrBagStringInt); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-any First argument expected URI, got http://www.w3.org/2001/XMLSchema#string", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // non-boolean predicate - arguments.clear(); - arguments.add(attrPredicateStringIntersection); - arguments.add(attrBagStringInt); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-any Predicate Function must return boolean, but 'urn:oasis:names:tc:xacml:1.0:function:string-intersection' returns 'string", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // predicate after first arg - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrPredicateStringIntersection); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-any 2nd argument must be bag, got 'anyURI'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bags of different types - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagace); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-any Predicate error: function:string-greater-than Expected data type 'string' saw 'integer' at arg index 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // no args - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-any Expected at least 2 arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // one arg - arguments.clear(); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-any Expected at least 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many args - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-any Expected 3 arguments, got 4", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // first null - arguments.clear(); - arguments.add(null); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-any Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second null - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagabcdefg); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-any 3rd argument must be bag, got 'null'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - - - - - - - - - @Test - public void testAny_of_all() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String f = "f"; - String g = "g"; - String h = "h"; - String j = "j"; - - String w = "w"; - String x = "x"; - - - Bag bagabcdefg = null; - Bag bagbdfhj = null; - Bag bagace = null; - Bag bagb = null; - Bag bagaaacccef = null; - Bag bagewx = null; - Bag bagInt = null; - Bag bagStringInt = null; - Bag bagEmpty = null; - Bag bagStringBooleansFalse = null; - Bag bagStringBooleansTrue = null; - Bag bagBooleansFalse = null; - Bag bagBooleansTrue = null; - - - // primitive attrs - FunctionArgumentAttributeValue attra = null; - FunctionArgumentAttributeValue attrh = null; - - - - - // predicates passed as arguments - FunctionArgumentAttributeValue attrPredicateStringEqual = null; - FunctionArgumentAttributeValue attrPredicateStringIntersection = null; - FunctionArgumentAttributeValue attrPredicateStringGreaterThanOrEqual = null; - FunctionArgumentAttributeValue attrPredicateStringGreaterThan = null; - FunctionArgumentAttributeValue attrPredicateBooleanFromString = null; - - try { - - // Create Bag contents - bagabcdefg = new Bag(); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); - bagbdfhj = new Bag(); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); - bagace = new Bag(); - bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagb = new Bag(); - bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagaaacccef = new Bag(); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagewx = new Bag(); - bagewx.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagewx.add(DataTypes.DT_STRING.createAttributeValue(w)); - bagewx.add(DataTypes.DT_STRING.createAttributeValue(x)); - bagInt = new Bag(); - bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagStringInt = new Bag(); - bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagEmpty = new Bag(); - bagStringBooleansTrue = new Bag(); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); - bagStringBooleansFalse = new Bag(); - bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagBooleansTrue = new Bag(); - bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(true)); - bagBooleansFalse = new Bag(); - bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - - - // create primitive attrs - attra = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(a)); - attrh = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(h)); - - - - // predicates passed as function arguments - attrPredicateStringEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_EQUAL)); - attrPredicateStringIntersection = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_INTERSECTION)); - attrPredicateStringGreaterThanOrEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_GREATER_THAN_OR_EQUAL)); - attrPredicateStringGreaterThan = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_GREATER_THAN)); - attrPredicateBooleanFromString = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_BOOLEAN_FROM_STRING)); - - } catch (Exception ex) { - fail("creating attribute e="+ ex); - } - - // make into attributes - FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); - FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); - FunctionArgumentBag attrBagewx = new FunctionArgumentBag(bagewx); - FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); - FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); - FunctionArgumentBag attrBagStringBooleansTrue = new FunctionArgumentBag(bagStringBooleansTrue); - - FunctionDefinitionHigherOrderBag fd = (FunctionDefinitionHigherOrderBag) StdFunctions.FD_ANY_OF_ALL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_ANY_OF_ALL, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - // normal match - arguments.clear(); - arguments.add(attrPredicateStringGreaterThanOrEqual); - arguments.add(attrBagewx); - arguments.add(attrBagace); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // normal no-match - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagace); - arguments.add(attrBagewx); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // primitive instead of bag - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attra); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-all 2nd argument must be bag, got 'string'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrBagace); - arguments.add(attra); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-all 3rd argument must be bag, got 'string'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // no primitives - predicate expects only 1 arg - arguments.clear(); - arguments.add(attrPredicateBooleanFromString); - arguments.add(attrBagStringBooleansTrue); - arguments.add(attrBagStringBooleansTrue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-all Predicate error: function:boolean-from-string Expected 1 arguments, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bag is empty - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagace); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagEmpty); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // no bag - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrh); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-all Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // bad predicate - arguments.clear(); - arguments.add(attrh); - arguments.add(attrBagStringInt); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-all First argument expected URI, got http://www.w3.org/2001/XMLSchema#string", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // non-boolean predicate - arguments.clear(); - arguments.add(attrPredicateStringIntersection); - arguments.add(attrBagStringInt); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-all Predicate Function must return boolean, but 'urn:oasis:names:tc:xacml:1.0:function:string-intersection' returns 'string", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // predicate after first arg - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrPredicateStringIntersection); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-all 2nd argument must be bag, got 'anyURI'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bags of different types - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagace); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-all Predicate error: function:string-greater-than Expected data type 'string' saw 'integer' at arg index 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // no args - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-all Expected at least 2 arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // one arg - arguments.clear(); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-all Expected at least 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many args - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-all Expected 3 arguments, got 4", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // first null - arguments.clear(); - arguments.add(null); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-all Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second null - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagabcdefg); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:any-of-all 3rd argument must be bag, got 'null'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - - - @Test - public void testAll_of_all() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String f = "f"; - String g = "g"; - String h = "h"; - String j = "j"; - - String w = "w"; - String x = "x"; - - - Bag bagabcdefg = null; - Bag bagbdfhj = null; - Bag bagace = null; - Bag bagb = null; - Bag bagaaacccef = null; - Bag bagawx = null; - Bag bagwx = null; - Bag bagInt = null; - Bag bagStringInt = null; - Bag bagEmpty = null; - Bag bagStringBooleansFalse = null; - Bag bagStringBooleansTrue = null; - Bag bagBooleansFalse = null; - Bag bagBooleansTrue = null; - - - // primitive attrs - FunctionArgumentAttributeValue attra = null; - FunctionArgumentAttributeValue attrh = null; - - - - - // predicates passed as arguments - FunctionArgumentAttributeValue attrPredicateStringEqual = null; - FunctionArgumentAttributeValue attrPredicateStringIntersection = null; - FunctionArgumentAttributeValue attrPredicateStringGreaterThan = null; - FunctionArgumentAttributeValue attrPredicateBooleanFromString = null; - - try { - - // Create Bag contents - bagabcdefg = new Bag(); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); - bagbdfhj = new Bag(); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); - bagace = new Bag(); - bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagb = new Bag(); - bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagaaacccef = new Bag(); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagawx = new Bag(); - bagawx.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagawx.add(DataTypes.DT_STRING.createAttributeValue(w)); - bagawx.add(DataTypes.DT_STRING.createAttributeValue(x)); - bagwx = new Bag(); - bagwx.add(DataTypes.DT_STRING.createAttributeValue(w)); - bagwx.add(DataTypes.DT_STRING.createAttributeValue(x)); - bagInt = new Bag(); - bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagStringInt = new Bag(); - bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagEmpty = new Bag(); - bagStringBooleansTrue = new Bag(); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); - bagStringBooleansFalse = new Bag(); - bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagBooleansTrue = new Bag(); - bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(true)); - bagBooleansFalse = new Bag(); - bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - - - // create primitive attrs - attra = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(a)); - attrh = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(h)); - - - - // predicates passed as function arguments - attrPredicateStringEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_EQUAL)); - attrPredicateStringIntersection = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_INTERSECTION)); - attrPredicateStringGreaterThan = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_GREATER_THAN)); - attrPredicateBooleanFromString = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_BOOLEAN_FROM_STRING)); - - } catch (Exception ex) { - fail("creating attribute e="+ ex); - } - - // make into attributes - FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); - FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); - FunctionArgumentBag attrBagawx = new FunctionArgumentBag(bagawx); - FunctionArgumentBag attrBagwx = new FunctionArgumentBag(bagwx); - FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); - FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); - FunctionArgumentBag attrBagStringBooleansTrue = new FunctionArgumentBag(bagStringBooleansTrue); - - FunctionDefinitionHigherOrderBag fd = (FunctionDefinitionHigherOrderBag) StdFunctions.FD_ALL_OF_ALL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_ALL_OF_ALL, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - // normal match - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagwx); - arguments.add(attrBagace); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // normal no-match - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagawx); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagace); - arguments.add(attrBagwx); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // primitive instead of bag - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attra); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-all 2nd argument must be bag, got 'string'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrPredicateStringEqual); - arguments.add(attrBagace); - arguments.add(attra); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-all 3rd argument must be bag, got 'string'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // no primitives - predicate expects only 1 arg - arguments.clear(); - arguments.add(attrPredicateBooleanFromString); - arguments.add(attrBagStringBooleansTrue); - arguments.add(attrBagStringBooleansTrue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-all Predicate error: function:boolean-from-string Expected 1 arguments, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bag is empty - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagace); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagEmpty); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // no bag - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrh); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-all Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // bad predicate - arguments.clear(); - arguments.add(attrh); - arguments.add(attrBagStringInt); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-all First argument expected URI, got http://www.w3.org/2001/XMLSchema#string", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // non-boolean predicate - arguments.clear(); - arguments.add(attrPredicateStringIntersection); - arguments.add(attrBagStringInt); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-all Predicate Function must return boolean, but 'urn:oasis:names:tc:xacml:1.0:function:string-intersection' returns 'string", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // predicate after first arg - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrPredicateStringIntersection); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-all 2nd argument must be bag, got 'anyURI'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bags of different types - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagwx); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-all Predicate error: function:string-greater-than Expected data type 'string' saw 'integer' at arg index 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // no args - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-all Expected at least 2 arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // one arg - arguments.clear(); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-all Expected at least 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many args - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-all Expected 3 arguments, got 4", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // first null - arguments.clear(); - arguments.add(null); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-all Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second null - arguments.clear(); - arguments.add(attrPredicateStringGreaterThan); - arguments.add(attrBagabcdefg); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:all-of-all 3rd argument must be bag, got 'null'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - - - - - - - @Test - public void testMap() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String f = "f"; - String g = "g"; - String h = "h"; - String j = "j"; - - - Bag bagabcdefg = null; - Bag bagbdfhj = null; - Bag bagace = null; - Bag bagb = null; - Bag bagaaacccef = null; - Bag bagInt = null; - Bag bagStringInt = null; - Bag bagEmpty = null; - Bag bagStringBooleansFalse = null; - Bag bagStringBooleansTrue = null; - Bag bagInt123 = null; - Bag bagInt789 = null; - - - // primitive attrs - FunctionArgumentAttributeValue attrh = null; - FunctionArgumentAttributeValue attrInt7 = null; - - - - // predicates passed as arguments - FunctionArgumentAttributeValue attrPredicateStringNormalizeToLowerCase = null; - FunctionArgumentAttributeValue attrPredicateIntegerEqual = null; - FunctionArgumentAttributeValue attrPredicateIntegerAdd = null; - - try { - - // Create Bag contents - bagabcdefg = new Bag(); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); - bagbdfhj = new Bag(); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); - bagace = new Bag(); - bagace.add(DataTypes.DT_STRING.createAttributeValue("A")); - bagace.add(DataTypes.DT_STRING.createAttributeValue("C")); - bagace.add(DataTypes.DT_STRING.createAttributeValue("E")); - bagb = new Bag(); - bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagaaacccef = new Bag(); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagInt = new Bag(); - bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagStringInt = new Bag(); - bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); - - bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagEmpty = new Bag(); - bagStringBooleansTrue = new Bag(); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); - bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); - bagStringBooleansFalse = new Bag(); - bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); - bagInt123 = new Bag(); - bagInt123.add(DataTypes.DT_INTEGER.createAttributeValue(1)); - bagInt123.add(DataTypes.DT_INTEGER.createAttributeValue(2)); - bagInt123.add(DataTypes.DT_INTEGER.createAttributeValue(3)); - bagInt789 = new Bag(); - bagInt789.add(DataTypes.DT_INTEGER.createAttributeValue(7)); - bagInt789.add(DataTypes.DT_INTEGER.createAttributeValue(8)); - bagInt789.add(DataTypes.DT_INTEGER.createAttributeValue(9)); - - - - // create primitive attrs - attrh = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(h)); - attrInt7 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(7)); - - - // predicates passed as function arguments - attrPredicateStringNormalizeToLowerCase = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_NORMALIZE_TO_LOWER_CASE)); - attrPredicateIntegerEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_INTEGER_EQUAL)); - attrPredicateIntegerAdd = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_INTEGER_ADD)); - - } catch (Exception ex) { - fail("creating attribute e="+ ex); - } - - // make into attributes - FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); - FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); - FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); - FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); - FunctionArgumentBag attrBagStringBooleansTrue = new FunctionArgumentBag(bagStringBooleansTrue); - FunctionArgumentBag attrBagInt789 = new FunctionArgumentBag(bagInt789); - - FunctionDefinitionHigherOrderBag fd = (FunctionDefinitionHigherOrderBag) StdFunctions.FD_MAP; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_MAP, fd.getId()); - assertNull( fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertTrue(fd.returnsBag()); - - // normal match - arguments.clear(); - arguments.add(attrPredicateStringNormalizeToLowerCase); - arguments.add(attrBagace); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertTrue(res.isBag()); - Bag bag = res.getBag(); - assertEquals(3, bag.size()); - List> bagAttributes = bag.getAttributeValueList(); - try { - assertTrue(bagAttributes.contains(DataTypes.DT_STRING.createAttributeValue("a"))); - assertFalse(bagAttributes.contains(DataTypes.DT_STRING.createAttributeValue("A"))); - assertTrue(bagAttributes.contains(DataTypes.DT_STRING.createAttributeValue("c"))); - assertFalse(bagAttributes.contains(DataTypes.DT_STRING.createAttributeValue("C"))); - assertTrue(bagAttributes.contains(DataTypes.DT_STRING.createAttributeValue("e"))); - assertFalse(bagAttributes.contains(DataTypes.DT_STRING.createAttributeValue("E"))); - } catch (Exception ex) { - fail("checking result e="+ex); - } - - // 2-input predicate - arguments.clear(); - arguments.add(attrPredicateIntegerAdd); - arguments.add(attrInt7); - arguments.add(attrBagInt789); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertTrue(res.isBag()); - bag = res.getBag(); - assertEquals(3, bag.size()); - bagAttributes = bag.getAttributeValueList(); - try { - assertTrue(bagAttributes.contains(DataTypes.DT_INTEGER.createAttributeValue("14"))); - assertTrue(bagAttributes.contains(DataTypes.DT_INTEGER.createAttributeValue("15"))); - assertTrue(bagAttributes.contains(DataTypes.DT_INTEGER.createAttributeValue("16"))); - } catch (Exception ex) { - fail("checking result e="+ex); - } - - - // predicate returns booleans - arguments.clear(); - arguments.add(attrPredicateIntegerEqual); - arguments.add(attrInt7); - arguments.add(attrBagInt789); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertTrue(res.isBag()); - bag = res.getBag(); - assertEquals(3, bag.size()); - bagAttributes = bag.getAttributeValueList(); - try { - assertEquals(bagAttributes.get(0), (DataTypes.DT_BOOLEAN.createAttributeValue(true))); - assertEquals(bagAttributes.get(1), (DataTypes.DT_BOOLEAN.createAttributeValue(false))); - assertEquals(bagAttributes.get(2), (DataTypes.DT_BOOLEAN.createAttributeValue(false))); - } catch (Exception ex) { - fail("checking result e="+ex); - } - - // predicate returns bag - - - - // no primitives - predicate function expects 2 - arguments.clear(); - arguments.add(attrPredicateIntegerAdd); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:map Predicate error: function:integer-add Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bag is empty - arguments.clear(); - arguments.add(attrPredicateStringNormalizeToLowerCase); - arguments.add(attrh); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertTrue(res.isBag()); - bag = res.getBag(); - assertEquals(0, bag.size());; - - // no bag - arguments.clear(); - arguments.add(attrPredicateStringNormalizeToLowerCase); - arguments.add(attrh); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:map Did not get any Bag argument; must have at least 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // extra bag - arguments.clear(); - arguments.add(attrPredicateStringNormalizeToLowerCase); - arguments.add(attrh); - arguments.add(attrBagStringBooleansTrue); - arguments.add(attrh); - arguments.add(attrBagStringBooleansTrue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:map must have only 1 bag; found one at index 2 and another at 4", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // bad predicate - arguments.clear(); - arguments.add(attrh); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:map First argument expected URI, got http://www.w3.org/2001/XMLSchema#string", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // predicate gets unexpected number of args - arguments.clear(); - arguments.add(attrPredicateStringNormalizeToLowerCase); - arguments.add(attrh); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:map Predicate error: function:string-normalize-to-lower-case Expected 1 arguments, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // predicate gets bad primitive type - arguments.clear(); - arguments.add(attrPredicateStringNormalizeToLowerCase); - arguments.add(attrPredicateStringNormalizeToLowerCase); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:map Predicate error: function:string-normalize-to-lower-case Expected 1 arguments, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bags of different types - arguments.clear(); - arguments.add(attrPredicateStringNormalizeToLowerCase); - arguments.add(attrh); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - // first null - arguments.clear(); - arguments.add(null); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:map Predicate Function (first argument) was null", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second null - arguments.clear(); - arguments.add(attrPredicateStringNormalizeToLowerCase); - arguments.add(attrBagabcdefg); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:map Got null argument at index 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionHomogeneousSimpleTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionHomogeneousSimpleTest.java deleted file mode 100644 index 1e104a594..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionHomogeneousSimpleTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.att.research.xacml.api.Status; -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.Bag; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentBag; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * FunctionDefinitionHomogeneousSimple is an abstract class, so we have to test it by creating a sub-class. - * The constructor is tested by default when an instance of the sub-class is created for other tests. - * - * Each of these functions needs to be tested for each type of function to be sure the values are correct, - * so this is just a simple test to see that the mechanism works. - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionHomogeneousSimpleTest { - - - - @Test - public void testGetDataTypeArgs() { - - // test a simple instance using the Equality class - FunctionDefinitionEquality fd = new FunctionDefinitionEquality(XACML3.ID_FUNCTION_STRING_EQUAL, DataTypes.DT_STRING); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - } - - @Test - public void testGetNumArgs() { - // test a simple instance using the Equality class - FunctionDefinitionEquality fd = new FunctionDefinitionEquality(XACML3.ID_FUNCTION_STRING_EQUAL, DataTypes.DT_STRING); - assertEquals(new Integer(2), fd.getNumArgs()); - } - - @Test - public void testValidateArguments() { - // create some arguments to use later - FunctionArgumentAttributeValue stringAttr1 = null; - FunctionArgumentAttributeValue stringAttr2 = null; - FunctionArgumentAttributeValue stringAttr3 = null; - FunctionArgumentAttributeValue intAttr = null; - try { - stringAttr1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc")); - stringAttr2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("def")); - stringAttr3 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("ghi")); - intAttr = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionEquality fd = new FunctionDefinitionEquality(XACML3.ID_FUNCTION_STRING_EQUAL, DataTypes.DT_STRING); - List convertedValues = new ArrayList<>(); - List listFunctionArguments = new ArrayList<>(); - - // test correct # of args, both of them strings - listFunctionArguments.add(stringAttr1); - listFunctionArguments.add(stringAttr2); - Status status = fd.validateArguments(listFunctionArguments, convertedValues); - assertTrue(status.isOk()); - assertEquals(convertedValues.size(),2); - - // test too few args - listFunctionArguments.remove(1); - status = fd.validateArguments(listFunctionArguments, convertedValues); - assertFalse(status.isOk()); - assertEquals("Expected 2 arguments, got 1", status.getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", status.getStatusCode().getStatusCodeValue().stringValue()); - - // test too many args - listFunctionArguments.add(stringAttr2); - listFunctionArguments.add(stringAttr3); - status = fd.validateArguments(listFunctionArguments, convertedValues); - assertFalse(status.isOk()); - assertEquals("Expected 2 arguments, got 3", status.getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", status.getStatusCode().getStatusCodeValue().stringValue()); - - // test with null arg - listFunctionArguments.clear(); - listFunctionArguments.add(null); - listFunctionArguments.add(stringAttr1); - status = fd.validateArguments(listFunctionArguments, convertedValues); - assertFalse(status.isOk()); - assertEquals("Got null argument at arg index 0", status.getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", status.getStatusCode().getStatusCodeValue().stringValue()); - - // test function that takes 0 args -//TODO test with func that specifies 0 args? ASSUME for now that there are no such functions since a function needs to operate on something -// fail("need to test function with 0 args and various inputs - see validateArguments code"); - - - // test with one is a bag - listFunctionArguments.clear(); - listFunctionArguments.add(stringAttr1); - Bag bag = new Bag(); - FunctionArgument bagArg = new FunctionArgumentBag(bag); - listFunctionArguments.add(bagArg); - status = fd.validateArguments(listFunctionArguments, convertedValues); - assertFalse(status.isOk()); - assertEquals("Expected a simple value, saw a bag at arg index 1", status.getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", status.getStatusCode().getStatusCodeValue().stringValue()); - - // test with string and int - listFunctionArguments.clear(); - listFunctionArguments.add(stringAttr1); - listFunctionArguments.add(intAttr); - status = fd.validateArguments(listFunctionArguments, convertedValues); - assertFalse(status.isOk()); - assertEquals("Expected data type 'string' saw 'integer' at arg index 1", status.getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", status.getStatusCode().getStatusCodeValue().stringValue()); - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionLogicalTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionLogicalTest.java deleted file mode 100644 index 7530e417b..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionLogicalTest.java +++ /dev/null @@ -1,422 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionLogicalTest { - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - // use the same args for each test - FunctionArgumentAttributeValue attrT = null; - FunctionArgumentAttributeValue attrF = null; - public FunctionDefinitionLogicalTest () { - try { - attrT = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(true)); - attrF = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(false)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - } - - - @Test - public void testOR() { - FunctionArgumentAttributeValue attr5 = null; - try { - attr5 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(5)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionLogical fd = (FunctionDefinitionLogical) StdFunctions.FD_OR; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_OR, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // test normal - arguments.add(attrT); - arguments.add(attrF); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(true), resValue); - - arguments.clear(); - arguments.add(attrF); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(false), resValue); - - // test no args - arguments.clear(); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(false), resValue); - - // first true, second error - arguments.clear(); - arguments.add(attrT); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(true), resValue); - - // first false, second error - arguments.clear(); - arguments.add(attrF); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:or Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // multiple false - arguments.clear(); - arguments.add(attrF); - arguments.add(attrF); - arguments.add(attrF); - arguments.add(attrF); - arguments.add(attrF); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(false), resValue); - - // non-boolean - arguments.clear(); - arguments.add(attrF); - arguments.add(attr5); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:or Expected data type 'boolean' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // first arg error - arguments.clear(); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:or Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - @Test - public void testAND() { - FunctionArgumentAttributeValue attr5 = null; - try { - attr5 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(5)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - - FunctionDefinitionLogical fd = (FunctionDefinitionLogical) StdFunctions.FD_AND; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_AND, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // test normal - arguments.add(attrT); - arguments.add(attrF); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(false), resValue); - - arguments.clear(); - arguments.add(attrF); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(false), resValue); - - // test no args - arguments.clear(); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(true), resValue); - - // first true, second error - arguments.clear(); - arguments.add(attrT); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:and Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // first false, second error - arguments.clear(); - arguments.add(attrF); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(false), resValue); - - // multiple true - arguments.clear(); - arguments.add(attrT); - arguments.add(attrT); - arguments.add(attrT); - arguments.add(attrT); - arguments.add(attrT); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(true), resValue); - - // non-boolean - arguments.clear(); - arguments.add(attrT); - arguments.add(attr5); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals("function:and Expected data type 'boolean' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // first arg error - arguments.clear(); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals("function:and Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - @Test - public void testN_of() { - FunctionArgumentAttributeValue attr0 = null; - FunctionArgumentAttributeValue attr2 = null; - try { - attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); - attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(2)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - - FunctionDefinitionLogical fd = (FunctionDefinitionLogical) StdFunctions.FD_N_OF; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_N_OF, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // test normal - arguments.add(attr2); - arguments.add(attrT); - arguments.add(attrF); - arguments.add(attrT); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(true), resValue); - - // normal fail - arguments.clear(); - arguments.add(attr2); - arguments.add(attrT); - arguments.add(attrF); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(false), resValue); - - - // null count - arguments.clear(); - arguments.add(null); - arguments.add(attrT); - arguments.add(attrF); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(true), resValue); - - // 0 count - arguments.clear(); - arguments.add(attr0); - arguments.add(attrT); - arguments.add(attrF); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(true), resValue); - - // bad object type for count - arguments.clear(); - arguments.add(attrT); - arguments.add(attrT); - arguments.add(attrF); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:n-of For input string: \"true\"", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // count larger than list - arguments.clear(); - arguments.add(attr2); - arguments.add(attrT); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:n-of Expected 2 arguments but only 1 arguments in list after the count", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // aborts after find ok - arguments.clear(); - arguments.add(attr2); - arguments.add(attrT); - arguments.add(attrT); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(true), resValue); - - // error before find ok - arguments.clear(); - arguments.add(attr2); - arguments.add(null); - arguments.add(attrT); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:n-of Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // non-boolean in list - arguments.clear(); - arguments.add(attr2); - arguments.add(attrT); - arguments.add(attr0); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:n-of Expected data type 'boolean' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - @Test - public void testNot() { - - FunctionDefinitionLogical fd = (FunctionDefinitionLogical) StdFunctions.FD_NOT; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_NOT, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // test normal - arguments.clear(); - arguments.add(attrT); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(false), resValue); - - arguments.clear(); - arguments.add(attrF); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(true), resValue); - - - // test null/0 args - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:not Expected 1 argument, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // test 2 args - arguments.clear(); - arguments.add(attrT); - arguments.add(attrF); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:not Expected 1 argument, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionNumberTypeConversionTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionNumberTypeConversionTest.java deleted file mode 100644 index 9b2a39424..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionNumberTypeConversionTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Tests for various classes containing only one function. - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionNumberTypeConversionTest { - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - @Test - public void testDouble_to_integer() { - FunctionArgumentAttributeValue attr1 = null; - try { - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(5.432)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionNumberTypeConversion fd = (FunctionDefinitionNumberTypeConversion) StdFunctions.FD_DOUBLE_TO_INTEGER; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DOUBLE_TO_INTEGER, fd.getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - - // test normal add - arguments.add(attr1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - BigInteger resValue = (BigInteger)res.getValue().getValue(); - assertEquals(BigInteger.valueOf(5), resValue); - } - - - @Test - public void testInteger_to_double() { - FunctionArgumentAttributeValue attr1 = null; - try { - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(5)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionNumberTypeConversion fd = (FunctionDefinitionNumberTypeConversion) StdFunctions.FD_INTEGER_TO_DOUBLE; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_INTEGER_TO_DOUBLE, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - - // test normal add - arguments.add(attr1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Double resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(5.0), resValue); - } - - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionRegexpMatchTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionRegexpMatchTest.java deleted file mode 100644 index 423c4db48..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionRegexpMatchTest.java +++ /dev/null @@ -1,511 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import javax.security.auth.x500.X500Principal; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacml.std.datatypes.IPAddress; -import com.att.research.xacml.std.datatypes.RFC2396DomainName; -import com.att.research.xacml.std.datatypes.RFC822Name; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionRegexpMatchTest { - - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - - @Test - public void testString() { - String v1 = new String("abc"); - String v2 = new String("def"); - - - FunctionArgumentAttributeValue attrV1 = null; - FunctionArgumentAttributeValue attrV2 = null; - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrInteger = null; - try { - attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); - attrV2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v2)); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionRegexpMatch fd = (FunctionDefinitionRegexpMatch) StdFunctions.FD_STRING_REGEXP_MATCH; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_REGEXP_MATCH, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // match - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrV1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // no match - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrV2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // null regex - arguments.clear(); - arguments.add(null); - arguments.add(attrV2); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-regexp-match Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrV2); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-regexp-match Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null object to match - arguments.clear(); - arguments.add(attrV1); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-regexp-match Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-regexp-match Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // regex not string - arguments.clear(); - arguments.add(attrInteger); - arguments.add(attrV2); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-regexp-match Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // object to match not correct type - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrInteger); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-regexp-match Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - @Test - public void testAnyURI() { - String regexp = new String("abc"); - URI uri1 = null; - URI uri2 = null; - try { - uri1 = new URI("abc"); - uri2 = new URI("def"); - } catch (Exception e) { - fail("Unable to create URIs, e="+e); - } - - - FunctionArgumentAttributeValue attrRegexp = null; - FunctionArgumentAttributeValue attrUri1 = null; - FunctionArgumentAttributeValue attrUri2 = null; - FunctionArgumentAttributeValue attrInteger = null; - try { - attrRegexp = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(regexp)); - attrUri1 = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(uri1)); - attrUri2 = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(uri2)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionRegexpMatch fd = (FunctionDefinitionRegexpMatch) StdFunctions.FD_ANYURI_REGEXP_MATCH; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_ANYURI_REGEXP_MATCH, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // match - arguments.clear(); - arguments.add(attrRegexp); - arguments.add(attrUri1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // no match - arguments.clear(); - arguments.add(attrRegexp); - arguments.add(attrUri2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // object to match not correct type - arguments.clear(); - arguments.add(attrRegexp); - arguments.add(attrInteger); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-regexp-match Expected data type 'anyURI' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - @Test - public void testIpAddress() { - String regexp = new String(".*123.*"); - IPAddress addr1 = null; - IPAddress addr2 = null; - try { - addr1 = IPAddress.newInstance("10.123.13.14"); - addr2 = IPAddress.newInstance("10.12.13.14"); - } catch (Exception e) { - fail("Unable to create IPAddresses, e="+e); - } - - - FunctionArgumentAttributeValue attrRegexp = null; - FunctionArgumentAttributeValue attrAddr1 = null; - FunctionArgumentAttributeValue attrAddr2 = null; - FunctionArgumentAttributeValue attrInteger = null; - try { - attrRegexp = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(regexp)); - attrAddr1 = new FunctionArgumentAttributeValue(DataTypes.DT_IPADDRESS.createAttributeValue(addr1)); - attrAddr2 = new FunctionArgumentAttributeValue(DataTypes.DT_IPADDRESS.createAttributeValue(addr2)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionRegexpMatch fd = (FunctionDefinitionRegexpMatch) StdFunctions.FD_IPADDRESS_REGEXP_MATCH; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_IPADDRESS_REGEXP_MATCH, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // match - arguments.clear(); - arguments.add(attrRegexp); - arguments.add(attrAddr1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // no match - arguments.clear(); - arguments.add(attrRegexp); - arguments.add(attrAddr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // object to match not correct type - arguments.clear(); - arguments.add(attrRegexp); - arguments.add(attrInteger); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-regexp-match Expected data type 'ipAddress' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - @Test - public void testDnsName() { - String regexp = new String("abc"); - RFC2396DomainName addr1 = null; - RFC2396DomainName addr2 = null; - try { - addr1 = RFC2396DomainName.newInstance("abc"); - addr2 = RFC2396DomainName.newInstance("def"); - } catch (Exception e) { - fail("Unable to create DNSNames, e="+e); - } - - - FunctionArgumentAttributeValue attrRegexp = null; - FunctionArgumentAttributeValue attrAddr1 = null; - FunctionArgumentAttributeValue attrAddr2 = null; - FunctionArgumentAttributeValue attrInteger = null; - try { - attrRegexp = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(regexp)); - attrAddr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DNSNAME.createAttributeValue(addr1)); - attrAddr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DNSNAME.createAttributeValue(addr2)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionRegexpMatch fd = (FunctionDefinitionRegexpMatch) StdFunctions.FD_DNSNAME_REGEXP_MATCH; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DNSNAME_REGEXP_MATCH, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // match - arguments.clear(); - arguments.add(attrRegexp); - arguments.add(attrAddr1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // no match - arguments.clear(); - arguments.add(attrRegexp); - arguments.add(attrAddr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // object to match not correct type - arguments.clear(); - arguments.add(attrRegexp); - arguments.add(attrInteger); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dnsName-regexp-match Expected data type 'dnsName' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - @Test - public void testRfc822Name() { - String regexp = new String(".*abc.*"); - RFC822Name addr1 = null; - RFC822Name addr2 = null; - try { - addr1 = RFC822Name.newInstance("abc@somewhere"); - addr2 = RFC822Name.newInstance("def@somewhere"); - } catch (Exception e) { - fail("Unable to create RFC822Names, e="+e); - } - - - FunctionArgumentAttributeValue attrRegexp = null; - FunctionArgumentAttributeValue attrAddr1 = null; - FunctionArgumentAttributeValue attrAddr2 = null; - FunctionArgumentAttributeValue attrInteger = null; - try { - attrRegexp = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(regexp)); - attrAddr1 = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(addr1)); - attrAddr2 = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(addr2)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionRegexpMatch fd = (FunctionDefinitionRegexpMatch) StdFunctions.FD_RFC822NAME_REGEXP_MATCH; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_RFC822NAME_REGEXP_MATCH, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // match - arguments.clear(); - arguments.add(attrRegexp); - arguments.add(attrAddr1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // no match - arguments.clear(); - arguments.add(attrRegexp); - arguments.add(attrAddr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // object to match not correct type - arguments.clear(); - arguments.add(attrRegexp); - arguments.add(attrInteger); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:rfc822Name-regexp-match Expected data type 'rfc822Name' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - @Test - public void testX500Name() { - String regexp = new String(".*Duke.*"); - X500Principal addr1 = null; - X500Principal addr2 = null; - try { - addr1 = new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US"); - addr2 = new X500Principal("CN=Policy Engine, OU=Research, O=ATT, C=US"); - } catch (Exception e) { - fail("Unable to create X500Name, e="+e); - } - - - FunctionArgumentAttributeValue attrRegexp = null; - FunctionArgumentAttributeValue attrAddr1 = null; - FunctionArgumentAttributeValue attrAddr2 = null; - FunctionArgumentAttributeValue attrInteger = null; - try { - attrRegexp = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(regexp)); - attrAddr1 = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(addr1)); - attrAddr2 = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(addr2)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionRegexpMatch fd = (FunctionDefinitionRegexpMatch) StdFunctions.FD_X500NAME_REGEXP_MATCH; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_X500NAME_REGEXP_MATCH, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // match - arguments.clear(); - arguments.add(attrRegexp); - arguments.add(attrAddr1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // no match - arguments.clear(); - arguments.add(attrRegexp); - arguments.add(attrAddr2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // object to match not correct type - arguments.clear(); - arguments.add(attrRegexp); - arguments.add(attrInteger); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:x500Name-regexp-match Expected data type 'x500Name' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionSetTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionSetTest.java deleted file mode 100644 index 8e8497b0b..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionSetTest.java +++ /dev/null @@ -1,1903 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.junit.Test; - -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.Bag; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentBag; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionSetTest { - - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - - - // - // INTERSECTION tests - // - - - @Test - public void testString_intersection() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String f = "f"; - String g = "g"; - String h = "h"; - String j = "j"; - - - Bag bagabcdefg = null; - Bag bagbdfhj = null; - Bag bagace = null; - Bag bagb = null; - Bag bagaaacccef = null; - Bag bagInt = null; - Bag bagStringInt = null; - Bag bagEmpty = null; - - FunctionArgumentAttributeValue attrBadType = null; - - try { - bagabcdefg = new Bag(); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); - bagbdfhj = new Bag(); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); - bagace = new Bag(); - bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagb = new Bag(); - bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagaaacccef = new Bag(); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagInt = new Bag(); - bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagStringInt = new Bag(); - bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagEmpty = new Bag(); - - attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.1)); - } catch (Exception ex) { - fail("creating attribute e="+ ex); - } - - // make into attributes - FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); - FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); - FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); - FunctionArgumentBag attrBagb = new FunctionArgumentBag(bagb); - FunctionArgumentBag attrBagaaacccef = new FunctionArgumentBag(bagaaacccef); - FunctionArgumentBag attrBagInt = new FunctionArgumentBag(bagInt); - FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); - FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); - - FunctionDefinitionSet fd = (FunctionDefinitionSet) StdFunctions.FD_STRING_INTERSECTION; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_INTERSECTION, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertTrue(fd.returnsBag()); - - // normal intersection (everything in both bags, no duplicates) - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Bag bag = res.getBag(); - assertNotNull(bag); - Iterator> it = bag.getAttributeValues(); - assertEquals(7, bag.size()); - AttributeValue attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - - // several but not all intersection - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(3, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(b, attrValueObject.getValue() ); - - // no intersection - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(0, bag.size()); - - // one intersection - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagb); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(1, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(b, attrValueObject.getValue() ); - - // bag one has duplicates that do not intersect - arguments.clear(); - arguments.add(attrBagaaacccef); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(1, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(f, attrValueObject.getValue() ); - - // bag one has duplicates that do intersect - arguments.clear(); - arguments.add(attrBagaaacccef); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(3, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - attrValueObject = it.next(); - assertEquals(c, attrValueObject.getValue() ); - attrValueObject = it.next(); - assertEquals(e, attrValueObject.getValue() ); - - // bag 2 has duplicates that do not intersect - arguments.clear(); - arguments.add(attrBagbdfhj); - arguments.add(attrBagaaacccef); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(1, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(f, attrValueObject.getValue() ); - - // bag 2 has duplicates that intersect - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagaaacccef); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(3, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - attrValueObject = it.next(); - assertEquals(c, attrValueObject.getValue() ); - attrValueObject = it.next(); - assertEquals(e, attrValueObject.getValue() ); - - // first bag is empty - arguments.clear(); - arguments.add(attrBagEmpty); - arguments.add(attrBagaaacccef); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(0, bag.size()); - - // second bag is empty - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(0, bag.size()); - - // bags of different types - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(1, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagInt); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(0, bag.size()); - - // first not a bag - arguments.clear(); - arguments.add(attrBadType); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-intersection Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second not a bag - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-intersection Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // first null - arguments.clear(); - arguments.add(null); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-intersection Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second null - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-intersection Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too few args - arguments.clear(); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-intersection Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-intersection Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many args - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-intersection Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - @Test - public void testInteger_intersection() { - BigInteger a = new BigInteger("1"); - BigInteger b = new BigInteger("2"); - BigInteger c = new BigInteger("3"); - BigInteger d = new BigInteger("4"); - BigInteger e = new BigInteger("5"); - BigInteger f = new BigInteger("6"); - BigInteger g = new BigInteger("7"); - BigInteger h = new BigInteger("8"); - BigInteger j = new BigInteger("9"); - - - Bag bagabcdefg = null; - Bag bagbdfhj = null; - Bag bagace = null; - Bag bagb = null; - Bag bagaaacccef = null; - Bag bagInt = null; - Bag bagStringInt = null; - Bag bagEmpty = null; - - FunctionArgumentAttributeValue attrBadType = null; - - try { - bagabcdefg = new Bag(); - bagabcdefg.add(DataTypes.DT_INTEGER.createAttributeValue(a)); - bagabcdefg.add(DataTypes.DT_INTEGER.createAttributeValue(b)); - bagabcdefg.add(DataTypes.DT_INTEGER.createAttributeValue(c)); - bagabcdefg.add(DataTypes.DT_INTEGER.createAttributeValue(d)); - bagabcdefg.add(DataTypes.DT_INTEGER.createAttributeValue(e)); - bagabcdefg.add(DataTypes.DT_INTEGER.createAttributeValue(f)); - bagabcdefg.add(DataTypes.DT_INTEGER.createAttributeValue(g)); - bagbdfhj = new Bag(); - bagbdfhj.add(DataTypes.DT_INTEGER.createAttributeValue(b)); - bagbdfhj.add(DataTypes.DT_INTEGER.createAttributeValue(d)); - bagbdfhj.add(DataTypes.DT_INTEGER.createAttributeValue(f)); - bagbdfhj.add(DataTypes.DT_INTEGER.createAttributeValue(h)); - bagbdfhj.add(DataTypes.DT_INTEGER.createAttributeValue(j)); - bagace = new Bag(); - bagace.add(DataTypes.DT_INTEGER.createAttributeValue(a)); - bagace.add(DataTypes.DT_INTEGER.createAttributeValue(c)); - bagace.add(DataTypes.DT_INTEGER.createAttributeValue(e)); - bagb = new Bag(); - bagb.add(DataTypes.DT_INTEGER.createAttributeValue(b)); - bagaaacccef = new Bag(); - bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(e)); - bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(f)); - bagInt = new Bag(); - bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagStringInt = new Bag(); - bagStringInt.add(DataTypes.DT_STRING.createAttributeValue("abc")); - bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(1)); - bagEmpty = new Bag(); - - attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.1)); - } catch (Exception ex) { - fail("creating attribute e="+ ex); - } - - // make into attributes - FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); - FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); - FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); - FunctionArgumentBag attrBagb = new FunctionArgumentBag(bagb); - FunctionArgumentBag attrBagaaacccef = new FunctionArgumentBag(bagaaacccef); - FunctionArgumentBag attrBagInt = new FunctionArgumentBag(bagInt); - FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); - FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); - - FunctionDefinitionSet fd = (FunctionDefinitionSet) StdFunctions.FD_INTEGER_INTERSECTION; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_INTEGER_INTERSECTION, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertTrue(fd.returnsBag()); - - // normal intersection (everything in both bags, no duplicates) - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Bag bag = res.getBag(); - assertNotNull(bag); - Iterator> it = bag.getAttributeValues(); - assertEquals(7, bag.size()); - AttributeValue attrValueObject = it.next(); - assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - - // several but not all intersection - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(3, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); - assertEquals(b, attrValueObject.getValue() ); - - // no intersection - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(0, bag.size()); - - // one intersection - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagb); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(1, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); - assertEquals(b, attrValueObject.getValue() ); - - // bag one has duplicates that do not intersect - arguments.clear(); - arguments.add(attrBagaaacccef); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(1, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); - assertEquals(f, attrValueObject.getValue() ); - - // bag one has duplicates that do intersect - arguments.clear(); - arguments.add(attrBagaaacccef); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(3, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - attrValueObject = it.next(); - assertEquals(c, attrValueObject.getValue() ); - attrValueObject = it.next(); - assertEquals(e, attrValueObject.getValue() ); - - // bag 2 has duplicates that do not intersect - arguments.clear(); - arguments.add(attrBagbdfhj); - arguments.add(attrBagaaacccef); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(1, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); - assertEquals(f, attrValueObject.getValue() ); - - // bag 2 has duplicates that intersect - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagaaacccef); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(3, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - attrValueObject = it.next(); - assertEquals(c, attrValueObject.getValue() ); - attrValueObject = it.next(); - assertEquals(e, attrValueObject.getValue() ); - - // first bag is empty - arguments.clear(); - arguments.add(attrBagEmpty); - arguments.add(attrBagaaacccef); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(0, bag.size()); - - // second bag is empty - arguments.clear(); - arguments.add(attrBagbdfhj); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(0, bag.size()); - - // bags of different types - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(1, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagInt); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(1, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - - - // first not a bag - arguments.clear(); - arguments.add(attrBadType); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:integer-intersection Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second not a bag - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:integer-intersection Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // first null - arguments.clear(); - arguments.add(null); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:integer-intersection Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second null - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:integer-intersection Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too few args - arguments.clear(); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:integer-intersection Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:integer-intersection Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many args - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:integer-intersection Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - - - - - - - - - - // - // AT_LEAST_ONE_MEMBER_OF tests - // - - @Test - public void testString_at_least_one_member_of() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String f = "f"; - String g = "g"; - String h = "h"; - String j = "j"; - - - Bag bagabcdefg = null; - Bag bagbdfhj = null; - Bag bagace = null; - Bag bagb = null; - Bag bagaaaccce = null; - Bag bagInt = null; - Bag bagStringInt = null; - Bag bagEmpty = null; - - FunctionArgumentAttributeValue attrBadType = null; - - try { - bagabcdefg = new Bag(); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); - bagbdfhj = new Bag(); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); - bagace = new Bag(); - bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagb = new Bag(); - bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagaaaccce = new Bag(); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagInt = new Bag(); - bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagStringInt = new Bag(); - bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagEmpty = new Bag(); - - attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.1)); - } catch (Exception ex) { - fail("creating attribute e="+ ex); - } - - // make into attributes - FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); - FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); - FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); - FunctionArgumentBag attrBagb = new FunctionArgumentBag(bagb); - FunctionArgumentBag attrBagaaaccce = new FunctionArgumentBag(bagaaaccce); - FunctionArgumentBag attrBagInt = new FunctionArgumentBag(bagInt); - FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); - FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); - - FunctionDefinitionSet fd = (FunctionDefinitionSet) StdFunctions.FD_STRING_AT_LEAST_ONE_MEMBER_OF; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_AT_LEAST_ONE_MEMBER_OF, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - // normal intersection (everything in both bags, no duplicates) - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - - // several but not all intersection - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // no intersection - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // one intersection - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagb); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // bag one has duplicates that do not intersect - arguments.clear(); - arguments.add(attrBagaaaccce); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // bag one has duplicates that do intersect - arguments.clear(); - arguments.add(attrBagaaaccce); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // bag 2 has duplicates that do not intersect - arguments.clear(); - arguments.add(attrBagbdfhj); - arguments.add(attrBagaaaccce); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // bag 2 has duplicates that intersect - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagaaaccce); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // 2 empty bags - arguments.clear(); - arguments.add(attrBagEmpty); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first non-empty, 2nd empty - arguments.clear(); - arguments.add(attrBagaaaccce); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first empty, 2nd not empty - arguments.clear(); - arguments.add(attrBagEmpty); - arguments.add(attrBagaaaccce); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // bags of different types - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagInt); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first not a bag - arguments.clear(); - arguments.add(attrBadType); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-at-least-one-member-of Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second not a bag - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-at-least-one-member-of Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // first null - arguments.clear(); - arguments.add(null); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-at-least-one-member-of Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second null - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-at-least-one-member-of Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too few args - arguments.clear(); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-at-least-one-member-of Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-at-least-one-member-of Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many args - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-at-least-one-member-of Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - - - - - - - - - - // - // UNION tests - // - - - - - - @Test - public void testString_union() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String f = "f"; - String g = "g"; - String h = "h"; - String j = "j"; - - - Bag bagabcdefg = null; - Bag bagbdfhj = null; - Bag bagace = null; - Bag bagaaacccef = null; - Bag bagInt = null; - Bag bagStringInt = null; - Bag bagEmpty = null; - - FunctionArgumentAttributeValue attrBadType = null; - - try { - bagabcdefg = new Bag(); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); - bagbdfhj = new Bag(); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); - bagace = new Bag(); - bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagaaacccef = new Bag(); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagInt = new Bag(); - bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagStringInt = new Bag(); - bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagEmpty = new Bag(); - - attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.1)); - } catch (Exception ex) { - fail("creating attribute e="+ ex); - } - - // make into attributes - FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); - FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); - FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); - FunctionArgumentBag attrBagaaacccef = new FunctionArgumentBag(bagaaacccef); - FunctionArgumentBag attrBagInt = new FunctionArgumentBag(bagInt); - FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); - FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); - - FunctionDefinitionSet fd = (FunctionDefinitionSet) StdFunctions.FD_STRING_UNION; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_UNION, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertTrue(fd.returnsBag()); - - // normal intersection (everything in both bags, no duplicates) - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Bag bag = res.getBag(); - assertNotNull(bag); - Iterator> it = bag.getAttributeValues(); - assertEquals(7, bag.size()); - AttributeValue attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - - // several but not all union - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(8, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - - // bag one has duplicates that do not match first bag - arguments.clear(); - arguments.add(attrBagaaacccef); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(8, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - - // bag one has duplicates that do match first bag - arguments.clear(); - arguments.add(attrBagaaacccef); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(4, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - attrValueObject = it.next(); - assertEquals(c, attrValueObject.getValue() ); - attrValueObject = it.next(); - assertEquals(e, attrValueObject.getValue() ); - - // bag 2 has duplicates that do not match first bag - arguments.clear(); - arguments.add(attrBagbdfhj); - arguments.add(attrBagaaacccef); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(8, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(b, attrValueObject.getValue() ); - - // bag 2 has duplicates that do match first bag - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagaaacccef); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(4, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - attrValueObject = it.next(); - assertEquals(c, attrValueObject.getValue() ); - attrValueObject = it.next(); - assertEquals(e, attrValueObject.getValue() ); - - // two empty bags - arguments.clear(); - arguments.add(attrBagEmpty); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(0, bag.size()); - - // first bag empty, 2nd not empty - arguments.clear(); - arguments.add(attrBagEmpty); - arguments.add(attrBagaaacccef); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(4, bag.size()); - - // first bag not empty, 2nd empty - arguments.clear(); - arguments.add(attrBagaaacccef); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(4, bag.size()); - - // bags of different types - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(4, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagInt); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - bag = res.getBag(); - assertNotNull(bag); - it = bag.getAttributeValues(); - assertEquals(4, bag.size()); - attrValueObject = it.next(); - assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); - assertEquals(a, attrValueObject.getValue() ); - - // first not a bag - arguments.clear(); - arguments.add(attrBadType); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-union Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second not a bag - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-union Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // first null - arguments.clear(); - arguments.add(null); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-union Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second null - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-union Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too few args - arguments.clear(); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-union Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-union Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many args - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-union Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - - - - - - - // - // SUBSET tests - // - - @Test - public void testString_subset() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String f = "f"; - String g = "g"; - String h = "h"; - String j = "j"; - - - Bag bagabcdefg = null; - Bag bagbdfhj = null; - Bag bagace = null; - Bag bagb = null; - Bag bagaaaccce = null; - Bag bagInt = null; - Bag bagStringInt = null; - Bag bagEmpty = null; - - FunctionArgumentAttributeValue attrBadType = null; - - try { - bagabcdefg = new Bag(); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); - bagbdfhj = new Bag(); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); - bagace = new Bag(); - bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagb = new Bag(); - bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagaaaccce = new Bag(); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagInt = new Bag(); - bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagStringInt = new Bag(); - bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagEmpty = new Bag(); - - attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.1)); - } catch (Exception ex) { - fail("creating attribute e="+ ex); - } - - // make into attributes - FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); - FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); - FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); - FunctionArgumentBag attrBagb = new FunctionArgumentBag(bagb); - FunctionArgumentBag attrBagaaaccce = new FunctionArgumentBag(bagaaaccce); - FunctionArgumentBag attrBagInt = new FunctionArgumentBag(bagInt); - FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); - FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); - - FunctionDefinitionSet fd = (FunctionDefinitionSet) StdFunctions.FD_STRING_SUBSET; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_SUBSET, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - // normal intersection (everything in both bags, no duplicates) - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - - // not subset - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // subset - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - - // no intersection - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // Not - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagb); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // Subset - arguments.clear(); - arguments.add(attrBagb); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // bag one has duplicates that do not intersect - arguments.clear(); - arguments.add(attrBagaaaccce); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // bag one has duplicates that do intersect - arguments.clear(); - arguments.add(attrBagaaaccce); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // bag 2 has duplicates that do not intersect - arguments.clear(); - arguments.add(attrBagbdfhj); - arguments.add(attrBagaaaccce); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // bag 2 has duplicates that intersect - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagaaaccce); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // 2 empty bags - arguments.clear(); - arguments.add(attrBagEmpty); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first non-empty, 2nd empty - arguments.clear(); - arguments.add(attrBagaaaccce); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first empty, 2nd not empty - arguments.clear(); - arguments.add(attrBagEmpty); - arguments.add(attrBagaaaccce); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // bags of different types - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - arguments.clear(); - arguments.add(attrBagb); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagInt); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first not a bag - arguments.clear(); - arguments.add(attrBadType); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-subset Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second not a bag - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-subset Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // first null - arguments.clear(); - arguments.add(null); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-subset Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second null - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-subset Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too few args - arguments.clear(); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-subset Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-subset Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many args - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-subset Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - - - - - - - - // - // SET_EQUALS tests - // - - @Test - public void testString_set_equals() { - String a = "a"; - String b = "b"; - String c = "c"; - String d = "d"; - String e = "e"; - String f = "f"; - String g = "g"; - String h = "h"; - String j = "j"; - - - Bag bagabcdefg = null; - Bag bagbdfhj = null; - Bag bagace = null; - Bag bagb = null; - Bag bagaaaccce = null; - Bag bagInt = null; - Bag bagStringInt = null; - Bag bagEmpty = null; - - FunctionArgumentAttributeValue attrBadType = null; - - try { - bagabcdefg = new Bag(); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); - bagbdfhj = new Bag(); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); - bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); - bagace = new Bag(); - bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagb = new Bag(); - bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); - bagaaaccce = new Bag(); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); - bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(e)); - bagInt = new Bag(); - bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagStringInt = new Bag(); - bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); - bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); - bagEmpty = new Bag(); - - attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.1)); - } catch (Exception ex) { - fail("creating attribute e="+ ex); - } - - // make into attributes - FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); - FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); - FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); - FunctionArgumentBag attrBagb = new FunctionArgumentBag(bagb); - FunctionArgumentBag attrBagaaaccce = new FunctionArgumentBag(bagaaaccce); - FunctionArgumentBag attrBagInt = new FunctionArgumentBag(bagInt); - FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); - FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); - - FunctionDefinitionSet fd = (FunctionDefinitionSet) StdFunctions.FD_STRING_SET_EQUALS; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_SET_EQUALS, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - // normal intersection (everything in both bags, no duplicates) - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - - // several but not all intersection - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // no intersection - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // one intersection - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagb); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // bag one has duplicates that do not intersect - arguments.clear(); - arguments.add(attrBagaaaccce); - arguments.add(attrBagbdfhj); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // bag one has duplicates that do intersect - arguments.clear(); - arguments.add(attrBagaaaccce); - arguments.add(attrBagace); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // bag 2 has duplicates that do not intersect - arguments.clear(); - arguments.add(attrBagbdfhj); - arguments.add(attrBagaaaccce); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // bag 2 has duplicates that intersect - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagaaaccce); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // 2 empty bags - arguments.clear(); - arguments.add(attrBagEmpty); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first non-empty, 2nd empty - arguments.clear(); - arguments.add(attrBagaaaccce); - arguments.add(attrBagEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first empty, 2nd not empty - arguments.clear(); - arguments.add(attrBagEmpty); - arguments.add(attrBagaaaccce); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // bags of different types - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagStringInt); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - arguments.clear(); - arguments.add(attrBagace); - arguments.add(attrBagInt); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first not a bag - arguments.clear(); - arguments.add(attrBadType); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-set-equals Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second not a bag - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-set-equals Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // first null - arguments.clear(); - arguments.add(null); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-set-equals Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // second null - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-set-equals Got null argument", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too few args - arguments.clear(); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-set-equals Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-set-equals Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many args - arguments.clear(); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - arguments.add(attrBagabcdefg); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-set-equals Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - - - - - - - // - // - // REST OF DATA TYPES OMITTED - // because they "should" all work the same - // - // - - - - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionSpecialMatchTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionSpecialMatchTest.java deleted file mode 100644 index f2e6bdb35..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionSpecialMatchTest.java +++ /dev/null @@ -1,487 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; - -import javax.security.auth.x500.X500Principal; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.Bag; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentBag; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionSpecialMatchTest { - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - @Test - public void testX500NameMatch() { - // assume that the contents of the name components are not significant and we can treat them as simple blocks of "=" - String A = "cn=Some person"; - String B = "O=Medico Corp"; - String C = "C=US"; - String D = "DNQUALIFIER=d string"; - String E = "SURNAME=some name"; - String F = "INITIALS=inits"; - - - X500Principal abc = new X500Principal(A + "," + B + "," + C); - X500Principal dabc = new X500Principal(D + "," + A + "," + B + "," + C); - X500Principal abcd = new X500Principal(A + "," + B + "," + C + "," + D); - X500Principal adbc = new X500Principal(A + "," + D + "," + B + "," + C); - X500Principal dcab = new X500Principal(D + "," + C + "," + A + "," + B) ; - X500Principal def = new X500Principal(D + "," + E + "," + F) ; - - - FunctionArgumentAttributeValue attrABC = null; - FunctionArgumentAttributeValue attrDABC = null; - FunctionArgumentAttributeValue attrABCD = null; - FunctionArgumentAttributeValue attrADBC = null; - FunctionArgumentAttributeValue attrDCAB = null; - FunctionArgumentAttributeValue attrDEF = null; - - FunctionArgumentAttributeValue attrBad = null; - FunctionArgumentBag attrBag = new FunctionArgumentBag(new Bag()); - - - try { - attrABC = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(abc)); - attrDABC = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(dabc)); - attrABCD = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(abcd)); - attrADBC = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(adbc)); - attrDCAB = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(dcab)); - attrDEF = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(def)); - - attrBad = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionX500NameMatch fd = (FunctionDefinitionX500NameMatch) StdFunctions.FD_X500NAME_MATCH; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_X500NAME_MATCH, fd.getId()); - assertEquals(DataTypes.DT_X500NAME.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - - // test normal, first exact match for second - arguments.clear(); - arguments.add(attrABC); - arguments.add(attrABC); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // test first is end of second - arguments.clear(); - arguments.add(attrABC); - arguments.add(attrDABC); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // first exact match for sub-section but not end of second - arguments.clear(); - arguments.add(attrABC); - arguments.add(attrABCD); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // components of first match components in second but not contiguous - arguments.clear(); - arguments.add(attrABC); - arguments.add(attrADBC); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // components of first match components in second but not in order - arguments.clear(); - arguments.add(attrABC); - arguments.add(attrDCAB); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first does not match second at all - arguments.clear(); - arguments.add(attrABC); - arguments.add(attrDEF); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first arg larger than 2nd arg - arguments.clear(); - arguments.add(attrABCD); - arguments.add(attrABC); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // bad arg types - arguments.clear(); - arguments.add(attrABC); - arguments.add(attrBad); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:x500Name-match Expected data type 'x500Name' saw 'integer' at arg index 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many args - arguments.clear(); - arguments.add(attrABC); - arguments.add(attrABC); - arguments.add(attrABC); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:x500Name-match Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too few args - arguments.clear(); - arguments.add(attrABC); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:x500Name-match Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:x500Name-match Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // one arg is bag - arguments.clear(); - arguments.add(attrABC); - arguments.add(attrBag); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:x500Name-match Expected a simple value, saw a bag at arg index 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null arg - arguments.clear(); - arguments.add(null); - arguments.add(attrBag); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:x500Name-match Got null argument at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - @Test - public void testRfc822NameMatch() { - - - - - FunctionArgumentAttributeValue attrStringabcxyz = null; - FunctionArgumentAttributeValue attrStringABCxyz = null; - FunctionArgumentAttributeValue attrStringabcXYZ = null; - FunctionArgumentAttributeValue attrStringcx = null; - FunctionArgumentAttributeValue attrStringwholedomainpart = null; - FunctionArgumentAttributeValue attrStringWholeDomainPart = null; - FunctionArgumentAttributeValue attrStringWholeDomain = null; - FunctionArgumentAttributeValue attrStringdomainpart = null; - FunctionArgumentAttributeValue attrStringDomainPart = null; - FunctionArgumentAttributeValue attrStringdotWholeDomain = null; - FunctionArgumentAttributeValue attrStringdomain = null; - - FunctionArgumentAttributeValue attrStringNoMatch = null; - FunctionArgumentAttributeValue attrStringMultipleAt = null; - FunctionArgumentAttributeValue attrStringMissingLocal = null; - FunctionArgumentAttributeValue attrStringMissingDomain = null; - - - FunctionArgumentAttributeValue attrRfcabcxyz = null; - FunctionArgumentAttributeValue attrRfcwholedomainpart = null; - FunctionArgumentAttributeValue attrRfcWholeDomainPart = null; - - FunctionArgumentBag attrBag = new FunctionArgumentBag(new Bag()); - - try { - attrStringabcxyz = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc@xyz")); - attrStringABCxyz = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("ABC@xyz")); - attrStringabcXYZ = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc@XYZ")); - attrStringcx = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("c@x")); - attrStringwholedomainpart = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("whole.domain.part")); - attrStringWholeDomainPart = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("Whole.Domain.Part")); - attrStringWholeDomain = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("Whole.Domain")); - attrStringdomainpart = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(".domain.part")); - attrStringDomainPart = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(".Domain.Part")); - attrStringdotWholeDomain = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(".Whole.Domain")); - attrStringdomain = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(".domain.")); - - attrStringNoMatch = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("no match to any legal name")); - attrStringMultipleAt = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("name@with@multipleAts")); - attrStringMissingLocal = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("@multipleAts")); - attrStringMissingDomain = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("localpart@")); - - attrRfcabcxyz = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue("abc@xyz")); - attrRfcwholedomainpart = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue("abc@whole.domain.part")); - attrRfcWholeDomainPart = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue("abc@Whole.Domain.Part")); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionRFC822NameMatch fd = (FunctionDefinitionRFC822NameMatch) StdFunctions.FD_RFC822NAME_MATCH; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_RFC822NAME_MATCH, fd.getId()); - assertEquals(DataTypes.DT_RFC822NAME.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // string identical to name - exact match on whole search term - arguments.clear(); - arguments.add(attrStringabcxyz); - arguments.add(attrRfcabcxyz); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.getStatus().isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // no match local case different - arguments.clear(); - arguments.add(attrStringABCxyz); - arguments.add(attrRfcabcxyz); - res = fd.evaluate(null, arguments); - assertTrue(res.getStatus().isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // match domain case different - arguments.clear(); - arguments.add(attrStringabcXYZ); - arguments.add(attrRfcabcxyz); - res = fd.evaluate(null, arguments); - assertTrue(res.getStatus().isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - - // partial local + partial domain - arguments.clear(); - arguments.add(attrStringcx); - arguments.add(attrRfcabcxyz); - res = fd.evaluate(null, arguments); - assertTrue(res.getStatus().isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // whole domain - arguments.clear(); - arguments.add(attrStringwholedomainpart); - arguments.add(attrRfcwholedomainpart); - res = fd.evaluate(null, arguments); - assertTrue(res.getStatus().isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // whole domain different case - arguments.clear(); - arguments.add(attrStringWholeDomainPart); - arguments.add(attrRfcwholedomainpart); - res = fd.evaluate(null, arguments); - assertTrue(res.getStatus().isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - arguments.clear(); - arguments.add(attrStringwholedomainpart); - arguments.add(attrRfcWholeDomainPart); - res = fd.evaluate(null, arguments); - assertTrue(res.getStatus().isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // whole domain fail - arguments.clear(); - arguments.add(attrStringWholeDomain); - arguments.add(attrRfcWholeDomainPart); - res = fd.evaluate(null, arguments); - assertTrue(res.getStatus().isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // partial domain match - arguments.clear(); - arguments.add(attrStringDomainPart); - arguments.add(attrRfcWholeDomainPart); - res = fd.evaluate(null, arguments); - assertTrue(res.getStatus().isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // partial domain different case - arguments.clear(); - arguments.add(attrStringdomainpart); - arguments.add(attrRfcWholeDomainPart); - res = fd.evaluate(null, arguments); - assertTrue(res.getStatus().isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // partial domain fail - arguments.clear(); - arguments.add(attrStringdotWholeDomain); - arguments.add(attrRfcWholeDomainPart); - res = fd.evaluate(null, arguments); - assertTrue(res.getStatus().isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - arguments.clear(); - arguments.add(attrStringdomain); - arguments.add(attrRfcWholeDomainPart); - res = fd.evaluate(null, arguments); - assertTrue(res.getStatus().isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // search term contains more than 1 @ - arguments.clear(); - arguments.add(attrStringMultipleAt); - arguments.add(attrRfcabcxyz); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:rfc822Name-match String contained more than 1 '@' in 'name@with@multipleAts'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // search term missing local part - arguments.clear(); - arguments.add(attrStringMissingLocal); - arguments.add(attrRfcabcxyz); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:rfc822Name-match String missing local part in '@multipleAts'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // search term missing domain part - arguments.clear(); - arguments.add(attrStringMissingDomain); - arguments.add(attrRfcabcxyz); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:rfc822Name-match String missing domain part in 'localpart@'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg types - arguments.clear(); - arguments.add(attrRfcabcxyz); - arguments.add(attrStringNoMatch); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:rfc822Name-match Expected data type 'string' saw 'rfc822Name' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many args - arguments.clear(); - arguments.add(attrStringNoMatch); - arguments.add(attrStringNoMatch); - arguments.add(attrStringNoMatch); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:rfc822Name-match Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too few args - arguments.clear(); - arguments.add(attrStringNoMatch); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:rfc822Name-match Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:rfc822Name-match Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // one arg is bag - arguments.clear(); - arguments.add(attrStringNoMatch); - arguments.add(attrBag); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:rfc822Name-match Expected a simple value, saw a bag at arg index 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null arg - arguments.clear(); - arguments.add(null); - arguments.add(attrStringNoMatch); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:rfc822Name-match Got null argument at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringConversionTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringConversionTest.java deleted file mode 100644 index deca2b15f..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringConversionTest.java +++ /dev/null @@ -1,2504 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.math.BigInteger; -import java.net.URI; -import java.net.URISyntaxException; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; - -import javax.security.auth.x500.X500Principal; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacml.std.datatypes.IPAddress; -import com.att.research.xacml.std.datatypes.IPv4Address; -import com.att.research.xacml.std.datatypes.IPv6Address; -import com.att.research.xacml.std.datatypes.ISO8601Date; -import com.att.research.xacml.std.datatypes.ISO8601DateTime; -import com.att.research.xacml.std.datatypes.ISO8601Time; -import com.att.research.xacml.std.datatypes.ISO8601TimeZone; -import com.att.research.xacml.std.datatypes.PortRange; -import com.att.research.xacml.std.datatypes.RFC2396DomainName; -import com.att.research.xacml.std.datatypes.RFC822Name; -import com.att.research.xacml.std.datatypes.XPathDayTimeDuration; -import com.att.research.xacml.std.datatypes.XPathYearMonthDuration; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Tests for converting objects to/from Strings. - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionStringConversionTest { - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - - /** - * Boolean - */ - @Test - public void testBoolean_from_string() { - FunctionArgumentAttributeValue attrString1 = null; - FunctionArgumentAttributeValue attrStringBadValue = null; - FunctionArgumentAttributeValue attrStringBadType = null; - try { - attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("true")); - attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_BOOLEAN_FROM_STRING; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_BOOLEAN_FROM_STRING, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrString1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(new Boolean(true), resValue); - - // bad value - arguments.clear(); - arguments.add(attrStringBadValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:boolean-from-string Cannot convert from \"java.lang.String\" with value \"not valid obj value\" to boolean", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:boolean-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - @Test - public void testString_from_boolean() { - FunctionArgumentAttributeValue attrObj1 = null; - FunctionArgumentAttributeValue attrStringBadType = null; - String objValueString = "false"; - try { - attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(objValueString)); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_BOOLEAN; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_FROM_BOOLEAN, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrObj1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(objValueString, res.getValue().getValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-from-boolean Expected data type 'boolean' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - - /** - * Integer - */ - @Test - public void testInteger_from_string() { - FunctionArgumentAttributeValue attrString1 = null; - FunctionArgumentAttributeValue attrStringBadValue = null; - FunctionArgumentAttributeValue attrStringBadType = null; - try { - attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123456")); - attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_INTEGER_FROM_STRING; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_INTEGER_FROM_STRING, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrString1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - BigInteger resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("123456"), resValue); - - // bad value - arguments.clear(); - arguments.add(attrStringBadValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:integer-from-string For input string: \"n\"", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:integer-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - @Test - public void testString_from_integer() { - FunctionArgumentAttributeValue attrObj1 = null; - FunctionArgumentAttributeValue attrStringBadType = null; - String objValueString = "1234"; - try { - attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(objValueString)); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_INTEGER; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_FROM_INTEGER, fd.getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrObj1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(objValueString, res.getValue().getValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-from-integer Expected data type 'integer' saw 'double' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - /** - * Double - */ - @Test - public void testDouble_from_string() { - FunctionArgumentAttributeValue attrString1 = null; - FunctionArgumentAttributeValue attrStringBadValue = null; - FunctionArgumentAttributeValue attrStringBadType = null; - try { - attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("5.432")); - attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_DOUBLE_FROM_STRING; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DOUBLE_FROM_STRING, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrString1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Double resValue = (Double)res.getValue().getValue(); - assertEquals(new Double(5.432), resValue); - - // bad value - arguments.clear(); - arguments.add(attrStringBadValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:double-from-string For input string: \"not valid obj value\"", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:double-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - @Test - public void testString_from_double() { - FunctionArgumentAttributeValue attrObj1 = null; - FunctionArgumentAttributeValue attrObjBig = null; - FunctionArgumentAttributeValue attrStringBadType = null; - String objValueString = "5.432"; - String objValueStringBig = "55555555555555555555.123455"; - try { - attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(objValueString)); - attrObjBig = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(objValueStringBig)); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_DOUBLE; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_FROM_DOUBLE, fd.getId()); - assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrObj1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(objValueString, res.getValue().getValue()); - - arguments.clear(); - arguments.add(attrObjBig); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals("5.555555555555556E19", res.getValue().getValue()); - - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-from-double Expected data type 'double' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - - - /** - * Time - */ - @Test - public void testTime_from_string() { - FunctionArgumentAttributeValue attrString1 = null; - FunctionArgumentAttributeValue attrString2 = null; - FunctionArgumentAttributeValue attrString3 = null; - FunctionArgumentAttributeValue attrString4 = null; - FunctionArgumentAttributeValue attrStringTimeZone = null; - FunctionArgumentAttributeValue attrStringBadValue = null; - FunctionArgumentAttributeValue attrStringBadType = null; - try { - attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("05:12:34.323")); - attrString2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("5:12:34.323")); - attrString3 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("05:12")); - attrString4 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("05:12:34")); - attrStringTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("05:12:34.323+03:00")); - attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_TIME_FROM_STRING; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_TIME_FROM_STRING, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrString1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - ISO8601Time resValue = (ISO8601Time)res.getValue().getValue(); - assertEquals(new ISO8601Time(5, 12, 34, 323), resValue); - - // check missing 0 in front - arguments.clear(); - arguments.add(attrString2); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:time-from-string Invalid hour of day", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // check missing seconds/msecs - arguments.clear(); - arguments.add(attrString3); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:time-from-string Time string too short", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // check missing just msecs - arguments.clear(); - arguments.add(attrString4); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (ISO8601Time)res.getValue().getValue(); - assertEquals(new ISO8601Time(5, 12, 34, 0), resValue); - - // check TimeZone - arguments.clear(); - arguments.add(attrStringTimeZone); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (ISO8601Time)res.getValue().getValue(); - assertEquals(new ISO8601Time(new ISO8601TimeZone(180), 5, 12, 34, 323), resValue); - - // bad value - arguments.clear(); - arguments.add(attrStringBadValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:time-from-string Invalid hour of day", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:time-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - @Test - public void testString_from_time() { - FunctionArgumentAttributeValue attrObj1 = null; - FunctionArgumentAttributeValue attrObj2 = null; - FunctionArgumentAttributeValue attrObjTimeZone = null; - FunctionArgumentAttributeValue attrStringBadType = null; - try { - attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue("05:12:34.323")); - attrObj2 = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue("05:01:02.323")); - attrObjTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue("05:12:34.323+03:00")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_TIME; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_FROM_TIME, fd.getId()); - assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrObj1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals("05:12:34.323", res.getValue().getValue()); - - // missing digits in string value? - arguments.clear(); - arguments.add(attrObj2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals("05:01:02.323", res.getValue().getValue()); - - // include TimeZone - arguments.clear(); - arguments.add(attrObjTimeZone); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals("05:12:34.323+03:00", res.getValue().getValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-from-time Expected data type 'time' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - - - /** - * Date - */ - @Test - public void testDate_from_string() { - FunctionArgumentAttributeValue attrString1 = null; - FunctionArgumentAttributeValue attrString2 = null; - FunctionArgumentAttributeValue attrString3 = null; - FunctionArgumentAttributeValue attrString4 = null; - FunctionArgumentAttributeValue attrString5 = null; - FunctionArgumentAttributeValue attrString6 = null; - FunctionArgumentAttributeValue attrString7 = null; - FunctionArgumentAttributeValue attrString8 = null; - FunctionArgumentAttributeValue attrString9 = null; - FunctionArgumentAttributeValue attrStringDateZone = null; - FunctionArgumentAttributeValue attrStringBadValue = null; - FunctionArgumentAttributeValue attrStringBadType = null; - try { - attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-12")); - attrString2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("-2013-05-12")); - attrString3 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("1232013-05-12")); - attrString4 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("-1232013-05-12")); - attrString5 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("213-05-12")); - attrString6 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-5-12")); - attrString7 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-2")); - attrString8 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-32-12")); - attrString9 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-45")); - attrStringDateZone = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-12+03:00")); - attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_DATE_FROM_STRING; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATE_FROM_STRING, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrString1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - ISO8601Date resValue = (ISO8601Date)res.getValue().getValue(); - assertEquals(new ISO8601Date(2013, 5, 12), resValue); - - // check negative - arguments.clear(); - arguments.add(attrString2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (ISO8601Date)res.getValue().getValue(); - assertEquals(new ISO8601Date(-2013, 5, 12), resValue); - - // check big - arguments.clear(); - arguments.add(attrString3); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (ISO8601Date)res.getValue().getValue(); - assertEquals(new ISO8601Date(1232013, 5, 12), resValue); - - // check big negative - arguments.clear(); - arguments.add(attrString4); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (ISO8601Date)res.getValue().getValue(); - assertEquals(new ISO8601Date(-1232013, 5, 12), resValue); - - // bad year - arguments.clear(); - arguments.add(attrString5); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-from-string Invalid year (must be at least 4 digits)", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad month - arguments.clear(); - arguments.add(attrString6); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-from-string Invalid month", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad day format - arguments.clear(); - arguments.add(attrString7); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-from-string Invalid day", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // month out of range - arguments.clear(); - arguments.add(attrString8); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-from-string Invalid month", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // day out of range - arguments.clear(); - arguments.add(attrString9); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-from-string Invalid day", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // check TimeZone - arguments.clear(); - arguments.add(attrStringDateZone); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (ISO8601Date)res.getValue().getValue(); - assertEquals(new ISO8601Date(new ISO8601TimeZone(180), 2013, 5, 12), resValue); - - // bad value - arguments.clear(); - arguments.add(attrStringBadValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-from-string Invalid year", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:date-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - @Test - public void testString_from_date() { - FunctionArgumentAttributeValue attrObj1 = null; - FunctionArgumentAttributeValue attrObj2 = null; - FunctionArgumentAttributeValue attrObjDateZone = null; - FunctionArgumentAttributeValue attrStringBadType = null; - try { - attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue("2013-05-12")); - attrObj2 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue("0001-01-01")); - attrObjDateZone = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue("2013-05-12+03:00")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_DATE; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_FROM_DATE, fd.getId()); - assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrObj1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals("2013-05-12", res.getValue().getValue()); - - // missing digits in string value? - arguments.clear(); - arguments.add(attrObj2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals("1-01-01", res.getValue().getValue()); - - // include DateZone - arguments.clear(); - arguments.add(attrObjDateZone); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals("2013-05-12+03:00", res.getValue().getValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-from-date Expected data type 'date' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - - - - /** - * DateTime - */ - @Test - public void testDateTime_from_string() { - FunctionArgumentAttributeValue attrString1 = null; - FunctionArgumentAttributeValue attrString2 = null; - FunctionArgumentAttributeValue attrString3 = null; - FunctionArgumentAttributeValue attrString4 = null; - FunctionArgumentAttributeValue attrString5 = null; - FunctionArgumentAttributeValue attrString6 = null; - FunctionArgumentAttributeValue attrString7 = null; - FunctionArgumentAttributeValue attrString8 = null; - FunctionArgumentAttributeValue attrString9 = null; - FunctionArgumentAttributeValue attrStringDateTimeZone = null; - FunctionArgumentAttributeValue attrStringBadValue = null; - FunctionArgumentAttributeValue attrStringBadType = null; - try { - attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-12T12:14:15.323")); - attrString2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("-2013-05-12T12:14:15.323")); - attrString3 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("1232013-05-12T12:14:15.323")); - attrString4 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("-1232013-05-12T12:14:15.323")); - attrString5 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("213-05-12T12:14:15.323")); - attrString6 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-5-12T12:14:15.323")); - attrString7 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-2T12:14:15.323")); - attrString8 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-32-12T12:14:15.323")); - attrString9 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-45T12:14:15.323")); - attrStringDateTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-12T12:14:15.323+03:00")); - attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_DATETIME_FROM_STRING; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DATETIME_FROM_STRING, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrString1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - ISO8601DateTime resValue = (ISO8601DateTime)res.getValue().getValue(); - assertEquals(new ISO8601DateTime(null, new ISO8601Date(2013, 5, 12), new ISO8601Time(12, 14, 15, 323)), resValue); - - // check negative - arguments.clear(); - arguments.add(attrString2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - assertEquals(new ISO8601DateTime(null, new ISO8601Date(-2013, 5, 12), new ISO8601Time(12, 14, 15, 323)), resValue); - - - // check big - arguments.clear(); - arguments.add(attrString3); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - assertEquals(new ISO8601DateTime(null, new ISO8601Date(1232013, 5, 12), new ISO8601Time(12, 14, 15, 323)), resValue); - - // check big negative - arguments.clear(); - arguments.add(attrString4); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - assertEquals(new ISO8601DateTime(null, new ISO8601Date(-1232013, 5, 12), new ISO8601Time(12, 14, 15, 323)), resValue); - - // bad year - arguments.clear(); - arguments.add(attrString5); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-from-string Invalid year (must be at least 4 digits)", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad month - arguments.clear(); - arguments.add(attrString6); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-from-string Invalid month", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad day format - arguments.clear(); - arguments.add(attrString7); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-from-string Invalid day", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // month out of range - arguments.clear(); - arguments.add(attrString8); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-from-string Invalid month", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // day out of range - arguments.clear(); - arguments.add(attrString9); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-from-string Invalid day", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // check TimeZone - arguments.clear(); - arguments.add(attrStringDateTimeZone); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (ISO8601DateTime)res.getValue().getValue(); - assertEquals(new ISO8601DateTime(new ISO8601TimeZone(180), new ISO8601Date(new ISO8601TimeZone(180), 2013, 5, 12), new ISO8601Time(new ISO8601TimeZone(180),12, 14, 15, 323)), resValue); - - // bad value - arguments.clear(); - arguments.add(attrStringBadValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-from-string Invalid year", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dateTime-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - @Test - public void testString_from_dateTime() { - FunctionArgumentAttributeValue attrObj1 = null; - FunctionArgumentAttributeValue attrObj2 = null; - FunctionArgumentAttributeValue attrObjDateTimeZone = null; - FunctionArgumentAttributeValue attrStringBadType = null; - try { - attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue("2013-05-12T12:14:15.323")); - attrObj2 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue("0001-01-01T12:14:15.323")); - attrObjDateTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue("2013-05-12T12:14:15.323+03:00")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_DATETIME; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_FROM_DATETIME, fd.getId()); - assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrObj1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals("2013-05-12T12:14:15.323", res.getValue().getValue()); - - // missing digits in string value? - arguments.clear(); - arguments.add(attrObj2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals("1-01-01T12:14:15.323", res.getValue().getValue()); - - // include DateTimeZone - arguments.clear(); - arguments.add(attrObjDateTimeZone); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals("2013-05-12T12:14:15.323+03:00", res.getValue().getValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-from-dateTime Expected data type 'dateTime' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - - - /** - * URI - */ - @Test - public void testURI_from_string() { - FunctionArgumentAttributeValue attrString1 = null; - FunctionArgumentAttributeValue attrStringBadValue = null; - FunctionArgumentAttributeValue attrStringBadType = null; - try { - attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("http://someMachine.com/subdir")); - attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_ANYURI_FROM_STRING; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_ANYURI_FROM_STRING, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_ANYURI.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrString1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - URI resValue = (URI)res.getValue().getValue(); - try { - assertEquals(new URI("http://someMachine.com/subdir"), resValue); - } catch (URISyntaxException e) { - fail("uri generation e="+e); - } - - // bad value - arguments.clear(); - arguments.add(attrStringBadValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-from-string Illegal character in path at index 3: not valid obj value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - @Test - public void testString_from_anyURI() { - FunctionArgumentAttributeValue attrObj1 = null; - FunctionArgumentAttributeValue attrStringBadType = null; - String objValueString = "http://aMachine.com:8080/aRef"; - try { - attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(objValueString)); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_ANYURI; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_FROM_ANYURI, fd.getId()); - assertEquals(DataTypes.DT_ANYURI.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrObj1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(objValueString, res.getValue().getValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-from-anyURI Expected data type 'anyURI' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - /** - * XPathDayTimeDuration - */ - @Test - public void testXPathDayTimeDuration_from_string() { - FunctionArgumentAttributeValue attrString1 = null; - FunctionArgumentAttributeValue attrStringNeg1 = null; - FunctionArgumentAttributeValue attrStringNeg2 = null; - FunctionArgumentAttributeValue attrStringNoDay = null; - FunctionArgumentAttributeValue attrStringNoHour = null; - FunctionArgumentAttributeValue attrStringNoMin = null; - FunctionArgumentAttributeValue attrStringNoSec = null; - FunctionArgumentAttributeValue attrStringNoP = null; - FunctionArgumentAttributeValue attrStringSecondsDot = null; - FunctionArgumentAttributeValue attrStringMissingTOk = null; - FunctionArgumentAttributeValue attrStringMissingTBad = null; - FunctionArgumentAttributeValue attrStringBadValue = null; - FunctionArgumentAttributeValue attrStringBadType = null; - try { - attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3DT10H30M23S")); - attrStringNeg1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("-P3DT10H30M23S")); - attrStringNeg2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P-3DT10H30M23S")); - attrStringNoDay = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("PT10H30M23S")); - attrStringNoHour = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3DT30M23S")); - attrStringNoMin = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3DT10H23S")); - attrStringNoSec = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3DT10H30M")); - attrStringNoP = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("3DT10H30M")); - attrStringSecondsDot = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3DT10H30M23.456S")); - attrStringMissingTOk = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3D")); - attrStringMissingTBad = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3D10H30M23S")); - - attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_DAYTIMEDURATION_FROM_STRING; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DAYTIMEDURATION_FROM_STRING, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_DAYTIMEDURATION.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrString1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - XPathDayTimeDuration resValue = (XPathDayTimeDuration)res.getValue().getValue(); - assertEquals(new XPathDayTimeDuration(1, 3, 10, 30, 23), resValue); - - - // negative values in front is allowed - arguments.clear(); - arguments.add(attrStringNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (XPathDayTimeDuration)res.getValue().getValue(); - assertEquals(new XPathDayTimeDuration(-1, 3, 10, 30, 23), resValue); - - // negative in middle of string not ok - arguments.clear(); - arguments.add(attrStringNeg2); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dayTimeDuration-from-string Invalid chunk \"P-3DT10H30M23S\" at position 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // omit parts that are 0 - arguments.clear(); - arguments.add(attrStringNoDay); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (XPathDayTimeDuration)res.getValue().getValue(); - assertEquals(new XPathDayTimeDuration(1, 0, 10, 30, 23), resValue); - - arguments.clear(); - arguments.add(attrStringNoHour); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (XPathDayTimeDuration)res.getValue().getValue(); - assertEquals(new XPathDayTimeDuration(1, 3, 0, 30, 23), resValue); - - arguments.clear(); - arguments.add(attrStringNoMin); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (XPathDayTimeDuration)res.getValue().getValue(); - assertEquals(new XPathDayTimeDuration(1, 3, 10, 0, 23), resValue); - - arguments.clear(); - arguments.add(attrStringNoSec); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (XPathDayTimeDuration)res.getValue().getValue(); - assertEquals(new XPathDayTimeDuration(1, 3, 10, 30, 0), resValue); - - // P must always be present - arguments.clear(); - arguments.add(attrStringNoP); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dayTimeDuration-from-string Invalid ISO8601 duration string \"3DT10H30M\" at position 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // seconds may contain decimal - arguments.clear(); - arguments.add(attrStringSecondsDot); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (XPathDayTimeDuration)res.getValue().getValue(); - assertEquals(new XPathDayTimeDuration(1, 3, 10, 30, 23.456), resValue); - - // T must be absent iff all time items are absent - arguments.clear(); - arguments.add(attrStringMissingTOk); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (XPathDayTimeDuration)res.getValue().getValue(); - assertEquals(new XPathDayTimeDuration(1, 3, 0, 0, 0), resValue); - - // negative in middle of string not ok - arguments.clear(); - arguments.add(attrStringMissingTBad); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dayTimeDuration-from-string Invalid ISO8601 duration string \"P3D10H30M23S\" at position 6: out of order component", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // bad value - arguments.clear(); - arguments.add(attrStringBadValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dayTimeDuration-from-string Invalid ISO8601 duration string \"not valid obj value\" at position 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dayTimeDuration-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - @Test - public void testString_from_dayTimeDuration() { - FunctionArgumentAttributeValue attrObj1 = null; - FunctionArgumentAttributeValue attrStringBadType = null; - String objValueString = "P3DT10H30M23S"; - try { - attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(objValueString)); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_DAYTIMEDURATION; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_FROM_DAYTIMEDURATION, fd.getId()); - assertEquals(DataTypes.DT_DAYTIMEDURATION.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrObj1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(objValueString, res.getValue().getValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-from-dayTimeDuration Expected data type 'dayTimeDuration' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - - - - - - - /** - * XPathYearMonthDuration - */ - @Test - public void testXPathYearMonthDuration_from_string() { - FunctionArgumentAttributeValue attrString1 = null; - FunctionArgumentAttributeValue attrStringNeg1 = null; - FunctionArgumentAttributeValue attrStringNeg2 = null; - FunctionArgumentAttributeValue attrStringNoYear1 = null; - FunctionArgumentAttributeValue attrStringNoYear2 = null; - FunctionArgumentAttributeValue attrStringNoMonth1 = null; - FunctionArgumentAttributeValue attrStringNoMonth2 = null; - FunctionArgumentAttributeValue attrStringNoValue = null; - FunctionArgumentAttributeValue attrStringNoP = null; - FunctionArgumentAttributeValue attrStringBigMonths = null; - FunctionArgumentAttributeValue attrStringMissingTOk = null; - FunctionArgumentAttributeValue attrStringMissingTBad = null; - FunctionArgumentAttributeValue attrStringZeroMonths = null; - FunctionArgumentAttributeValue attrStringBadValue = null; - FunctionArgumentAttributeValue attrStringBadType = null; - try { - attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P1Y2M")); - attrStringNeg1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("-P1Y2M")); - attrStringNeg2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P-1Y2M")); - attrStringNoYear1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P2M")); - attrStringNoYear2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("PY2M")); - attrStringNoMonth1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P1Y")); - attrStringNoMonth2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P1YM")); - attrStringNoValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P")); - attrStringNoP = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("1Y2M")); - attrStringBigMonths = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P1Y12M")); - attrStringMissingTOk = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3D")); - attrStringMissingTBad = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3D10H30M23S")); - attrStringZeroMonths = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P0M")); - - attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_YEARMONTHDURATION_FROM_STRING; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_YEARMONTHDURATION_FROM_STRING, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_YEARMONTHDURATION.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrString1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - XPathYearMonthDuration resValue = (XPathYearMonthDuration)res.getValue().getValue(); - assertEquals(new XPathYearMonthDuration(1,1, 2), resValue); - - - // negative values in front is allowed - arguments.clear(); - arguments.add(attrStringNeg1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (XPathYearMonthDuration)res.getValue().getValue(); - assertEquals(new XPathYearMonthDuration(-1, 1, 2), resValue); - - // negative in middle of string not ok - arguments.clear(); - arguments.add(attrStringNeg2); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:yearMonthDuration-from-string Invalid chunk \"P-1Y2M\" at position 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // omit parts that are 0 - arguments.clear(); - arguments.add(attrStringNoYear1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (XPathYearMonthDuration)res.getValue().getValue(); - assertEquals(new XPathYearMonthDuration(1, 0, 2), resValue); - - arguments.clear(); - arguments.add(attrStringNoYear2); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:yearMonthDuration-from-string Invalid chunk \"PY2M\" at position 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - arguments.clear(); - arguments.add(attrStringNoMonth1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (XPathYearMonthDuration)res.getValue().getValue(); - assertEquals(new XPathYearMonthDuration(1, 1, 0), resValue); - - arguments.clear(); - arguments.add(attrStringNoMonth2); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:yearMonthDuration-from-string Invalid chunk \"P1YM\" at position 3", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // No field with a value - arguments.clear(); - arguments.add(attrStringNoValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:yearMonthDuration-from-string Invalid ISO8601 duration string \"P\": No duration components following P", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // P must always be present - arguments.clear(); - arguments.add(attrStringNoP); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:yearMonthDuration-from-string Invalid ISO8601 duration string \"1Y2M\" at position 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // Canonical Form of output may not have more than 12 months, but input as string is ok? - arguments.clear(); - arguments.add(attrStringBigMonths); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (XPathYearMonthDuration)res.getValue().getValue(); - assertEquals(new XPathYearMonthDuration(1, 1, 12), resValue); - - // Canonical representation of 0 Months - arguments.clear(); - arguments.add(attrStringZeroMonths); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (XPathYearMonthDuration)res.getValue().getValue(); - assertEquals(new XPathYearMonthDuration(1, 0, 0), resValue); - - // T must be absent iff all time items are absent - arguments.clear(); - arguments.add(attrStringMissingTOk); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:yearMonthDuration-from-string Invalid XPath yearMonthDuraiton \"{durationSign=1years=0months=0days=3hours=0minutes=0seconds=0millis=0}\": includes days, hours, minutes, or seconds", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // negative in middle of string not ok - arguments.clear(); - arguments.add(attrStringMissingTBad); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:yearMonthDuration-from-string Invalid ISO8601 duration string \"P3D10H30M23S\" at position 6: out of order component", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // bad value - arguments.clear(); - arguments.add(attrStringBadValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:yearMonthDuration-from-string Invalid ISO8601 duration string \"not valid obj value\" at position 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:yearMonthDuration-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - @Test - public void testString_from_yearMonthDuration() { - FunctionArgumentAttributeValue attrObj1 = null; - FunctionArgumentAttributeValue attrStringBadType = null; - String objValueString = "P1Y2M"; - try { - attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(objValueString)); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_YEARMONTHDURATION; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_FROM_YEARMONTHDURATION, fd.getId()); - assertEquals(DataTypes.DT_YEARMONTHDURATION.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrObj1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(objValueString, res.getValue().getValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-from-yearMonthDuration Expected data type 'yearMonthDuration' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - - - - /** - * X500Principal - * - * See http://www.ietf.org/rfc/rfc2253.txt and http://www.ietf.org/rfc/rfc2251.txt - */ - @Test - public void testX500Principal_from_string() { - FunctionArgumentAttributeValue attrString1 = null; - FunctionArgumentAttributeValue attrStringNoComma = null; - FunctionArgumentAttributeValue attrStringEmpty = null; - FunctionArgumentAttributeValue attrStringNoValue = null; - FunctionArgumentAttributeValue attrStringOrder = null; - FunctionArgumentAttributeValue attrStringDottedDecimalOID = null; - FunctionArgumentAttributeValue attrStringBadValue = null; - FunctionArgumentAttributeValue attrStringBadType = null; - try { - attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("CN=Name, L=local, ST=NJ, O=ATT, C=USA")); - attrStringNoComma = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("CN=Name, L=local ST=NJ, O=ATT, C=USA")); - attrStringEmpty = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); - attrStringNoValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("CN=Name, L=, ST=NJ, O=ATT, C=USA")); - attrStringOrder = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("L=local, ST=NJ, O=ATT, CN=Name, C=USA")); - attrStringDottedDecimalOID = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2.5.4.3=A. N. Other")); - - attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_X500NAME_FROM_STRING; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_X500NAME_FROM_STRING, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_X500NAME.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrString1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - X500Principal resValue = (X500Principal)res.getValue().getValue(); - assertEquals(new X500Principal("CN=Name, L=local, ST=NJ, O=ATT, C=USA"), resValue); - - // no comma between components => next attribute/value is included as part of first value - arguments.clear(); - arguments.add(attrStringNoComma); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (X500Principal)res.getValue().getValue(); - assertEquals(new X500Principal("CN=Name, L=local ST=NJ, O=ATT, C=USA"), resValue); - - // nothing in name (fail) - arguments.clear(); - arguments.add(attrStringEmpty); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (X500Principal)res.getValue().getValue(); - assertEquals(new X500Principal(""), resValue); - - // type value with no = - arguments.clear(); - arguments.add(attrStringNoValue); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (X500Principal)res.getValue().getValue(); - assertEquals(new X500Principal("CN=Name, L=, ST=NJ, O=ATT, C=USA"), resValue); - - // different order - arguments.clear(); - arguments.add(attrStringOrder); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (X500Principal)res.getValue().getValue(); - assertNotEquals(new X500Principal("CN=Name, L=local, ST=NJ, O=ATT, C=USA"), resValue); - - // dotted-decimal name with numbers - arguments.clear(); - arguments.add(attrStringDottedDecimalOID); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (X500Principal)res.getValue().getValue(); - assertEquals(new X500Principal("2.5.4.3=A. N. Other"), resValue); - - - - // bad value - arguments.clear(); - arguments.add(attrStringBadValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:x500Name-from-string improperly specified input name: not valid obj value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:x500Name-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - @Test - public void testString_from_x500Name() { - FunctionArgumentAttributeValue attrObj1 = null; - FunctionArgumentAttributeValue attrStringBadType = null; - String objValueString = "CN=Name, L=local, ST=NJ, O=ATT, C=USA"; - try { - attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(objValueString)); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_X500NAME; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_FROM_X500NAME, fd.getId()); - assertEquals(DataTypes.DT_X500NAME.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrObj1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(objValueString, res.getValue().getValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-from-x500Name Expected data type 'x500Name' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - - /** - * RFC822Name - */ - @Test - public void testRFC822Name_from_string() { - FunctionArgumentAttributeValue attrString1 = null; - FunctionArgumentAttributeValue attrStringCapsDomain = null; - FunctionArgumentAttributeValue attrStringCapsLocal = null; - FunctionArgumentAttributeValue attrStringMissingAt = null; - FunctionArgumentAttributeValue attrStringMissingLocal = null; - FunctionArgumentAttributeValue attrStringMissingDomain = null; - FunctionArgumentAttributeValue attrStringEmpty = null; - FunctionArgumentAttributeValue attrStringBadValue = null; - FunctionArgumentAttributeValue attrStringBadType = null; - try { - attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("local@Domain")); - attrStringCapsDomain = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("local@DOMAIN")); - attrStringCapsLocal = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("LOCAL@Domain")); - attrStringMissingAt = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("localDomain")); - attrStringMissingLocal = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("@Domain")); - attrStringMissingDomain = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("local@")); - attrStringEmpty = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); - - attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_RFC822NAME_FROM_STRING; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_RFC822NAME_FROM_STRING, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_RFC822NAME.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrString1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - RFC822Name resValue = (RFC822Name)res.getValue().getValue(); - assertEquals(new RFC822Name("local", "domain"), resValue); - - // caps domain - arguments.clear(); - arguments.add(attrStringCapsDomain); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (RFC822Name)res.getValue().getValue(); - assertEquals(new RFC822Name("local", "domain"), resValue); - - // caps local - arguments.clear(); - arguments.add(attrStringCapsLocal); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (RFC822Name)res.getValue().getValue(); - assertNotEquals(new RFC822Name("local", "domain"), resValue); - - // missing at - arguments.clear(); - arguments.add(attrStringMissingAt); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:rfc822Name-from-string Invalid RFC822Name \"localDomain\": missing local part", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // missing local - arguments.clear(); - arguments.add(attrStringMissingLocal); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:rfc822Name-from-string Invalid RFC822Name \"@Domain\": empty parts", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // missing domain - arguments.clear(); - arguments.add(attrStringMissingDomain); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:rfc822Name-from-string Invalid RFC822Name \"local@\": empty parts", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // empty - arguments.clear(); - arguments.add(attrStringEmpty); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:rfc822Name-from-string Invalid RFC822Name \"\": missing local part", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // bad value - arguments.clear(); - arguments.add(attrStringBadValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:rfc822Name-from-string Invalid RFC822Name \"not valid obj value\": missing local part", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:rfc822Name-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - @Test - public void testString_from_rfc822Name() { - FunctionArgumentAttributeValue attrObj1 = null; - FunctionArgumentAttributeValue attrStringBadType = null; - String objValueString = "local@DOMAIN"; - try { - attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(objValueString)); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_RFC822NAME; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_FROM_RFC822NAME, fd.getId()); - assertEquals(DataTypes.DT_RFC822NAME.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrObj1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals("local@domain", res.getValue().getValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-from-rfc822Name Expected data type 'rfc822Name' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - - /** - * IPAddress - */ - @Test - public void testIPAddress_from_string() { - FunctionArgumentAttributeValue attrString1 = null; - FunctionArgumentAttributeValue attrStringFull = null; - FunctionArgumentAttributeValue attrStringMissingElement = null; - FunctionArgumentAttributeValue attrStringTooManyElement = null; - FunctionArgumentAttributeValue attrStringIllegalElement = null; - FunctionArgumentAttributeValue attrStringOutOfOrder = null; - - FunctionArgumentAttributeValue attrStringMask = null; - FunctionArgumentAttributeValue attrStringMissingMaskElement = null; - FunctionArgumentAttributeValue attrStringTooManyMaskElement = null; - FunctionArgumentAttributeValue attrStringIllegalMaskElement = null; - FunctionArgumentAttributeValue attrStringMaskNoValue = null; - - FunctionArgumentAttributeValue attrStringMinusPort = null; - FunctionArgumentAttributeValue attrStringPortMinus = null; - FunctionArgumentAttributeValue attrStringPortPort = null; - FunctionArgumentAttributeValue attrStringNoPort = null; - FunctionArgumentAttributeValue attrStringBadPort = null; - FunctionArgumentAttributeValue attrStringTooManyPorts = null; - FunctionArgumentAttributeValue attrStringBadValue = null; - FunctionArgumentAttributeValue attrStringBadType = null; - - // set up for v4 address tests - this setup and the tests are repeated for V6 - short[] addrShorts= {123, 134, 156, 255 }; - short[] addrMaskShorts= {255, 255, 255, 255 }; - try { - attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255")); - attrStringFull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255/255.255.255.255:123-456")); - attrStringMissingElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.255")); - attrStringTooManyElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.255.111.222")); - attrStringIllegalElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.256.255")); - attrStringOutOfOrder = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.256.255:123-456/255.255.255.255")); - - attrStringMask = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255/255.255.255.255")); - attrStringMissingMaskElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255/123.134.255")); - attrStringTooManyMaskElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255/122.134.155.111.222")); - attrStringIllegalMaskElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255/123.134.256.255")); - attrStringMaskNoValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255/")); - // optional mask - // "/" with no mask (fail) - - attrStringMinusPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255:-123")); - attrStringPortMinus = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255:123-")); - attrStringPortPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255:1234567-432")); - attrStringNoPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255:")); - attrStringBadPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255:12.34")); - attrStringTooManyPorts = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255:-123-456")); - - - - attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_IPADDRESS_FROM_STRING; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_IPADDRESS_FROM_STRING, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_IPADDRESS.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrString1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - IPAddress resValue = (IPAddress)res.getValue().getValue(); - assertEquals(new IPv4Address(addrShorts, null, null), resValue); - - // fully-loaded address - arguments.clear(); - arguments.add(attrStringFull); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (IPAddress)res.getValue().getValue(); - try { - assertEquals(new IPv4Address(addrShorts, addrMaskShorts, PortRange.newInstance("123-456")), resValue); - } catch (Exception e) { - fail("port error e="+e); - } - - // missing element - arguments.clear(); - arguments.add(attrStringMissingElement); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"123.134.255\": invalid address", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many elements - arguments.clear(); - arguments.add(attrStringTooManyElement); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"123.134.255.111.222\": invalid address", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // illegal element - arguments.clear(); - arguments.add(attrStringIllegalElement); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"123.134.256.255\": invalid octet: \"256", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // Out of order - arguments.clear(); - arguments.add(attrStringOutOfOrder); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"123.134.256.255:123-456/255.255.255.255\": out of order components", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // simple mask - arguments.clear(); - arguments.add(attrStringMask); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (IPAddress)res.getValue().getValue(); - try { - assertEquals(new IPv4Address(addrShorts, addrMaskShorts, null), resValue); - } catch (Exception e) { - fail("port error e="+e); - } - - // missing mask element - arguments.clear(); - arguments.add(attrStringMissingMaskElement); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"123.134.255\": invalid address", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many mask elements - arguments.clear(); - arguments.add(attrStringTooManyMaskElement); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"122.134.155.111.222\": invalid address", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // illegal Mask element - arguments.clear(); - arguments.add(attrStringIllegalMaskElement); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"123.134.256.255\": invalid octet: \"256", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - //mask indicator without value - arguments.clear(); - arguments.add(attrStringMaskNoValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"\": invalid address", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // portrange (-port, port-, port-port) - arguments.clear(); - arguments.add(attrStringMinusPort); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (IPAddress)res.getValue().getValue(); - try { - assertEquals(new IPv4Address(addrShorts, null, PortRange.newInstance("-123")), resValue); - } catch (ParseException e) { - fail("port error e="+e); - } - - arguments.clear(); - arguments.add(attrStringPortMinus); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (IPAddress)res.getValue().getValue(); - try { - assertEquals(new IPv4Address(addrShorts, null, PortRange.newInstance("123-")), resValue); - } catch (ParseException e) { - fail("port error e="+e); - } - - arguments.clear(); - arguments.add(attrStringPortPort); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (IPAddress)res.getValue().getValue(); - try { - assertEquals(new IPv4Address(addrShorts, null, PortRange.newInstance("1234567-432")), resValue); - } catch (ParseException e) { - fail("port error e="+e); - } - - // ":" without port - arguments.clear(); - arguments.add(attrStringNoPort); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"123.134.156.255:\": no portrange given after ':'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // bad port number - arguments.clear(); - arguments.add(attrStringBadPort); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid PortRange \"12.34\": invalid port number", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad port range - arguments.clear(); - arguments.add(attrStringTooManyPorts); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid PortRange \"-123-456\": too many ranges", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // bad value - arguments.clear(); - arguments.add(attrStringBadValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Unknown IPAddress type for \"not valid obj value\"", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // - // V6 IP Addresses - // - - // reset the variable for IPv6 tests - FunctionArgumentAttributeValue attrStringAlternateFull = null; - FunctionArgumentAttributeValue attrStringEmptyElement = null; - FunctionArgumentAttributeValue attrString2xEmptyElement = null; - FunctionArgumentAttributeValue attrStringNoStartBracket = null; - FunctionArgumentAttributeValue attrStringNoEndBracket = null; - short[] addrv6Shorts = {(short)0x2001, (short)0xdb8, (short)0x85a3, (short)0x0, (short)0x0, (short)0x8a2e, (short)0x370, (short)0x1}; - Short prefix = new Short((short) 121); - try { - attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]")); - attrStringFull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1/121]:123-456")); - attrStringAlternateFull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]/121:123-456")); - attrStringEmptyElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3::8a2e:370:1]")); - attrString2xEmptyElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3::8a2e::1]")); - attrStringNoStartBracket = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2002:db8:85a3::8a2e::1]")); - attrStringNoEndBracket = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3::8a2e::1")); - - attrStringMissingElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:1]")); - attrStringTooManyElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1:123]")); - attrStringIllegalElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:mnop:85a3:0:0:8a2e:370:1]")); - attrStringOutOfOrder = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:mnop:85a3:0:0:8a2e:370:1:123-456/121]")); - - attrStringMask = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1/21]")); - attrStringIllegalMaskElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1/130]")); - attrStringMaskNoValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1/]")); - - attrStringMinusPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]:-123")); - attrStringPortMinus = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]:123-")); - attrStringPortPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]:1234567-432")); - attrStringNoPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]:")); - attrStringBadPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]:12.34")); - attrStringTooManyPorts = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]:-123-456")); - - attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - - // test normal - arguments.clear(); - arguments.add(attrString1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (IPAddress)res.getValue().getValue(); - assertEquals(new IPv6Address(addrv6Shorts, null, null), resValue); - - // fully-loaded address - "prefix" is inside the brackets (not clear if this is correct) - arguments.clear(); - arguments.add(attrStringFull); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (IPAddress)res.getValue().getValue(); - try { - assertEquals(new IPv6Address(addrv6Shorts, new Short(prefix), PortRange.newInstance("123-456")), resValue); - } catch (Exception e) { - fail("port error e="+e); - } - - // Alternate way of identifying "prefix" - outside the brackets - arguments.clear(); - arguments.add(attrStringAlternateFull); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (IPAddress)res.getValue().getValue(); - try { - assertEquals(new IPv6Address(addrv6Shorts, prefix, PortRange.newInstance("123-456")), resValue); - } catch (Exception e) { - fail("port error e="+e); - } - - - // consecutive zero elements removed - arguments.clear(); - arguments.add(attrStringEmptyElement); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (IPAddress)res.getValue().getValue(); - try { - assertEquals(new IPv6Address(addrv6Shorts, prefix, null), resValue); - } catch (Exception e) { - fail("port error e="+e); - } - - // consecutive zero elements removed in two locations (no-no) - arguments.clear(); - arguments.add(attrString2xEmptyElement); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv6Address string \"2001:db8:85a3::8a2e::1\": multiple zero runs", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // address must have [] on it - arguments.clear(); - arguments.add(attrStringNoStartBracket); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv6Address string \"2002:db8:85a3::8a2e::1]\": missing opening bracket", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrStringNoEndBracket); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv6Address string \"[2001:db8:85a3::8a2e::1\": missing closing bracket", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // missing element - arguments.clear(); - arguments.add(attrStringMissingElement); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv6Address string \"2001:db8:85a3:0:0:8a2e:1\": not enough address fields", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many elements - arguments.clear(); - arguments.add(attrStringTooManyElement); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv6Address string \"2001:db8:85a3:0:0:8a2e:370:1:123\"", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // illegal element - arguments.clear(); - arguments.add(attrStringIllegalElement); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv6Address component \"mnop\": invalid hex", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // Out of order - arguments.clear(); - arguments.add(attrStringOutOfOrder); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv6Address string \"2001:mnop:85a3:0:0:8a2e:370:1:123-456\"", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // simple mask - arguments.clear(); - arguments.add(attrStringMask); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (IPAddress)res.getValue().getValue(); - try { - assertEquals(new IPv6Address(addrv6Shorts, prefix, null), resValue); - } catch (Exception e) { - fail("port error e="+e); - } - - // illegal Mask element - arguments.clear(); - arguments.add(attrStringIllegalMaskElement); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid Ipv6Address string \"[2001:db8:85a3:0:0:8a2e:370:1/130]\": prefix is larger than 128", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - //mask indicator without value - arguments.clear(); - arguments.add(attrStringMaskNoValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid Ipv6Address string \"[2001:db8:85a3:0:0:8a2e:370:1/]\": prefix designation without value", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // portrange (-port, port-, port-port) - arguments.clear(); - arguments.add(attrStringMinusPort); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (IPAddress)res.getValue().getValue(); - try { - assertEquals(new IPv6Address(addrv6Shorts, null, PortRange.newInstance("-123")), resValue); - } catch (ParseException e) { - fail("port error e="+e); - } - - arguments.clear(); - arguments.add(attrStringPortMinus); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (IPAddress)res.getValue().getValue(); - try { - assertEquals(new IPv6Address(addrv6Shorts, null, PortRange.newInstance("123-")), resValue); - } catch (ParseException e) { - fail("port error e="+e); - } - - arguments.clear(); - arguments.add(attrStringPortPort); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (IPAddress)res.getValue().getValue(); - try { - assertEquals(new IPv6Address(addrv6Shorts, null, PortRange.newInstance("1234567-432")), resValue); - } catch (ParseException e) { - fail("port error e="+e); - } - - // ":" without port - arguments.clear(); - arguments.add(attrStringNoPort); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid IPv6 address string \"[2001:db8:85a3:0:0:8a2e:370:1]:\": no portrange given after ':'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // bad port number - arguments.clear(); - arguments.add(attrStringBadPort); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid PortRange \"12.34\": invalid port number", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad port range - arguments.clear(); - arguments.add(attrStringTooManyPorts); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:ipAddress-from-string Invalid PortRange \"-123-456\": too many ranges", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - - - - } - - @Test - public void testString_from_ipAddress() { - FunctionArgumentAttributeValue attrObj1 = null; - FunctionArgumentAttributeValue attrObjV6 = null; - FunctionArgumentAttributeValue attrStringBadType = null; - String objValueString = "123.145.255.255"; - String objValueStringV6 = "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]"; - try { - attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_IPADDRESS.createAttributeValue(objValueString)); - attrObjV6 = new FunctionArgumentAttributeValue(DataTypes.DT_IPADDRESS.createAttributeValue(objValueStringV6)); - - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_IPADDRESS; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_FROM_IPADDRESS, fd.getId()); - assertEquals(DataTypes.DT_IPADDRESS.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal V4 - arguments.clear(); - arguments.add(attrObj1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(objValueString, res.getValue().getValue()); - - // test normal V6 - arguments.clear(); - arguments.add(attrObjV6); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(objValueStringV6.toLowerCase(), res.getValue().getValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-from-ipAddress Expected data type 'ipAddress' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - - - - - - - - /** - * RFC2396DomainName - */ - @Test - public void testRFC2396DomainName_from_string() { - FunctionArgumentAttributeValue attrString1 = null; - FunctionArgumentAttributeValue attrString2 = null; - FunctionArgumentAttributeValue attrStringMinusPort = null; - FunctionArgumentAttributeValue attrStringPortMinus = null; - FunctionArgumentAttributeValue attrStringPortPort = null; - FunctionArgumentAttributeValue attrStringNoPort = null; - FunctionArgumentAttributeValue attrStringBadPort = null; - FunctionArgumentAttributeValue attrStringTooManyPorts = null; - - FunctionArgumentAttributeValue attrStringBadValue = null; - FunctionArgumentAttributeValue attrStringBadType = null; - try { - attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host")); - attrString2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host.host")); - - attrStringMinusPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host.host:-123")); - attrStringPortMinus = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host.host:123-")); - attrStringPortPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host.host:1234567-432")); - attrStringNoPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host.host:")); - attrStringBadPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host.host:12.34")); - attrStringTooManyPorts = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host.host:-123-456")); - - attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_DNSNAME_FROM_STRING; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_DNSNAME_FROM_STRING, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_DNSNAME.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrString1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - RFC2396DomainName resValue = (RFC2396DomainName)res.getValue().getValue(); - assertEquals(new RFC2396DomainName("host", null), resValue); - - arguments.clear(); - arguments.add(attrString2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (RFC2396DomainName)res.getValue().getValue(); - assertEquals(new RFC2396DomainName("host.host", null), resValue); - - - // portrange (-port, port-, port-port) - arguments.clear(); - arguments.add(attrStringMinusPort); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (RFC2396DomainName)res.getValue().getValue(); - try { - assertEquals(new RFC2396DomainName("host.host", PortRange.newInstance("-123")), resValue); - } catch (ParseException e) { - fail("port error e="+e); - } - - arguments.clear(); - arguments.add(attrStringPortMinus); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (RFC2396DomainName)res.getValue().getValue(); - try { - assertEquals(new RFC2396DomainName("host.host", PortRange.newInstance("123-")), resValue); - } catch (ParseException e) { - fail("port error e="+e); - } - - arguments.clear(); - arguments.add(attrStringPortPort); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (RFC2396DomainName)res.getValue().getValue(); - try { - assertEquals(new RFC2396DomainName("host.host", PortRange.newInstance("1234567-432")), resValue); - } catch (ParseException e) { - fail("port error e="+e); - } - - // ":" without port - arguments.clear(); - arguments.add(attrStringNoPort); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dnsName-from-string Invalid RFC 2396 port range \"host.host:\": no port numbers", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad port number - arguments.clear(); - arguments.add(attrStringBadPort); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dnsName-from-string Invalid RFC 2396 port range \"12.34\"", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad port range - arguments.clear(); - arguments.add(attrStringTooManyPorts); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dnsName-from-string Invalid RFC 2396 port range \"-123-456\"", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad value - arguments.clear(); - arguments.add(attrStringBadValue); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dnsName-from-string Invalid RFC 2396 host name \"not valid obj value\"", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:dnsName-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - @Test - public void testString_from_dnsName() { - FunctionArgumentAttributeValue attrObj1 = null; - FunctionArgumentAttributeValue attrStringBadType = null; - String objValueString = "someName.com"; - try { - attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_DNSNAME.createAttributeValue(objValueString)); - attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); - - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_DNSNAME; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_FROM_DNSNAME, fd.getId()); - assertEquals(DataTypes.DT_DNSNAME.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - // test normal - arguments.clear(); - arguments.add(attrObj1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(objValueString, res.getValue().getValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrStringBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-from-dnsName Expected data type 'dnsName' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - } - - - - - - - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringEqualIgnoreCaseTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringEqualIgnoreCaseTest.java deleted file mode 100644 index 65f92a9f0..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringEqualIgnoreCaseTest.java +++ /dev/null @@ -1,129 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Only one function to test here. Code copy/pasted from FunctionDefinitionEqualityTest - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * In the first implementation of XACML we had separate files for each XACML Function. - * This release combines multiple Functions in fewer files to minimize code duplication. - * This file supports the following XACML codes: - * string-equal-ignore-case - * - * - */ -public class FunctionDefinitionStringEqualIgnoreCaseTest { - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - FunctionArgumentAttributeValue stringAttr1 = null; - FunctionArgumentAttributeValue stringAttr2 = null; - FunctionArgumentAttributeValue stringAttr3 = null; - FunctionArgumentAttributeValue stringAttr4 = null; - - FunctionArgumentAttributeValue intAttr1 = null; - - public FunctionDefinitionStringEqualIgnoreCaseTest() { - try { - stringAttr1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc")); - stringAttr2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc")); - stringAttr3 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("ABC")); - stringAttr4 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("def")); - intAttr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - } - - - /** - * String match even when Case is different - */ - @Test - public void testFunctionDefinitionStringEqualIgnoreCase() { - - FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_STRING_EQUAL_IGNORE_CASE; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_EQUAL_IGNORE_CASE, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - - - // test normal equals and non-equals - // check "abc" with "abc" - arguments.add(stringAttr1); - arguments.add(stringAttr2); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // check "abc" with "ABC" (should be same) - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(stringAttr3); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // test bad args data types? Not needed? - arguments.clear(); - arguments.add(stringAttr1); - arguments.add(intAttr1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - - -//TODO - null in either first or 2nd arg => NullPointerException - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringFunctionsTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringFunctionsTest.java deleted file mode 100644 index 7b556e3bc..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringFunctionsTest.java +++ /dev/null @@ -1,1497 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionStringFunctionsTest { - - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - ExpressionResult res; - - - @Test - public void testConcatenate() { - String v1 = new String("abc"); - String v2 = new String("def"); - - FunctionArgumentAttributeValue attrV1 = null; - FunctionArgumentAttributeValue attrV2 = null; - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrBlank = null; - FunctionArgumentAttributeValue attrInteger = null; - try { - attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); - attrV2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v2)); - attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_STRING_CONCATENATE; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_CONCATENATE, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // match - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrV2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - String resValue = (String)res.getValue().getValue(); - assertEquals(v1 + v2, resValue); - - // empty non-null first arg - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrV2); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - resValue = (String)res.getValue().getValue(); - assertEquals(v2, resValue); - - // empty non-null second arg - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - resValue = (String)res.getValue().getValue(); - assertEquals(v1, resValue); - - // two blanks - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - resValue = (String)res.getValue().getValue(); - assertEquals("", resValue); - - // null firat arg - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-concatenate Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // null second arg - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-concatenate Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrInteger); - arguments.add(attrV2); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-concatenate Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-concatenate Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - @Test - public void testStringStartsWith() { - String v1 = new String("abc"); - String bigger = new String("abc some string"); - String biggerNoMatch = new String(" abc some string"); - String caps = new String("AbC"); - - FunctionArgumentAttributeValue attrV1 = null; - FunctionArgumentAttributeValue attrBigger = null; - FunctionArgumentAttributeValue attrBiggerNoMatch = null; - FunctionArgumentAttributeValue attrCaps = null; - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrBlank = null; - FunctionArgumentAttributeValue attrInteger = null; - try { - attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); - attrBigger = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(bigger)); - attrBiggerNoMatch = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(biggerNoMatch)); - attrCaps = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(caps)); - attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_STRING_STARTS_WITH; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_STARTS_WITH, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // match - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // no match - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBiggerNoMatch); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // caps no match - arguments.clear(); - arguments.add(attrCaps); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // bigger on the inside - arguments.clear(); - arguments.add(attrBigger); - arguments.add(attrV1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // empty non-null first arg - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // empty non-null second arg - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // two blanks - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // null firat arg - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-starts-with Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-starts-with Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // illegal arg type - arguments.clear(); - arguments.add(attrInteger); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-starts-with Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - @Test - public void testAnyuriStartsWith() { - - - FunctionArgumentAttributeValue attrV1 = null; - FunctionArgumentAttributeValue attrBigger = null; - FunctionArgumentAttributeValue attrBiggerNoMatch = null; - FunctionArgumentAttributeValue attrCaps = null; - FunctionArgumentAttributeValue attrBigString = null; - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrBlankString = null; - FunctionArgumentAttributeValue attrBlankURI = null; - FunctionArgumentAttributeValue attrInteger = null; - try { - String v1 = new String("abc"); - URI bigger = new URI("abc.some.string"); - URI biggerNoMatch = new URI("Zabc.some.string"); - String caps = new String("AbC"); - String bigString = "thisIsSomeReallyBigStringToMatch"; - - attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); - attrBigger = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(bigger)); - attrBiggerNoMatch = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(biggerNoMatch)); - attrCaps = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(caps)); - attrBigString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(bigString)); - attrBlankString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); - attrBlankURI = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("")); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_ANYURI_STARTS_WITH; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_ANYURI_STARTS_WITH, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // match - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // no match - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBiggerNoMatch); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // caps no match - arguments.clear(); - arguments.add(attrCaps); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // bigger on the inside - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // empty non-null first arg - arguments.clear(); - arguments.add(attrBlankString); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // empty non-null second arg - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBlankURI); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - - // two blanks - arguments.clear(); - arguments.add(attrBlankString); - arguments.add(attrBlankURI); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // arguments reversed - arguments.clear(); - arguments.add(attrBigger); - arguments.add(attrV1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-starts-with Expected data type 'string' saw 'anyURI'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // null firat arg - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrBlankURI); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-starts-with Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-starts-with Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // illegal arg type - arguments.clear(); - arguments.add(attrInteger); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-starts-with Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - @Test - public void testStringEndsWith() { - String v1 = new String("abc"); - String bigger = new String("abc some string abc"); - String biggerNoMatch = new String(" abc some string abc "); - String caps = new String("AbC"); - - FunctionArgumentAttributeValue attrV1 = null; - FunctionArgumentAttributeValue attrBigger = null; - FunctionArgumentAttributeValue attrBiggerNoMatch = null; - FunctionArgumentAttributeValue attrCaps = null; - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrBlank = null; - FunctionArgumentAttributeValue attrInteger = null; - try { - attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); - attrBigger = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(bigger)); - attrBiggerNoMatch = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(biggerNoMatch)); - attrCaps = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(caps)); - attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_STRING_ENDS_WITH; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_ENDS_WITH, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // match - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // no match - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBiggerNoMatch); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // caps no match - arguments.clear(); - arguments.add(attrCaps); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // bigger on the inside - arguments.clear(); - arguments.add(attrBigger); - arguments.add(attrV1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // empty non-null first arg - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // empty non-null second arg - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // two blanks - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // null firat arg - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-ends-with Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-ends-with Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // illegal arg type - arguments.clear(); - arguments.add(attrInteger); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-ends-with Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - @Test - public void testAnyuriEndsWith() { - - - FunctionArgumentAttributeValue attrV1 = null; - FunctionArgumentAttributeValue attrBigger = null; - FunctionArgumentAttributeValue attrBiggerNoMatch = null; - FunctionArgumentAttributeValue attrCaps = null; - FunctionArgumentAttributeValue attrBigString = null; - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrBlankString = null; - FunctionArgumentAttributeValue attrBlankURI = null; - FunctionArgumentAttributeValue attrInteger = null; - try { - String v1 = new String("abc"); - URI bigger = new URI("abc.some.stringabc"); - URI biggerNoMatch = new URI("Zabc.some.stringabcZ"); - String caps = new String("AbC"); - String bigString = "thisIsSomeReallyBigStringToMatch"; - - attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); - attrBigger = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(bigger)); - attrBiggerNoMatch = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(biggerNoMatch)); - attrCaps = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(caps)); - attrBigString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(bigString)); - attrBlankString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); - attrBlankURI = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("")); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_ANYURI_ENDS_WITH; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_ANYURI_ENDS_WITH, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // match - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // no match - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBiggerNoMatch); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // caps no match - arguments.clear(); - arguments.add(attrCaps); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // bigger on the inside - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // empty non-null first arg - arguments.clear(); - arguments.add(attrBlankString); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // empty non-null second arg - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBlankURI); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - - // two blanks - arguments.clear(); - arguments.add(attrBlankString); - arguments.add(attrBlankURI); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // arguments reversed - arguments.clear(); - arguments.add(attrBigger); - arguments.add(attrV1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-ends-with Expected data type 'string' saw 'anyURI'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // null firat arg - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrBlankURI); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-ends-with Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-ends-with Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // illegal arg type - arguments.clear(); - arguments.add(attrInteger); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-ends-with Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - @Test - public void testStringSubstring() { - String bigString = new String("abc some string abc"); - - FunctionArgumentAttributeValue attrBigString = null; - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrBlank = null; - FunctionArgumentAttributeValue attrDouble = null; - - FunctionArgumentAttributeValue attrInteger0 = null; - FunctionArgumentAttributeValue attrInteger1 = null; - FunctionArgumentAttributeValue attrIntegerM1 = null; - FunctionArgumentAttributeValue attrInteger8 = null; - FunctionArgumentAttributeValue attrInteger19 = null; - FunctionArgumentAttributeValue attrInteger20 = null; - - - - try { - attrBigString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(bigString)); - attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); - attrInteger0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); - attrInteger1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); - attrIntegerM1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(-1)); - attrInteger8 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(8)); - attrInteger19 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(19)); - attrInteger20 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(20)); - attrDouble = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(123.4)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_STRING_SUBSTRING; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_SUBSTRING, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // match - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrInteger1); - arguments.add(attrInteger8); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - String resValue = (String)res.getValue().getValue(); - assertEquals("bc some", resValue); - - // edge: start - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrInteger0); - arguments.add(attrInteger8); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - resValue = (String)res.getValue().getValue(); - assertEquals("abc some", resValue); - - // edge: end - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrInteger8); - arguments.add(attrInteger19); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - resValue = (String)res.getValue().getValue(); - assertEquals(" string abc", resValue); - - // from index to end of string - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrInteger8); - arguments.add(attrIntegerM1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - resValue = (String)res.getValue().getValue(); - assertEquals(" string abc", resValue); - - // first index too low - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrIntegerM1); - arguments.add(attrInteger8); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-substring Start point '-1' out of range 0-19 for string='abc some string abc'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // second index too big - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrInteger8); - arguments.add(attrInteger20); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-substring End point '20' out of range 0-19 for string='abc some string abc'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // indexes reversed - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrInteger8); - arguments.add(attrInteger1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-substring End point '1' less than start point 'null' for string='abc some string abc'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // indexes the same - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrInteger8); - arguments.add(attrInteger8); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - resValue = (String)res.getValue().getValue(); - assertEquals("", resValue); - - // blank string with indexes both 0 - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrInteger0); - arguments.add(attrInteger0); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - resValue = (String)res.getValue().getValue(); - assertEquals("", resValue); - - // non-string first attribute - arguments.clear(); - arguments.add(attrDouble); - arguments.add(attrInteger8); - arguments.add(attrInteger1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-substring Expected data type 'string' saw 'double'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // non-integer 2nd attr - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrDouble); - arguments.add(attrInteger1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-substring Expected data type 'integer' saw 'double'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // non-integer 3rd attr - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrInteger8); - arguments.add(attrDouble); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-substring Expected data type 'integer' saw 'double'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // 4 args - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrInteger8); - arguments.add(attrInteger1); - arguments.add(attrInteger1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-substring Expected 3 arguments, got 4", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // 2 args - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrInteger8); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-substring Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null 1st arg - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrInteger8); - arguments.add(attrInteger1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-substring Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // null 2nd arg - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrNull); - arguments.add(attrInteger1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-substring Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - } - - - - - @Test - public void testAnyURISubstring() { - String bigString = new String("http://company.com:8080/this/is/some/long/uri"); - - FunctionArgumentAttributeValue attrURI = null; - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrBlank = null; - FunctionArgumentAttributeValue attrDouble = null; - - FunctionArgumentAttributeValue attrInteger0 = null; - FunctionArgumentAttributeValue attrInteger1 = null; - FunctionArgumentAttributeValue attrIntegerM1 = null; - FunctionArgumentAttributeValue attrInteger8 = null; - FunctionArgumentAttributeValue attrInteger45 = null; - FunctionArgumentAttributeValue attrInteger46 = null; - - - - try { - attrURI = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(bigString)); - attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("")); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(null)); - attrInteger0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); - attrInteger1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); - attrIntegerM1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(-1)); - attrInteger8 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(8)); - attrInteger45 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(45)); - attrInteger46 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(46)); - attrDouble = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(123.4)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_ANYURI_SUBSTRING; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_ANYURI_SUBSTRING, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // match - arguments.clear(); - arguments.add(attrURI); - arguments.add(attrInteger1); - arguments.add(attrInteger8); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - String resValue = (String)res.getValue().getValue(); - assertEquals("ttp://c", resValue); - - // edge: start - arguments.clear(); - arguments.add(attrURI); - arguments.add(attrInteger0); - arguments.add(attrInteger8); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - resValue = (String)res.getValue().getValue(); - assertEquals("http://c", resValue); - - // edge: end - arguments.clear(); - arguments.add(attrURI); - arguments.add(attrInteger8); - arguments.add(attrInteger45); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - resValue = (String)res.getValue().getValue(); - assertEquals("ompany.com:8080/this/is/some/long/uri", resValue); - - // from index to end of string - arguments.clear(); - arguments.add(attrURI); - arguments.add(attrInteger8); - arguments.add(attrIntegerM1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - resValue = (String)res.getValue().getValue(); - assertEquals("ompany.com:8080/this/is/some/long/uri", resValue); - - // first index too low - arguments.clear(); - arguments.add(attrURI); - arguments.add(attrIntegerM1); - arguments.add(attrInteger8); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-substring Start point '-1' out of range 0-45 for string='http://company.com:8080/this/is/some/long/uri'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // second index too big - arguments.clear(); - arguments.add(attrURI); - arguments.add(attrInteger8); - arguments.add(attrInteger46); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-substring End point '46' out of range 0-45 for string='http://company.com:8080/this/is/some/long/uri'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // indexes reversed - arguments.clear(); - arguments.add(attrURI); - arguments.add(attrInteger8); - arguments.add(attrInteger1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-substring End point '1' less than start point 'null' for string='http://company.com:8080/this/is/some/long/uri'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // indexes the same - arguments.clear(); - arguments.add(attrURI); - arguments.add(attrInteger8); - arguments.add(attrInteger8); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - resValue = (String)res.getValue().getValue(); - assertEquals("", resValue); - - // blank string with indexes both 0 - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrInteger0); - arguments.add(attrInteger0); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); - resValue = (String)res.getValue().getValue(); - assertEquals("", resValue); - - // non-string first attribute - arguments.clear(); - arguments.add(attrDouble); - arguments.add(attrInteger8); - arguments.add(attrInteger1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-substring Expected data type 'anyURI' saw 'double'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // non-integer 2nd attr - arguments.clear(); - arguments.add(attrURI); - arguments.add(attrDouble); - arguments.add(attrInteger1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-substring Expected data type 'integer' saw 'double'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // non-integer 3rd attr - arguments.clear(); - arguments.add(attrURI); - arguments.add(attrInteger8); - arguments.add(attrDouble); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-substring Expected data type 'integer' saw 'double'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // 4 args - arguments.clear(); - arguments.add(attrURI); - arguments.add(attrInteger8); - arguments.add(attrInteger1); - arguments.add(attrInteger1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-substring Expected 3 arguments, got 4", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // 2 args - arguments.clear(); - arguments.add(attrURI); - arguments.add(attrInteger8); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-substring Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null 1st arg - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrInteger8); - arguments.add(attrInteger1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-substring Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // null 2nd arg - arguments.clear(); - arguments.add(attrURI); - arguments.add(attrNull); - arguments.add(attrInteger1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-substring Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - - - - - - - - - - - - - - - - - - @Test - public void testStringContains() { - String v1 = new String("abc"); - String bigger = new String("abc some string abc"); - String biggerNoMatch = new String(" abc some string abc "); - String caps = new String("AbC"); - - FunctionArgumentAttributeValue attrV1 = null; - FunctionArgumentAttributeValue attrBigger = null; - FunctionArgumentAttributeValue attrBiggerNoMatch = null; - FunctionArgumentAttributeValue attrCaps = null; - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrBlank = null; - FunctionArgumentAttributeValue attrInteger = null; - try { - attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); - attrBigger = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(bigger)); - attrBiggerNoMatch = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(biggerNoMatch)); - attrCaps = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(caps)); - attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_STRING_CONTAINS; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_CONTAINS, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // match - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // no match - arguments.clear(); - arguments.add(attrBiggerNoMatch); - arguments.add(attrV1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // caps no match - arguments.clear(); - arguments.add(attrCaps); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // bigger on the inside - arguments.clear(); - arguments.add(attrBigger); - arguments.add(attrV1); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // empty non-null first arg - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // empty non-null second arg - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // two blanks - arguments.clear(); - arguments.add(attrBlank); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // null firat arg - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrBlank); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-contains Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-contains Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // illegal arg type - arguments.clear(); - arguments.add(attrInteger); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:string-contains Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - @Test - public void testAnyuriContains() { - - - FunctionArgumentAttributeValue attrV1 = null; - FunctionArgumentAttributeValue attrBigger = null; - FunctionArgumentAttributeValue attrBiggerNoMatch = null; - FunctionArgumentAttributeValue attrCaps = null; - FunctionArgumentAttributeValue attrBigString = null; - FunctionArgumentAttributeValue attrNull = null; - FunctionArgumentAttributeValue attrBlankString = null; - FunctionArgumentAttributeValue attrBlankURI = null; - FunctionArgumentAttributeValue attrInteger = null; - try { - String v1 = new String("abc"); - URI bigger = new URI("abc.some.stringabc"); - URI biggerNoMatch = new URI("Zabc.some.stringabcZ"); - String caps = new String("AbC"); - String bigString = "thisIsSomeReallyBigStringToMatch"; - - attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); - attrBigger = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(bigger)); - attrBiggerNoMatch = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(biggerNoMatch)); - attrCaps = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(caps)); - attrBigString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(bigString)); - attrBlankString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); - attrBlankURI = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("")); - attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); - attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_ANYURI_CONTAINS; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_ANYURI_CONTAINS, fd.getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // match - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // no match - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrBiggerNoMatch); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // caps no match - arguments.clear(); - arguments.add(attrCaps); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // bigger on the inside - arguments.clear(); - arguments.add(attrBigString); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - // empty non-null first arg - arguments.clear(); - arguments.add(attrBlankString); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // empty non-null second arg - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrBlankURI); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(false, resValue); - - - // two blanks - arguments.clear(); - arguments.add(attrBlankString); - arguments.add(attrBlankURI); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); - resValue = (Boolean)res.getValue().getValue(); - assertEquals(true, resValue); - - // arguments reversed - arguments.clear(); - arguments.add(attrBigger); - arguments.add(attrV1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-contains Expected data type 'string' saw 'anyURI'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // null firat arg - arguments.clear(); - arguments.add(attrNull); - arguments.add(attrBlankURI); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-contains Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null second arg - arguments.clear(); - arguments.add(attrV1); - arguments.add(attrNull); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-contains Got null attribute", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // illegal arg type - arguments.clear(); - arguments.add(attrInteger); - arguments.add(attrBigger); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:anyURI-contains Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringNormalizeTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringNormalizeTest.java deleted file mode 100644 index 0de8a0f0b..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionStringNormalizeTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionStringNormalizeTest { - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - @Test - public void testString_normalize_space() { - String initialString = " First and last are whitespace "; - FunctionArgumentAttributeValue attr1 = null; - try { - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(initialString)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringNormalize fd = (FunctionDefinitionStringNormalize) StdFunctions.FD_STRING_NORMALIZE_SPACE; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_NORMALIZE_SPACE, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - - // test normal add - arguments.add(attr1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - String resValue = (String)res.getValue().getValue(); - assertEquals(initialString.length() - 4, resValue.length()); - assertTrue(initialString.trim().equals(resValue)); - } - - - @Test - public void testString_normalize_to_lower_case() { - String initialString = " First and last are whitespace "; - FunctionArgumentAttributeValue attr1 = null; - try { - attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(initialString)); - } catch (Exception e) { - fail("creating attribute e="+ e); - } - - FunctionDefinitionStringNormalize fd = (FunctionDefinitionStringNormalize) StdFunctions.FD_STRING_NORMALIZE_TO_LOWER_CASE; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_STRING_NORMALIZE_TO_LOWER_CASE, fd.getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - - // test normal add - arguments.add(attr1); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - String resValue = (String)res.getValue().getValue(); - assertTrue(initialString.toLowerCase().equals(resValue)); - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionURIStringConcatenateTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionURIStringConcatenateTest.java deleted file mode 100644 index 8a864a1a0..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionURIStringConcatenateTest.java +++ /dev/null @@ -1,185 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.net.URI; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Test; - -import com.att.research.xacml.api.XACML2; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionURIStringConcatenateTest { - - /* - * THE FUNCTION BEING TESTED BY THIS CLASS IS DEPRECATED - * uri-string-concatenate has been deprecated in XACML 3.0 - */ - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList<>(); - - - @SuppressWarnings("deprecation") - @Test - public void testURI_string_concatenate() { - - // URI args - FunctionArgumentAttributeValue attrURI1 = null; - - - FunctionArgumentAttributeValue attrStrAbc = null; - FunctionArgumentAttributeValue attrStrSlashMno = null; - FunctionArgumentAttributeValue attrStrSlashInMiddle = null; - FunctionArgumentAttributeValue attrStrWithSpace = null; - - - try { - attrURI1 = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("http://someplace")); - - - attrStrAbc = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("Abc")); - attrStrSlashMno = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("/Mno")); - attrStrSlashInMiddle = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("hij/pqr")); - attrStrWithSpace = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("x y z")); - - - } catch (Exception e) { - fail("creating attributes e="+ e); - } - - // deprecation marking in the following line is correct - this function IS deprecated but still valid for XACML 3.0 - FunctionDefinitionURIStringConcatenate fd = (FunctionDefinitionURIStringConcatenate) StdFunctions.FD_URI_STRING_CONCATENATE; - - // check identity and type of the thing created - assertEquals(XACML2.ID_FUNCTION_URI_STRING_CONCATENATE, fd.getId()); - assertEquals(DataTypes.DT_ANYURI.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - - - // add one string to uri - arguments.clear(); - arguments.add(attrURI1); - arguments.add(attrStrAbc); - ExpressionResult res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.net.URI.class, res.getValue().getValue().getClass()); - URI resValue = (URI)res.getValue().getValue(); - assertEquals("http://someplaceAbc", resValue.toString()); - - - // add 2 strings to uri - arguments.clear(); - arguments.add(attrURI1); - arguments.add(attrStrAbc); - arguments.add(attrStrSlashMno); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.net.URI.class, res.getValue().getValue().getClass()); - resValue = (URI)res.getValue().getValue(); - assertEquals("http://someplaceAbc/Mno", resValue.toString()); - - // slash in middle of string - arguments.clear(); - arguments.add(attrURI1); - arguments.add(attrStrSlashInMiddle); - arguments.add(attrStrSlashMno); - res = fd.evaluate(null, arguments); - assertTrue(res.isOk()); - assertEquals(java.net.URI.class, res.getValue().getValue().getClass()); - resValue = (URI)res.getValue().getValue(); - assertEquals("http://someplacehij/pqr/Mno", resValue.toString()); - - // create bad uri - arguments.clear(); - arguments.add(attrURI1); - arguments.add(attrStrWithSpace); - arguments.add(attrStrSlashMno); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:uri-string-concatenate Final string 'http://someplacex y z/Mno' not URI, Illegal character in authority at index 7: http://someplacex y z/Mno", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // no args - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:uri-string-concatenate Expected 2 or more arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // one arg - arguments.clear(); - arguments.add(attrURI1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:uri-string-concatenate Expected 2 or more arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // first arg not uri - arguments.clear(); - arguments.add(attrStrAbc); - arguments.add(attrURI1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:uri-string-concatenate Expected data type 'anyURI' saw 'string' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // 2nd arg not string - arguments.clear(); - arguments.add(attrURI1); - arguments.add(attrURI1); - res = fd.evaluate(null, arguments); - assertFalse(res.isOk()); - assertEquals("function:uri-string-concatenate Expected data type 'string' saw 'anyURI' at arg index 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionXPathTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionXPathTest.java deleted file mode 100644 index 3a7d12869..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/FunctionDefinitionXPathTest.java +++ /dev/null @@ -1,1127 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.xml.namespace.NamespaceContext; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathFactory; - -import org.junit.Test; - -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.StdRequest; -import com.att.research.xacml.std.StdStatus; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacml.std.datatypes.XPathExpressionWrapper; -import com.att.research.xacml.std.dom.DOMRequest; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; -import com.att.research.xacmlatt.pdp.std.StdEvaluationContext; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.*; - -/** - * Test of PDP Functions (See XACML core spec section A.3) - * - * TO RUN - use jUnit - * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test - * - * - */ -public class FunctionDefinitionXPathTest { - - // - // Strings for the Request contents - // - - String reqStrMainStart = "" - + "" - + " " - + " " - + " Julius Hibbert" - + " " - + " " - + " This is IT! " - + " " - + " " - + " This is IT! " - + " " - + ""; - - String reqStrResourceStart = ""; - - String reqStrContentMdRecord = - " " + - "" + - "" + - "ABC Hospital" + - "Surgery" + - "" + - "" + - "Bart Simpson" + - "60" + - "male" + - "123456" + - "" + - "" + - "" + - "Gastric Cancer" + - "Hyper tension" + - "" + - "" + - "" + - "Well differentiated adeno carcinoma" + - "" + - "2000-10-05" + - "" + - "" + - " " + - " " + - ""; - String reqStrMalformedContent = - " " + - "" + - "" + - "ABC Hospital" + - "" + - ""; - String reqStrResourceEnd = " " - + " http://medico.com/record/patient/BartSimpson" - + " " - + " "; - String reqStrActionStart = ""; - - String reqStrActionEnd = "" - + "read" - + "" - + " "; - String reqStrEnvironmentStartEnd = " "; - String reqStrMainEnd = " "; - - - // combined strings for convenience - String reqStrMainResourceStart = reqStrMainStart + reqStrResourceStart; - String reqStrResourceAllEnd = reqStrResourceEnd + reqStrActionStart + reqStrActionEnd + reqStrEnvironmentStartEnd + reqStrMainEnd; - - - /* - * variables useful in the following tests - */ - List arguments = new ArrayList(); - - - - // Name Spaces used in the XML as part of these examples (copied from the Conformance tests) - needed for compiling XPaths - NamespaceContext nameSpaceContext = new NamespaceContext() { - @Override - public Iterator getPrefixes(String arg0) { return null;} - - @Override - public String getPrefix(String arg0) {return null;} - - @Override - public String getNamespaceURI(String arg0) { - if("md".equals(arg0)) { - return "http://www.medico.com/schemas/record"; - } else if ("xacml-context".equals(arg0)) { - return "urn:oasis:names:tc:xacml:3.0:context:schema:os"; - } else if ("xsi".equals(arg0)) { - return "http://www.w3.org/2001/XMLSchema-instance"; - } - return null; - } - }; - - - - // - // XPath Function Attributes available for use in tests (representing appropriate fragment of Policy) - // - - FunctionArgumentAttributeValue attrXnull = null; - FunctionArgumentAttributeValue attrXEmpty = null; - FunctionArgumentAttributeValue attrXNoCategory = null; - FunctionArgumentAttributeValue attrXNoValue = null; - FunctionArgumentAttributeValue attrXSlashSlashMdRecord = null; - FunctionArgumentAttributeValue attrXSlashSlashStar = null; - FunctionArgumentAttributeValue attrXSlashSlashMdName = null; - FunctionArgumentAttributeValue attrXSlashSlashMdMalignancy = null; - FunctionArgumentAttributeValue attrXNotInRequest = null; - FunctionArgumentAttributeValue attrXSlashSlashMdRecordSlashStar = null; - FunctionArgumentAttributeValue attrXMdPatientInfo = null; - - FunctionArgumentAttributeValue attrBadType = null; - - // String version of attrs for use in Deprecated functions - FunctionArgumentAttributeValue attrStrnull = null; - FunctionArgumentAttributeValue attrStrEmpty = null; - FunctionArgumentAttributeValue attrStrNoCategory = null; - FunctionArgumentAttributeValue attrStrNoValue = null; - FunctionArgumentAttributeValue attrStrSlashSlashMdRecord = null; - FunctionArgumentAttributeValue attrStrSlashSlashStar = null; - FunctionArgumentAttributeValue attrStrSlashSlashMdName = null; - FunctionArgumentAttributeValue attrStrSlashSlashMdMalignancy = null; - FunctionArgumentAttributeValue attrStrNotInRequest = null; - FunctionArgumentAttributeValue attrStrSlashSlashMdRecordSlashStar = null; - FunctionArgumentAttributeValue attrStrMdPatientInfo = null; - - - // - // REQUEST objects available for use in tests - // - Request requestEmpty = new StdRequest(StdStatus.STATUS_OK); - Request requestMdRecord = null; - Request requestDoubleResources = null; - Request requestResourceActionContent = null; - Request requestContentInAction = null; - - - - - /** - * Set up all variables in one place because it is complicated (lots of steps needed for each attribute) - */ - public FunctionDefinitionXPathTest() { - try { - XPathFactory xPathFactory = XPathFactory.newInstance(); - XPath xpath = xPathFactory.newXPath(); - xpath.setNamespaceContext(nameSpaceContext); - - // Create XPaths to use in expressions - XPathExpressionWrapper xEmpty = new XPathExpressionWrapper(""); - XPathExpressionWrapper xSlashSlashMdRecord = new XPathExpressionWrapper(xpath.compile("//md:record")); - XPathExpressionWrapper xSlashSlashStar = new XPathExpressionWrapper(xpath.compile("//*")); - XPathExpressionWrapper xSlashSlashMdName = new XPathExpressionWrapper(xpath.compile("//md:name")); - XPathExpressionWrapper xSlashSlashMdMalignancy = new XPathExpressionWrapper(xpath.compile("//md:malignancy")); - XPathExpressionWrapper xNotInRequest = new XPathExpressionWrapper(xpath.compile("value_Not_in_request")); - XPathExpressionWrapper xSlashSlashMdRecordSlashStar = new XPathExpressionWrapper(xpath.compile("//md:record/*")); - XPathExpressionWrapper xMdPatientInfo = new XPathExpressionWrapper(xpath.compile("md:patient_info")); - - - - // create Function Attributes out of the XPathExpressions - attrXnull = new FunctionArgumentAttributeValue(null); - attrXEmpty = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xEmpty)); - attrXNoCategory = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xSlashSlashMdRecord)); - attrXNoValue = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xEmpty, - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - attrXSlashSlashMdRecord = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xSlashSlashMdRecord, - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - attrXSlashSlashStar = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xSlashSlashStar, - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - attrXSlashSlashMdName = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xSlashSlashMdName, - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - attrXSlashSlashMdMalignancy = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xSlashSlashMdMalignancy, - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - attrXNotInRequest = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xNotInRequest, - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - - attrXSlashSlashMdRecordSlashStar = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xSlashSlashMdRecordSlashStar, - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - attrXMdPatientInfo = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xMdPatientInfo, - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - - - // Deprecated versions of args - attrStrnull = new FunctionArgumentAttributeValue(null); - attrStrEmpty = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); - attrStrNoCategory = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("//md:record")); - attrStrNoValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("", - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - attrStrSlashSlashMdRecord = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("//md:record", - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - attrStrSlashSlashStar = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("//*", - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - attrStrSlashSlashMdName = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("//md:name", - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - attrStrSlashSlashMdMalignancy = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("//md:malignancy", - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - attrStrNotInRequest = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("value_Not_in_request", - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - - attrStrSlashSlashMdRecordSlashStar = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("//md:record/*", - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - attrStrMdPatientInfo = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("md:patient_info", - new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); - - - - - attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("some string")); - - - - // Request objects - // to create a Request object the easiest way is to put the xml into a file and use the DOMRequest to load it. - - // single Content in the Resources section (normal valid request) - String reqString = reqStrMainResourceStart + reqStrContentMdRecord + reqStrResourceAllEnd; - File tFile = File.createTempFile("functionJunit", "request"); - BufferedWriter bw = new BufferedWriter(new FileWriter(tFile)); - bw.append(reqString); - bw.flush(); - bw.close(); - requestMdRecord = DOMRequest.load(tFile); - tFile.delete(); - - // Resources included twice - reqString = reqStrMainResourceStart + reqStrContentMdRecord + reqStrResourceEnd + reqStrResourceStart + reqStrContentMdRecord +reqStrResourceAllEnd; - tFile = File.createTempFile("functionJunit", "request"); - bw = new BufferedWriter(new FileWriter(tFile)); - bw.append(reqString); - bw.flush(); - bw.close(); - requestDoubleResources = DOMRequest.load(tFile); - tFile.delete(); - - - // content included in both Resource and Action - ok - reqString = reqStrMainResourceStart + reqStrContentMdRecord + reqStrResourceEnd + reqStrActionStart + reqStrContentMdRecord + reqStrActionEnd + reqStrMainEnd; - tFile = File.createTempFile("functionJunit", "request"); - bw = new BufferedWriter(new FileWriter(tFile)); - bw.append(reqString); - bw.flush(); - bw.close(); - requestResourceActionContent = DOMRequest.load(tFile); - tFile.delete(); - - // Content included only in Action - missing content produces non-error result according to spec - reqString = reqStrMainResourceStart + reqStrResourceEnd + reqStrActionStart + reqStrContentMdRecord + reqStrActionEnd + reqStrMainEnd; - tFile = File.createTempFile("functionJunit", "request"); - bw = new BufferedWriter(new FileWriter(tFile)); - bw.append(reqString); - bw.flush(); - bw.close(); - requestContentInAction = DOMRequest.load(tFile); - tFile.delete(); - - - - // Test that Bad XML is caught - @SuppressWarnings("unused") - Request requestContentMisplaced = null; - @SuppressWarnings("unused") - Request requestMalformedContent = null; - @SuppressWarnings("unused") - Request requestDoubleContent = null; - - - // Content included twice - error - reqString = reqStrMainResourceStart + reqStrContentMdRecord + reqStrContentMdRecord +reqStrResourceAllEnd; - tFile = File.createTempFile("functionJunit", "request"); - bw = new BufferedWriter(new FileWriter(tFile)); - bw.append(reqString); - bw.flush(); - bw.close(); - try { - requestDoubleContent = DOMRequest.load(tFile); - tFile.delete(); - } catch (com.att.research.xacml.std.dom.DOMStructureException e) { - // this is what it should do, so just continue - } catch (Exception e) { - fail("Unexpected exception for bad XML, e="+e); - } - - // Bad XML - Content not under a Category - reqString = reqStrMainStart + reqStrContentMdRecord + reqStrResourceStart + reqStrResourceEnd + reqStrActionStart + reqStrActionEnd + reqStrMainEnd; - tFile = File.createTempFile("functionJunit", "request"); - bw = new BufferedWriter(new FileWriter(tFile)); - bw.append(reqString); - bw.flush(); - bw.close(); - try { - requestContentMisplaced = DOMRequest.load(tFile); - tFile.delete(); - } catch (com.att.research.xacml.std.dom.DOMStructureException e) { - // this is what it should do, so just continue - } catch (Exception e) { - fail("Unexpected exception for bad XML, e="+e); - } - - // Bad XML - Content is not valid XML - reqString = reqStrMainResourceStart + reqStrMalformedContent + reqStrResourceAllEnd; - tFile = File.createTempFile("functionJunit", "request"); - bw = new BufferedWriter(new FileWriter(tFile)); - bw.append(reqString); - bw.flush(); - bw.close(); - try { - requestMalformedContent = DOMRequest.load(tFile); - tFile.delete(); - } catch (com.att.research.xacml.std.dom.DOMStructureException e) { - // this is what it should do, so just continue - } catch (Exception e) { - fail("Unexpected exception for bad XML, e="+e); - } - - } catch (Exception e) { - fail("Constructor initializing variables, e="+ e + " cause="+e.getCause()); - } - - } - - - - - - - - - @Test - public void testXpath_node_count() { - - - - FunctionDefinitionXPath fd = (FunctionDefinitionXPath) StdFunctions.FD_XPATH_NODE_COUNT; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_XPATH_NODE_COUNT, fd.getId()); - assertEquals(DataTypes.DT_XPATHEXPRESSION.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(1), fd.getNumArgs()); - - - // match all elements within context - arguments.clear(); - arguments.add(attrXSlashSlashStar); - ExpressionResult res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - BigInteger resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("18"), resValue); - - // match exactly 1 element - arguments.clear(); - arguments.add(attrXSlashSlashMdMalignancy); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("1"), resValue); - - // match a few but not all - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("2"), resValue); - - - // verify variables using in other tests: count nodes immediately under md:record - arguments.clear(); - arguments.add(attrXSlashSlashMdRecordSlashStar); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("3"), resValue); - - // verify variables using in other tests: count number of records containing patient_info - arguments.clear(); - arguments.add(attrXMdPatientInfo); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("1"), resValue); - - // verify variables using in other tests: count number of records containing md:name - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("2"), resValue); - - // verify variables using in other tests: count number of records containing md:malignancy - arguments.clear(); - arguments.add(attrXSlashSlashMdMalignancy); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("1"), resValue); - - - - - // match no element - arguments.clear(); - arguments.add(attrXNotInRequest); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("0"), resValue); - - // Resources included twice - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestDoubleResources, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-count More than one Content section for id 'urn:oasis:names:tc:xacml:3.0:attribute-category:resource'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // Content in both Resource and Action categories (ok) - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestResourceActionContent, null, null), arguments); - assertTrue(res.isOk()); - resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("2"), resValue); - - // Content only in Action category (missing in Resources -> 0 according to spec) - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestContentInAction, null, null), arguments); - assertTrue(res.isOk()); - resValue = (BigInteger)res.getValue().getValue(); - assertEquals(new BigInteger("0"), resValue); - - - - -//TODO - any other tests???? - - // null Evaluation Context - arguments.clear(); - arguments.add(attrXEmpty); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-count Got null EvaluationContext", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null Request - arguments.clear(); - arguments.add(attrXSlashSlashMdRecord); - res = fd.evaluate(new StdEvaluationContext(null, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-count Got null Request in EvaluationContext", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null attribute - arguments.clear(); - arguments.add(attrXnull); - res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-count Got null attribute at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // no value - arguments.clear(); - arguments.add(attrXNoValue); - res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-count XPathExpression returned null at index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // no category - arguments.clear(); - arguments.add(attrXNoCategory); - res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-count Got null Category at index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // too many args - arguments.clear(); - arguments.add(attrXEmpty); - arguments.add(attrXEmpty); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-count Expected 1 arguments, got 2", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too few args - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-count Expected 1 arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-count Expected data type 'xpathExpression' saw 'string' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null args - arguments.clear(); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-count Got null argument at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - @Test - public void testXpath_node_equal() { - - - FunctionDefinitionXPath fd = (FunctionDefinitionXPath) StdFunctions.FD_XPATH_NODE_EQUAL; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_XPATH_NODE_EQUAL, fd.getId()); - assertEquals(DataTypes.DT_XPATHEXPRESSION.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - - // test normal success - exactly the same set - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - arguments.add(attrXSlashSlashMdName); - ExpressionResult res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // success - second list is subset of first list - arguments.clear(); - arguments.add(attrXSlashSlashMdRecordSlashStar); - arguments.add(attrXMdPatientInfo); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // success - first list is subset of second list - arguments.clear(); - arguments.add(attrXMdPatientInfo); - arguments.add(attrXSlashSlashMdRecordSlashStar); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // success - second list contains children of first list - arguments.clear(); - arguments.add(attrXSlashSlashMdRecord); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // success - first list contains children of second list - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - arguments.add(attrXSlashSlashMdRecord); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - - - // two non-overlapping sets - arguments.clear(); - arguments.add(attrXSlashSlashMdMalignancy); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first list contains nothing - arguments.clear(); - arguments.add(attrXNotInRequest); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // second list contains nothing - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - arguments.add(attrXNotInRequest); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - - -//TODO - //????? - ///??????? add real tests - ////// - - - // Resources included twice - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestDoubleResources, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal More than one Content section for id 'urn:oasis:names:tc:xacml:3.0:attribute-category:resource'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - - // Content in both Resource and Action categories (ok) - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestResourceActionContent, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // Content only in Action category (missing in Resources -> 0 according to spec) - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestContentInAction, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - - // null Evaluation Context - arguments.clear(); - arguments.add(attrXSlashSlashMdRecord); - arguments.add(attrXSlashSlashMdRecord); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal Got null EvaluationContext", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null Request - arguments.clear(); - arguments.add(attrXSlashSlashMdRecord); - arguments.add(attrXSlashSlashMdRecord); - res = fd.evaluate(new StdEvaluationContext(null, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal Got null Request in EvaluationContext", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null attribute - arguments.clear(); - arguments.add(attrXnull); - arguments.add(attrXSlashSlashMdRecord); - res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal Got null attribute at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrXSlashSlashMdRecord); - arguments.add(attrXnull); - res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal Got null attribute at arg index 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // no value - arguments.clear(); - arguments.add(attrXNoValue); - arguments.add(attrXSlashSlashMdRecord); - res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal XPathExpression returned null at index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrXSlashSlashMdRecord); - arguments.add(attrXNoValue); - res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal XPathExpression returned null at index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // no category - arguments.clear(); - arguments.add(attrXNoCategory); - arguments.add(attrXSlashSlashMdRecord); - res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal Got null Category at index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrXSlashSlashMdRecord); - arguments.add(attrXNoCategory); - res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal XPathExpression returned null at index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many args - arguments.clear(); - arguments.add(attrXEmpty); - arguments.add(attrXEmpty); - arguments.add(attrXEmpty); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too few args - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrXEmpty); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrBadType); - arguments.add(attrXEmpty); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal Expected data type 'xpathExpression' saw 'string' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrXEmpty); - arguments.add(attrBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal Expected data type 'xpathExpression' saw 'string' at arg index 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null args - arguments.clear(); - arguments.add(attrXEmpty); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal Got null argument at arg index 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(null); - arguments.add(attrXEmpty); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-equal Got null argument at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - } - - - - - @Test - public void testXpath_node_match() { - - - FunctionDefinitionXPath fd = (FunctionDefinitionXPath) StdFunctions.FD_XPATH_NODE_MATCH; - - // check identity and type of the thing created - assertEquals(XACML3.ID_FUNCTION_XPATH_NODE_MATCH, fd.getId()); - assertEquals(DataTypes.DT_XPATHEXPRESSION.getId(), fd.getDataTypeArgs().getId()); - assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); - - // just to be safe... If tests take too long these can probably be eliminated - assertFalse(fd.returnsBag()); - assertEquals(new Integer(2), fd.getNumArgs()); - - - // test normal success - exactly the same set - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - arguments.add(attrXSlashSlashMdName); - ExpressionResult res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - Boolean resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // success - second list is subset of first list - arguments.clear(); - arguments.add(attrXSlashSlashMdRecordSlashStar); - arguments.add(attrXMdPatientInfo); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // success - first list is subset of second list - arguments.clear(); - arguments.add(attrXMdPatientInfo); - arguments.add(attrXSlashSlashMdRecordSlashStar); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // success - second list contains children of first list - arguments.clear(); - arguments.add(attrXSlashSlashMdRecord); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // success - first list contains children of second list - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - arguments.add(attrXSlashSlashMdRecord); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - - - // two non-overlapping sets - arguments.clear(); - arguments.add(attrXSlashSlashMdMalignancy); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // first list contains nothing - arguments.clear(); - arguments.add(attrXNotInRequest); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - // second list contains nothing - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - arguments.add(attrXNotInRequest); - res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - -//TODO - //????? - ///??????? add real tests - ////// - - - // Resources included twice - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestDoubleResources, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match More than one Content section for id 'urn:oasis:names:tc:xacml:3.0:attribute-category:resource'", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - // Content in both Resource and Action categories (ok) - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestResourceActionContent, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertTrue(resValue); - - // Content only in Action category (missing in Resources -> 0 according to spec) - arguments.clear(); - arguments.add(attrXSlashSlashMdName); - arguments.add(attrXSlashSlashMdName); - res = fd.evaluate(new StdEvaluationContext(requestContentInAction, null, null), arguments); - assertTrue(res.isOk()); - resValue = (Boolean)res.getValue().getValue(); - assertFalse(resValue); - - - // null Evaluation Context - arguments.clear(); - arguments.add(attrXSlashSlashMdRecord); - arguments.add(attrXSlashSlashMdRecord); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match Got null EvaluationContext", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null Request - arguments.clear(); - arguments.add(attrXSlashSlashMdRecord); - arguments.add(attrXSlashSlashMdRecord); - res = fd.evaluate(new StdEvaluationContext(null, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match Got null Request in EvaluationContext", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null attribute - arguments.clear(); - arguments.add(attrXnull); - arguments.add(attrXSlashSlashMdRecord); - res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match Got null attribute at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrXSlashSlashMdRecord); - arguments.add(attrXnull); - res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match Got null attribute at arg index 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // no value - arguments.clear(); - arguments.add(attrXNoValue); - arguments.add(attrXSlashSlashMdRecord); - res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match XPathExpression returned null at index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrXSlashSlashMdRecord); - arguments.add(attrXNoValue); - res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match XPathExpression returned null at index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // no category - arguments.clear(); - arguments.add(attrXNoCategory); - arguments.add(attrXSlashSlashMdRecord); - res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match Got null Category at index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrXSlashSlashMdRecord); - arguments.add(attrXNoCategory); - res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match XPathExpression returned null at index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too many args - arguments.clear(); - arguments.add(attrXEmpty); - arguments.add(attrXEmpty); - arguments.add(attrXEmpty); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // too few args - arguments.clear(); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrXEmpty); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // bad arg type - arguments.clear(); - arguments.add(attrBadType); - arguments.add(attrXEmpty); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match Expected data type 'xpathExpression' saw 'string' at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(attrXEmpty); - arguments.add(attrBadType); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match Expected data type 'xpathExpression' saw 'string' at arg index 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - // null args - arguments.clear(); - arguments.add(attrXEmpty); - arguments.add(null); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match Got null argument at arg index 1", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - arguments.clear(); - arguments.add(null); - arguments.add(attrXEmpty); - res = fd.evaluate(null, arguments); - assertFalse(res.getStatus().isOk()); - assertEquals( "function:xpath-node-match Got null argument at arg index 0", res.getStatus().getStatusMessage()); - assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); - - - - } - - - - // - // DEPRECATED versions that use String arguments rather than XPATHEXPRESSIONs - // are NOT supported due to ambiguity in the semantics between 2.0 ( is root and has only one in resources) - // and 3.0 ( is root and there are multiple sections in any category) - // - - - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/PDPTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/PDPTest.java deleted file mode 100644 index bd19ae357..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/PDPTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - - -import static org.junit.Assert.assertNull; -//import static org.junit.Assert.fail; - -import org.junit.Test; - -public class PDPTest { - - @Test - public void testDummy() { - assertNull(null); - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/TestRunner.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/TestRunner.java deleted file mode 100644 index 111d85276..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/TestRunner.java +++ /dev/null @@ -1,46 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test; - -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; - -public class TestRunner { - private static Result results; - - public static void main(String[] args) { - Result result = JUnitCore.runClasses(PDPTest.class); - for(Failure failure: result.getFailures()) { - System.out.println("Failed Test: " + failure.toString()); - } - results = null; - if(result.wasSuccessful()) { - System.out.println("Test Results... "); - System.out.println("Stats: \nRun Time: " + (results.getRunTime()+result.getRunTime()) + "\nTotal Tests:" + results.getRunCount()+ result.getRunCount() - + "\nFailures: " + results.getFailureCount()+ result.getFailureCount()); - System.exit(1); - } - System.out.println("Tests Failed..."); - System.out.println("Stats: \nRun Time: " + result.getRunTime() + "\nTests:" + result.getRunCount() - + "\nFailures: " + result.getFailureCount()); - } -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/Conformance.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/Conformance.java deleted file mode 100644 index fb0d6922a..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/Conformance.java +++ /dev/null @@ -1,634 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.conformance; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.PrintWriter; -import java.net.URI; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import com.att.research.xacml.api.Advice; -import com.att.research.xacml.api.Attribute; -import com.att.research.xacml.api.AttributeAssignment; -import com.att.research.xacml.api.AttributeCategory; -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.IdReference; -import com.att.research.xacml.api.Obligation; -import com.att.research.xacml.api.Response; -import com.att.research.xacml.api.Result; - -/** - * Conformance is an application that runs a ConformanceTestSet and dumps results comparing the actual and - * expected results. - * - * TO RUN in Eclipse: - * This is run as a Java Application. - * You must first create a Run/Debug Configuration: - * Under the Argument tab, in Program Arguments you must set the -i or --input command line argument. - * You should also direct the output to a file using -o or --output. (default is Console) - * See the init() method in this file for other useful arguments. - * Example for a Windows machine: - * -i testsets/conformance/xacml3.0-ct-v.0.4 - * -o \Users\yourLogin\Downloads\conformance.txt - * You must also set the VM arguments: - * -Dxacml.properties=testsets/conformance/xacml.properties . - * -Dlog4j.configuration=.\logging.properties - * - * @version $Revision: 1.2 $ - */ -public class Conformance { - private ConformanceScopeResolver scopeResolver; - private ConformanceTestEngine testEngine; - private ConformanceTestSet testSet = new ConformanceTestSet(); - private File outputFile; - private PrintWriter outputFileWriter; - - private List testNamesToRun = new ArrayList(); - - private boolean verbose; - private boolean failuresOnly; - private boolean strict; - private boolean stopOnFirstError; - - private int testsRun; - private int decisionsMatch; - private int statusCodesMatch; - private int attributesMatch; - private int policyIdsMatch; - private int policySetIdsMatch; - private int associatedAdviceMatch; - private int obligationsMatch; - private int unknownFunctions; - - - - - protected synchronized ConformanceScopeResolver getScopeResolver() { - if (this.scopeResolver == null) { - this.scopeResolver = new ConformanceScopeResolver(); - - /* - * TODO: - * Add the known scopes for the 2.0 conformance test. This could be made more general by allowing loading - * from a properties file eventually. - */ - try { - URI ID_SCOPE_ROOT = new URI("urn:root"); - URI ID_SCOPE_CHILD1 = new URI("urn:root:child1"); - URI ID_SCOPE_CHILD2 = new URI("urn:root:child2"); - URI ID_SCOPE_C1D1 = new URI("urn:root:child1:descendant1"); - URI ID_SCOPE_C1D2 = new URI("urn:root:child1:descendant2"); - URI ID_SCOPE_C2D1 = new URI("urn:root:child2:descendant1"); - URI ID_SCOPE_C2D2 = new URI("urn:root:child2:descendant2"); - - this.scopeResolver.add(ID_SCOPE_ROOT, ID_SCOPE_CHILD1); - this.scopeResolver.add(ID_SCOPE_CHILD1, ID_SCOPE_C1D1); - this.scopeResolver.add(ID_SCOPE_CHILD1, ID_SCOPE_C1D2); - this.scopeResolver.add(ID_SCOPE_ROOT, ID_SCOPE_CHILD2); - this.scopeResolver.add(ID_SCOPE_CHILD2, ID_SCOPE_C2D1); - this.scopeResolver.add(ID_SCOPE_CHILD2, ID_SCOPE_C2D2); - } catch (Exception ex) { - ex.printStackTrace(System.err); - } - - } - return this.scopeResolver; - } - - private void close() throws IOException { - if (this.outputFileWriter != null) { - this.outputFileWriter.close(); - } - } - - private boolean init(String[] args) { - boolean lenientRequests = true; - boolean lenientPolicies = false; - // default is to not run any non-first-time iterations - int iterations = -1; - String testSetDirectoryNames = ""; - for (int i = 0 ; i < args.length ; ) { - - if (args[i].equals("-h") || args[i].equals("--help") || args[i].equals("-help")) { - printHelp(); - return false; - } - - - // where the XML Request/Response files are located - if (args[i].equals("-i") || args[i].equals("--input")) { - i++; - while (i < args.length && !args[i].startsWith("-")) { - testSetDirectoryNames += " " + args[i]; - try { - testSet.addConformanceTestSet(ConformanceTestSet.loadDirectory(new File(args[i]))); - } catch (Exception ex) { - ex.printStackTrace(System.err); - return false; - } - i++; - } - - // File path name where output will be put - default is stdout == Console - } else if (args[i].equals("-o") || args[i].equals("--output")) { - if (i+1 < args.length) { - this.outputFile = new File(args[i+1]); - i += 2; - } else { - System.err.println("Missing argument to " + args[i] + " command line option"); - return false; - } - // A list of specific test names (e.g.: -t IIA001 IIA007 IIIE301) - default is to run all tests - } else if (args[i].equals("-t") || args[i].equals("--tests")) { - i++; - while (i < args.length && !args[i].startsWith("-")) { - testNamesToRun.add(args[i]); - i++; - } - if (testNamesToRun.size() == 0) { - System.err.println("Missing test names after -t or --tests argument"); - return false; - } - // Include full details in the response, both the expected reqsponse (from file) and the actual response - } else if (args[i].equals("-v") || args[i].equals("--verbose")) { - this.verbose = true; - i++; - // Report only failures (success is silent) - } else if (args[i].equals("-f") || args[i].equals("--failures")) { - this.failuresOnly = true; - i++; - // When set, the XML must not contain extra attibutes/elements. Default is "lenient" where unexpected entries are ignored - } else if (args[i].equals("-s") || args[i].equals("--strict")) { - this.strict = true; - i++; - // (self explanatory) - } else if (args[i].equals("--stop-on-error")) { - this.stopOnFirstError = true; - i++; - } else if (args[i].equals("--lenient")) { - lenientPolicies = true; - lenientRequests = true; - i++; - } else if (args[i].equals("--lenient-policies")) { - lenientPolicies = true; - i++; - } else if (args[i].equals("--lenient-requests")) { - lenientRequests = true; - i++; - } else if (args[i].equals("--strict-policies")) { - lenientPolicies = false; - i++; - } else if (args[i].equals("--strict-requests")) { - lenientRequests = false; - i++; - } else if (args[i].equals("--iterations")) { - // this is a count of how many ADDITIONAL times the decide() should be called. - // The first time decide() is called it takes a long time to set up, - // so to get an accurate number for how fast a single Request is handled we need to ignore the time for the first run - // and timings for 1 or more non-first-time calls to decide(). - if (i+1 < args.length) { - try { - iterations = Integer.parseInt(args[i+1]); - i += 2; - } catch (NumberFormatException ex) { - System.err.println("Invalid iteration count '" + args[i+1] + "'"); - return false; - } - } else { - System.err.println("Missing argument to " + args[i] + " command line option"); - return false; - } - if (iterations < 1) { - System.err.println("Cannot use --iterations " + iterations + ". Must use an integer greater than 0"); - return false; - } - } else { - System.err.println("Unknown command line option " + args[i]); - return false; - } - } - - this.testEngine = new ConformanceTestEngine(this.getScopeResolver(), lenientRequests, lenientPolicies, iterations); - - if (testSetDirectoryNames.length() == 0) { - System.err.println("No test set directory given (need -i or --iniput command line option)"); - return false; - } - if (testSet.getListConformanceTests().size() == 0) { - System.err.println("No tests in given directories: " + testSetDirectoryNames); - } - - if (testNamesToRun.size() > 0) { - String s = ""; - for (String name : testNamesToRun) { - s += ", " + name; - } - System.out.println("Tests limited to: " + s.substring(1)); - } - - if (this.outputFile == null) { - this.outputFileWriter = new PrintWriter(System.out); - } else { - try { - this.outputFileWriter = new PrintWriter(new FileOutputStream(this.outputFile)); - } catch (IOException ex) { - System.err.println("Cannot open " + this.outputFile.getAbsolutePath() + " for writing."); - return false; - } - } - - return true; - } - - private void printHelp() { - System.out.println("usage: Conformance --input OPTIONS"); - System.out.println(""); - System.out.println(" -f, --failures Only include failed tests in the output. \n"+ - " Default is to include all test's results in the output file."); - System.out.println(""); - System.out.println(" -h, --help Prints help."); - - System.out.println(""); - System.out.println(" -i, --input Directory containing the XML Request/Response files. \n"+ - " This may be multiple space-separated directory paths. REQUIRED"); - - System.out.println(""); - System.out.println(" --iterations The number of times to run through the set of tests in the input directory."); - - System.out.println(""); - System.out.println(" --lenient Allow both Requests and Policies to have unexpected elements, no data in , etc. \n"+ - " Default is to not allow anything that is not explicitly listed in the XACML spec."); - - System.out.println(""); - System.out.println(" --lenient-policies Allow Policies to have unexpected elements, no data in , etc. \n" + - " Default is to not allow anything that is not explicitly listed in the XACML spec."); - - System.out.println(""); - System.out.println(" --lenient-requests Allow Requests to have unexpected elements, no data in , etc. \n" + - " Default is to not allow anything that is not explicitly listed in the XACML spec."); - - System.out.println(""); - System.out.println(" -o, --output Directory where the output results file will be put."); - - System.out.println(""); - System.out.println(" -s, --strict Check both the Decision and all other parts of the Response (Attributes, Obligations and Advice). \n "+ - " Default is to check just the Decision."); - - System.out.println(""); - System.out.println(" --stop-on-error Stop running conformance tests the first time one fails. Default is to continue through all tests."); - - System.out.println(""); - System.out.println(" --strict-policies Require Policies to have no unexpected elements, data in , etc. \n" + - " This is the default, but can be used to override Policies when option --lenient is used."); - - System.out.println(""); - System.out.println(" --strict-requests Require Requests to have no unexpected elements, data in , etc. \n" + - " This is the default, but can be used to override Requests when option --lenient is used."); - - System.out.println(""); - System.out.println(" -t, --tests A space-separated list of specific tests to be run. \n" + - " These are just the names of the tests as in 'IIA001 IIC178'. \n" + - " Default is to run all tests in the input directory."); - - System.out.println(""); - System.out.println(" -v, --verbose The entire expected and actual Response objects in the output. \n"+ - " Default is just a summary line."); - - } - - private boolean failed(ConformanceTestResult conformanceTestResult) { - ResponseMatchResult responseMatchResult = conformanceTestResult.getResponseMatchResult(); - if (responseMatchResult == null) { - return true; - } - if (!responseMatchResult.decisionsMatch() || !responseMatchResult.statusCodesMatch()) { - return true; - } else if (this.strict) { - if (!responseMatchResult.associatedAdviceMatches() || - !responseMatchResult.attributesMatch() || - !responseMatchResult.obligationsMatch() || - !responseMatchResult.policyIdentifiersMatch() || - !responseMatchResult.policySetIdentifiersMatch() - ) { - return true; - } - } - return false; - } - - private void dump(AttributeAssignment attributeAssignment) { - this.outputFileWriter.println("\t\t\t\tAttributeAssignment:"); - if (attributeAssignment.getCategory() != null) { - this.outputFileWriter.println("\t\t\t\t\tCategory: " + attributeAssignment.getCategory().stringValue()); - } - if (attributeAssignment.getAttributeId() != null) { - this.outputFileWriter.println("\t\t\t\t\tAttributeId: " + attributeAssignment.getAttributeId().stringValue()); - } - if (attributeAssignment.getDataTypeId() != null) { - this.outputFileWriter.println("\t\t\t\t\tDataType: " + attributeAssignment.getDataTypeId().stringValue()); - } - if (attributeAssignment.getIssuer() != null) { - this.outputFileWriter.println("\t\t\t\t\tIssuer: " + attributeAssignment.getIssuer()); - } - if (attributeAssignment.getAttributeValue() != null && attributeAssignment.getAttributeValue().getValue() != null) { - this.outputFileWriter.println("\t\t\t\t\tValue: " + attributeAssignment.getAttributeValue().getValue().toString()); - } - } - - private void dump(Attribute attribute) { - this.outputFileWriter.println("\t\t\t\t\tAttribute: " + (attribute.getAttributeId() == null ? "" : attribute.getAttributeId().stringValue())); - if (attribute.getIssuer() != null) { - this.outputFileWriter.println("\t\t\t\t\t\tIssuer: " + attribute.getIssuer()); - } - Iterator> iterAttributeValues = attribute.getValues().iterator(); - if (iterAttributeValues.hasNext()) { - this.outputFileWriter.println("\t\t\t\t\t\tValues: "); - while (iterAttributeValues.hasNext()) { - this.outputFileWriter.print("\t\t\t\t\t\t\t"); - AttributeValue attributeValue = iterAttributeValues.next(); - if (attributeValue.getDataTypeId() != null) { - this.outputFileWriter.print("DataType: " + attributeValue.getDataTypeId().stringValue() + " "); - } - if (attributeValue.getValue() != null) { - this.outputFileWriter.print("Value: " + attributeValue.getValue().toString()); - } - this.outputFileWriter.println(); - } - } - } - - private void dump(AttributeCategory attributeCategory) { - this.outputFileWriter.println("\t\t\tAttributeCategory: " + (attributeCategory.getCategory() == null ? "" : attributeCategory.getCategory().stringValue())); - Collection listAttributes = attributeCategory.getAttributes(); - if (listAttributes.size() > 0) { - this.outputFileWriter.println("\t\t\t\tAttributes:"); - for (Attribute attribute: listAttributes) { - this.dump(attribute); - } - } - } - - private void dump(Result result) { - this.outputFileWriter.println("\t\t======== Result =========="); - this.outputFileWriter.println("\t\tDecision: " + (result.getDecision() == null ? "null" : result.getDecision().name())); - if (result.getStatus() == null) { - this.outputFileWriter.println("\t\tStatus: null"); - } else { - this.outputFileWriter.println("\t\tStatus:"); - if (result.getStatus().getStatusCode() != null) { - this.outputFileWriter.println("\t\t\tStatusCode: " + result.getStatus().getStatusCode().toString()); - } - if (result.getStatus().getStatusMessage() != null) { - this.outputFileWriter.println("\t\t\tStatusMessage: " + result.getStatus().getStatusMessage()); - } - if (result.getStatus().getStatusDetail() != null) { - this.outputFileWriter.println("\t\t\tStatusDetail: " + result.getStatus().getStatusDetail().toString()); - } - } - Collection listAdvice = result.getAssociatedAdvice(); - if (listAdvice.size() > 0) { - this.outputFileWriter.println("\t\tAdvice:"); - for (Advice advice : listAdvice) { - if (advice.getId() != null) { - this.outputFileWriter.println("\t\t\tId: " + advice.getId().stringValue()); - } - Collection attributeAssignments = advice.getAttributeAssignments(); - if (attributeAssignments.size() > 0) { - this.outputFileWriter.println("\t\t\tAttributeAssignments:"); - for (AttributeAssignment attributeAssignment: attributeAssignments) { - this.dump(attributeAssignment); - } - } - } - } - Collection listObligations = result.getObligations(); - if (listObligations.size() > 0) { - for (Obligation obligation: listObligations) { - if (obligation.getId() != null) { - this.outputFileWriter.println("\t\t\tId: " + obligation.getId().stringValue()); - } - Collection attributeAssignments = obligation.getAttributeAssignments(); - if (attributeAssignments.size() > 0) { - this.outputFileWriter.println("\t\t\tAttributeAssignments:"); - for (AttributeAssignment attributeAssignment : attributeAssignments) { - this.dump(attributeAssignment); - } - } - } - } - Collection listAttributeCategories = result.getAttributes(); - if (listAttributeCategories.size() > 0) { - this.outputFileWriter.println("\t\tAttributes:"); - for (AttributeCategory attributeCategory : listAttributeCategories) { - this.dump(attributeCategory); - } - } - Collection listIdReferences; - if ((listIdReferences = result.getPolicyIdentifiers()).size() > 0) { - this.outputFileWriter.println("\t\tPolicyIds:"); - for (IdReference idReference : listIdReferences) { - this.outputFileWriter.println("\t\t\t" + idReference.toString()); - } - } - if ((listIdReferences = result.getPolicySetIdentifiers()).size() > 0) { - this.outputFileWriter.println("\t\tPolicySetIds:"); - for (IdReference idReference : listIdReferences) { - this.outputFileWriter.println("\t\t\t" + idReference.toString()); - } - } - } - - private void dump(String label, Response response) { - this.outputFileWriter.println("\t========== " + label + "=========="); - if (response == null) { - this.outputFileWriter.println("null"); - return; - } - - for (Result result : response.getResults()) { - this.dump(result); - } - } - - private void dump(ConformanceTestResult conformanceTestResult) { - - ResponseMatchResult responseMatchResult = conformanceTestResult.getResponseMatchResult(); - if (this.verbose) { - this.outputFileWriter.println("========== Test " + conformanceTestResult.getConformanceTest().getTestName() + " =========="); - this.dump("Expected Response", conformanceTestResult.getExpectedResponse()); - this.dump("Actual Response", conformanceTestResult.getActualResponse()); - if (responseMatchResult != null) { - this.outputFileWriter.println("\t========== Matching =========="); - this.outputFileWriter.println("\tDecisions Match? " + responseMatchResult.decisionsMatch()); - this.outputFileWriter.println("\tStatus Codes Match? " + responseMatchResult.statusCodesMatch()); - this.outputFileWriter.println("\tAttributes Match? " + responseMatchResult.attributesMatch()); - this.outputFileWriter.println("\tPolicyIds Match? " + responseMatchResult.policyIdentifiersMatch()); - this.outputFileWriter.println("\tPolicySetIds Match? " + responseMatchResult.policySetIdentifiersMatch()); - this.outputFileWriter.println("\tAssociated Advice Match? " + responseMatchResult.associatedAdviceMatches()); - this.outputFileWriter.println("\tObligations Match? " + responseMatchResult.obligationsMatch()); - this.outputFileWriter.println("========== End =========="); - } - } else { - String testName = conformanceTestResult.getConformanceTest().getTestName(); - if (responseMatchResult != null) { - Iterator iterResultMatches = responseMatchResult.getResultMatchResults(); - if (iterResultMatches == null || !iterResultMatches.hasNext()) { - this.outputFileWriter.println(testName); - } else { - while (iterResultMatches.hasNext()) { - ResultMatchResult resultMatchResult = iterResultMatches.next(); - this.outputFileWriter.printf("%s,%s,%s,%s,%s,%s,%s,%s,%d,%d\n", - testName, - resultMatchResult.decisionsMatch(), - resultMatchResult.statusCodesMatch(), - resultMatchResult.attributesMatch(), - resultMatchResult.policyIdentifiersMatch(), - resultMatchResult.policySetIdentifiersMatch(), - resultMatchResult.associatedAdviceMatches(), - resultMatchResult.obligationsMatch(), - conformanceTestResult.getFirstCallTime(), - conformanceTestResult.getAverageTotalLoopTime() - ); - } - } - } - } - this.outputFileWriter.flush(); - } - - private boolean run(ConformanceTest conformanceTest) throws Exception { - this.testsRun++; - ConformanceTestResult conformanceTestResult = this.testEngine.run(conformanceTest); - boolean bFailed = true; - if (conformanceTestResult != null) { - ResponseMatchResult responseMatchResult = conformanceTestResult.getResponseMatchResult(); - if (responseMatchResult != null) { - if (responseMatchResult.decisionsMatch()) { - this.decisionsMatch++; - this.statusCodesMatch += (responseMatchResult.statusCodesMatch() ? 1 : 0); - this.attributesMatch += (responseMatchResult.attributesMatch() ? 1 : 0); - this.policyIdsMatch += (responseMatchResult.policyIdentifiersMatch() ? 1 : 0); - this.policySetIdsMatch += (responseMatchResult.policySetIdentifiersMatch() ? 1 : 0); - this.associatedAdviceMatch += (responseMatchResult.associatedAdviceMatches() ? 1 : 0); - this.obligationsMatch += (responseMatchResult.obligationsMatch() ? 1 : 0); - } - this.unknownFunctions += (responseMatchResult.unknownFunction() ? 1 : 0); - bFailed = this.failed(conformanceTestResult); - if (bFailed || !this.failuresOnly) { - this.dump(conformanceTestResult); - } - } else if (conformanceTestResult.getError() != null) { - this.outputFileWriter.println(conformanceTestResult.getError()); - } - } - return (!bFailed || !this.stopOnFirstError); - } - - private void run() throws Exception { - long tStart = System.currentTimeMillis(); - - if (!this.verbose) { - this.outputFileWriter.println("Test,Decision,Status,Attributes,PolicyIds,PolicySetIds,Advice,Obligations"); - } - Iterator iterConformanceTests = this.testSet.getConformanceTests(); - boolean bContinue = true; - while (bContinue && iterConformanceTests.hasNext()) { -// bContinue = this.run(iterConformanceTests.next()); - ConformanceTest test = iterConformanceTests.next(); - if (testNamesToRun.size() > 0) { - if ( ! testNamesToRun.contains(test.getTestName())) { - continue; - } - } - bContinue = this.run(test); - } - - long tElapsed = System.currentTimeMillis() - tStart; - - if (this.verbose) { - this.outputFileWriter.println("Tests run = " + this.testsRun); - this.outputFileWriter.println("Decisions match = " + this.decisionsMatch); - this.outputFileWriter.println("Status Codes match = " + this.statusCodesMatch); - this.outputFileWriter.println("Attributes match = " + this.attributesMatch); - this.outputFileWriter.println("PolicyIds match = " + this.policyIdsMatch); - this.outputFileWriter.println("PolicySetIds match = " + this.policySetIdsMatch); - this.outputFileWriter.println("Associated Advice match = " + this.associatedAdviceMatch); - this.outputFileWriter.println("Obligations match = " + this.obligationsMatch); - this.outputFileWriter.println("Unknown functions = " + this.unknownFunctions); - } else { - this.outputFileWriter.printf("Total (%d),%d,%d,%d,%d,%d,%d,%d,%d\n", - this.testsRun, - this.decisionsMatch, - this.statusCodesMatch, - this.attributesMatch, - this.policyIdsMatch, - this.policySetIdsMatch, - this.associatedAdviceMatch, - this.obligationsMatch, - this.unknownFunctions); - } - - if (tElapsed > 0) { - long tHours = tElapsed / (60*60*1000); - tElapsed = tElapsed - tHours * 60 * 60 *1000; - long tMinutes = tElapsed / (60*1000); - tElapsed = tElapsed - tMinutes * 60 * 1000; - long tSeconds = tElapsed / 1000; - tElapsed = tElapsed - tSeconds * 1000; - - this.outputFileWriter.printf("Elapsed time = %02d:%02d:%02d.%03d\n", tHours, tMinutes, tSeconds, tElapsed); - this.outputFileWriter.printf("First decide time in nano-seconds %d\n", this.testEngine.getFirstDecideTime()); - this.outputFileWriter.printf("Total Multiple decide time in nano-seconds %d\n", this.testEngine.getDecideTimeMultiple()); - - this.outputFileWriter.printf("\nAverage First decide time in nano-seconds %d\n", this.testEngine.getAvgFirstDecideTime()); - this.outputFileWriter.printf("Average decide time after first call in nano-seconds %d\n", this.testEngine.getAvgDecideTimeMultiple()); - } - } - - public Conformance() { - } - - public static void main(String[] args) { - Conformance conformance = new Conformance(); - try { - if (conformance.init(args)) { - conformance.run(); - } - - } catch (Exception ex) { - ex.printStackTrace(System.err); - System.exit(1); - } finally { - try { - conformance.close(); - } catch (IOException ex) { - ex.printStackTrace(System.err); - } - } - System.exit(0); - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformancePIPEngine.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformancePIPEngine.java deleted file mode 100644 index 64085411f..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformancePIPEngine.java +++ /dev/null @@ -1,242 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.conformance; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStreamReader; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -import com.att.research.xacml.api.Attribute; -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.DataType; -import com.att.research.xacml.api.DataTypeException; -import com.att.research.xacml.api.DataTypeFactory; -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.api.pip.PIPException; -import com.att.research.xacml.api.pip.PIPFinder; -import com.att.research.xacml.api.pip.PIPRequest; -import com.att.research.xacml.api.pip.PIPResponse; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.StdMutableAttribute; -import com.att.research.xacml.std.pip.StdPIPResponse; -import com.att.research.xacml.std.pip.engines.ConfigurableEngine; -import com.att.research.xacml.util.FactoryException; - -/** - * ConformancePIPEngine implements the {@link com.att.research.xacml.api.pip.PIPFinder} interface to find attributes - * loaded from a text file containing the following fields: - * category-id,attribute-id,datatype-id,issuer,value - * - * @version $Revision: 1.1 $ - */ -public class ConformancePIPEngine implements ConfigurableEngine { - public static final String PROP_DESCRIPTION = ".description"; - public static final String PROP_FILE = ".file"; - - private static final Logger logger = FlexLogger.getLogger(ConformancePIPEngine.class); - - private String name; - private String description; - private Map cache = new HashMap<>(); - private List listAttributes = new ArrayList<>(); - private DataTypeFactory dataTypeFactory; - - public ConformancePIPEngine() { - - } - - protected DataTypeFactory getDataTypeFactory() throws FactoryException { - if (this.dataTypeFactory == null) { - this.dataTypeFactory = DataTypeFactory.newInstance(); - } - return this.dataTypeFactory; - } - - protected static String generateKey(PIPRequest pipRequest) { - StringBuilder stringBuilder = new StringBuilder(pipRequest.getCategory().toString()); - stringBuilder.append('+'); - stringBuilder.append(pipRequest.getAttributeId().toString()); - stringBuilder.append('+'); - stringBuilder.append(pipRequest.getDataTypeId().toString()); - String issuer = pipRequest.getIssuer(); - if (issuer != null) { - stringBuilder.append('+'); - stringBuilder.append(issuer); - } - return stringBuilder.toString(); - } - - protected void store(String[] fields) throws FactoryException { - DataTypeFactory thisDataTypeFactory = this.getDataTypeFactory(); - Identifier identifierCategory = new IdentifierImpl(fields[0]); - Identifier identifierAttribute = new IdentifierImpl(fields[1]); - Identifier identifierDataType = new IdentifierImpl(fields[2]); - String issuer = (fields.length == 5 ? fields[3] : null); - String value = fields[fields.length - 1]; - - DataType dataType = thisDataTypeFactory.getDataType(identifierDataType); - if (dataType == null) { - logger.error("Unknown data type " + identifierDataType.stringValue()); - return; - } - - AttributeValue attributeValue = null; - try { - attributeValue = dataType.createAttributeValue(value); - } catch (DataTypeException ex) { - throw new FactoryException("DataTypeException creating AttributeValue", ex); - } - Attribute attribute = new StdMutableAttribute(identifierCategory, identifierAttribute, attributeValue, issuer, false); - this.listAttributes.add(attribute); - } - - public void loadAttributes(File fileAttributes) throws IOException, ParseException, FactoryException { - if (fileAttributes != null) { - if (!fileAttributes.exists()) { - throw new FileNotFoundException("Attributes file " + fileAttributes.getAbsolutePath() + " not found."); - } else if (!fileAttributes.canRead()) { - throw new IOException("Attributes file " + fileAttributes.getAbsolutePath() + " is not readable."); - } - - BufferedReader bufferedReader = null; - try { - bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileAttributes))); - String line; - while ((line = bufferedReader.readLine()) != null) { - if (line.length() > 0) { - String[] fields = line.split("[|]",-1); - if (fields.length < 4) { - logger.warn("Not enough fields in record \"" + line + "\""); - continue; - } - this.store(fields); - - } - } - } finally { - if (bufferedReader != null) { - bufferedReader.close(); - } - } - } - } - - protected Attribute findAttribute(PIPRequest pipRequest) { - Attribute attributeResult = null; - Iterator iterAttributes = this.listAttributes.iterator(); - while ((attributeResult == null) && iterAttributes.hasNext()) { - Attribute attributeTest = iterAttributes.next(); - if (pipRequest.getCategory().equals(attributeTest.getCategory()) && - pipRequest.getAttributeId().equals(attributeTest.getAttributeId()) && - (pipRequest.getIssuer() == null || pipRequest.getIssuer().equals(attributeTest.getIssuer()))) { - attributeResult = attributeTest; - } - } - return attributeResult; - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { - String pipRequestKey = generateKey(pipRequest); - PIPResponse pipResponse = this.cache.get(pipRequestKey); - if (pipResponse != null) { - return pipResponse; - } - Attribute attributeMatch = this.findAttribute(pipRequest); - if (attributeMatch == null) { - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - /* - * Iterate through the values and only return the ones that match the requested data type - */ - List> matchingValues = new ArrayList<>(); - Iterator> iterAttributeValues = attributeMatch.getValues().iterator(); - while (iterAttributeValues.hasNext()) { - AttributeValue attributeValue = iterAttributeValues.next(); - if (pipRequest.getDataTypeId().equals(attributeValue.getDataTypeId())) { - matchingValues.add(attributeValue); - } - } - if (matchingValues.size() > 0) { - Attribute attributeResponse = new StdMutableAttribute(attributeMatch.getCategory(), attributeMatch.getAttributeId(), matchingValues, attributeMatch.getIssuer(), false); - pipResponse = new StdPIPResponse(attributeResponse); - this.cache.put(pipRequestKey, pipResponse); - } - return pipResponse; - } - - @Override - public String getName() { - return this.name; - } - - @Override - public String getDescription() { - return this.description; - } - - @Override - public void configure(String id, Properties properties) throws PIPException { - this.name = id; - this.description = properties.getProperty(id + PROP_DESCRIPTION); - if (this.description == null) { - this.description = "PIPEngine for the Conformance tests that loads attributes from a CSV file"; - } - String pipFile = properties.getProperty(id + PROP_FILE); - if (pipFile != null) { - try { - this.loadAttributes(new File(pipFile)); - } catch (Exception ex) { - logger.error("Exception loading PIP file " + pipFile, ex); - throw new PIPException("Exception loading PIP file " + pipFile, ex); - } - } - } - - @Override - public Collection attributesRequired() { - return Collections.emptyList(); - } - - @Override - public Collection attributesProvided() { - // - // We could return everything in our list - // - return Collections.emptyList(); - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceRepository.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceRepository.java deleted file mode 100644 index edbfbbf62..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceRepository.java +++ /dev/null @@ -1,127 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.conformance; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Properties; - -import com.att.research.xacml.util.StringUtils; -import com.att.research.xacml.util.XACMLProperties; -import com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory; - -/** - * ConformanceRepository represents one or more policies for a single policy test, which will include one or more root policies, and - * zero or more referenced policies. - * - * @version $Revision$ - */ -public class ConformanceRepository { - private List rootPolicies = new ArrayList<>(); - private List referencedPolicies = new ArrayList<>(); - - private void setXACMLProperty(String propertyName, List listFiles) { - Iterator iterFiles = listFiles.iterator(); - StringBuilder stringBuilderIdList = new StringBuilder(); - while (iterFiles.hasNext()) { - File file = iterFiles.next(); - if (stringBuilderIdList.length() > 0) { - stringBuilderIdList.append(','); - } - stringBuilderIdList.append(file.getName()); - - XACMLProperties.setProperty(file.getName() + StdPolicyFinderFactory.PROP_FILE, file.getAbsolutePath()); - } - XACMLProperties.setProperty(propertyName, stringBuilderIdList.toString()); - } - - public ConformanceRepository() { - } - - public void setXACMLProperties() { - if (this.rootPolicies.size() > 0) { - this.setXACMLProperty(XACMLProperties.PROP_ROOTPOLICIES, this.rootPolicies); - } - if (this.referencedPolicies.size() > 0) { - this.setXACMLProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, this.referencedPolicies); - } - } - - private void loadProperty(File fileDir, Properties properties, String propertyName, List listFiles) { - String fileNameList = properties.getProperty(propertyName); - if (fileNameList != null) { - String[] fileNameArray = fileNameList.split("[,]",0); - if (fileNameArray != null && fileNameArray.length > 0) { - for (String fileName : fileNameArray) { - File file = new File(fileDir, fileName); - if (file.exists() && file.canRead()) { - listFiles.add(file); - } - } - } - } - } - - public void load(File fileRepository) throws IOException { - Properties propertiesRepository = new Properties(); - try (InputStream is = new FileInputStream(fileRepository)) { - propertiesRepository.load(is); - } - this.loadProperty(fileRepository.getParentFile(), propertiesRepository, XACMLProperties.PROP_ROOTPOLICIES, this.rootPolicies); - this.loadProperty(fileRepository.getParentFile(), propertiesRepository, XACMLProperties.PROP_REFERENCEDPOLICIES, this.referencedPolicies); - } - - public void addRootPolicy(File filePolicy) { - this.rootPolicies.add(filePolicy); - } - - public boolean hasRootPolicy() { - return (this.rootPolicies.size() > 0); - } - - @Override - public String toString() { - StringBuilder stringBuilder = new StringBuilder("{"); - boolean needComma = false; - - if (this.rootPolicies != null && this.rootPolicies.size() > 0) { - stringBuilder.append("rootPolicies="); - stringBuilder.append(StringUtils.toString(this.rootPolicies.iterator())); - needComma = true; - } - if (this.referencedPolicies != null && this.referencedPolicies.size() > 0) { - if (needComma) { - stringBuilder.append(','); - } - stringBuilder.append("referencedPolicies="); - stringBuilder.append(StringUtils.toString(this.referencedPolicies.iterator())); - needComma = true; - } - stringBuilder.append('}'); - return stringBuilder.toString(); - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceScopeResolver.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceScopeResolver.java deleted file mode 100644 index 76149869a..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceScopeResolver.java +++ /dev/null @@ -1,121 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.conformance; - -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -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 com.att.research.xacml.api.Attribute; -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.pdp.ScopeQualifier; -import com.att.research.xacml.api.pdp.ScopeResolver; -import com.att.research.xacml.api.pdp.ScopeResolverException; -import com.att.research.xacml.api.pdp.ScopeResolverResult; -import com.att.research.xacml.std.StdMutableAttribute; -import com.att.research.xacml.std.StdScopeResolverResult; -import com.att.research.xacml.std.StdStatus; -import com.att.research.xacml.std.StdStatusCode; -import com.att.research.xacml.std.datatypes.DataTypes; - -/** - * ConformanceScopeResolver implements {@link com.att.research.xacml.pdp.ScopeResolver} for the conformance tests - * using a fixed set of hierarchical resources defined in a map. - * - * @version $Revision$ - */ -public class ConformanceScopeResolver implements ScopeResolver { - private Logger logger = FlexLogger.getLogger(ConformanceScopeResolver.class); - private Map> mapIdentifierToChildren = new HashMap<>(); - - public ConformanceScopeResolver() { - } - - public void add(URI identifierRoot, URI identifierChild) { - List listChildrenRoot = this.mapIdentifierToChildren.get(identifierRoot); - if (listChildrenRoot == null) { - listChildrenRoot = new ArrayList<>(); - this.mapIdentifierToChildren.put(identifierRoot, listChildrenRoot); - } - listChildrenRoot.add(identifierChild); - } - - private void addChildren(Attribute attributeResourceId, URI urnResourceIdValue, boolean bDescendants, List listAttributes) { - List listChildren = this.mapIdentifierToChildren.get(urnResourceIdValue); - if (listChildren != null) { - for (URI uriChild : listChildren) { - AttributeValue attributeValueURI = null; - try { - attributeValueURI = DataTypes.DT_ANYURI.createAttributeValue(uriChild); - if (attributeValueURI != null) { - listAttributes.add(new StdMutableAttribute(attributeResourceId.getCategory(), attributeResourceId.getAttributeId(), attributeValueURI, attributeResourceId.getIssuer(), attributeResourceId.getIncludeInResults())); - } - } catch (Exception ex) { - this.logger.error("Exception converting URI to an AttributeValue"); - } - if (bDescendants) { - this.addChildren(attributeResourceId, uriChild, bDescendants, listAttributes); - } - } - } - } - - private void addChildren(Attribute attributeResourceId, boolean bDescendants, List listAttributes) { - /* - * Iterate over the values that are URNs - */ - Iterator> iterAttributeValueURNs = attributeResourceId.findValues(DataTypes.DT_ANYURI); - if (iterAttributeValueURNs != null) { - while (iterAttributeValueURNs.hasNext()) { - this.addChildren(attributeResourceId, iterAttributeValueURNs.next().getValue(), bDescendants, listAttributes); - } - } - } - - @Override - public ScopeResolverResult resolveScope(Attribute attributeResourceId, ScopeQualifier scopeQualifier) throws ScopeResolverException { - List listAttributes = new ArrayList<>(); - switch(scopeQualifier) { - case CHILDREN: - listAttributes.add(attributeResourceId); - this.addChildren(attributeResourceId, false, listAttributes); - break; - case DESCENDANTS: - listAttributes.add(attributeResourceId); - this.addChildren(attributeResourceId, true, listAttributes); - break; - case IMMEDIATE: - listAttributes.add(attributeResourceId); - break; - default: - this.logger.error("Unknown ScopeQualifier: " + scopeQualifier.name()); - return new StdScopeResolverResult(new StdStatus(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, "Unknown ScopeQualifier " + scopeQualifier.name())); - } - return new StdScopeResolverResult(listAttributes); - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTest.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTest.java deleted file mode 100644 index bb985ad7a..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.conformance; - -import java.io.File; - -/** - * ConformanceTest represents a collection of XACML files with a root Policy document, optional referenced Policy documents, a Request, and a Response. - * - * @version $Revision: 1.2 $ - */ -public class ConformanceTest { - private String testName; - private File request; - private File response; - private ConformanceRepository repository; - - public ConformanceTest(String name, ConformanceRepository conformanceRepository, File fileRequest, File fileResponse) { - this.testName = name; - this.request = fileRequest; - this.response = fileResponse; - this.repository = conformanceRepository; - } - - public ConformanceTest(String name) { - this.testName = name; - } - - public String getTestName() { - return this.testName; - } - public void setTestName(String s) { - this.testName = s; - } - public ConformanceRepository getRepository() { - if (this.repository == null) { - this.repository = new ConformanceRepository(); - } - return this.repository; - } - public File getRequest() { - return this.request; - } - public void setRequest(File f) { - this.request = f; - } - public File getResponse() { - return this.response; - } - public void setResponse(File f) { - this.response = f; - } - - public boolean isComplete() { - return this.getTestName() != null && this.getRepository() != null && this.getRepository().hasRootPolicy() && this.getRequest() != null && this.getResponse() != null; - } - - @Override - public String toString() { - StringBuilder stringBuilder = new StringBuilder(); - boolean needColon = false; - if (this.getTestName() != null) { - stringBuilder.append(this.getTestName()); - needColon = true; - } - if (this.getRepository() != null) { - - } - if (this.getRequest() != null) { - if (needColon) { - stringBuilder.append(':'); - } - stringBuilder.append(this.getRequest().getName()); - needColon = true; - } - if (this.getResponse() != null) { - if (needColon) { - stringBuilder.append(':'); - } - stringBuilder.append(this.getResponse().getName()); - needColon = true; - } - return stringBuilder.toString(); - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTestEngine.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTestEngine.java deleted file mode 100644 index c2ad3a207..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTestEngine.java +++ /dev/null @@ -1,219 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.conformance; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.Response; -import com.att.research.xacml.api.pdp.PDPEngine; -import com.att.research.xacml.api.pdp.PDPEngineFactory; -import com.att.research.xacml.api.pdp.ScopeResolver; -import com.att.research.xacml.std.dom.DOMProperties; -import com.att.research.xacml.std.dom.DOMRequest; -import com.att.research.xacml.std.dom.DOMResponse; -import com.att.research.xacml.util.FactoryException; - -/** - * ConformanceTestEngine handles the creation of the PDPEngine for a ConformanceTest instance. - * - * @version $Revision: 1.2 $ - */ -public class ConformanceTestEngine { - private Logger logger = FlexLogger.getLogger(ConformanceTestEngine.class); - - private PDPEngineFactory pdpEngineFactory; - private ScopeResolver scopeResolver; - private boolean lenientRequests; - private boolean lenientPolicies; - private int iterations = 1; - - // total of all first calls to decide() - private long firstDecideTime; - private int numberOfFirstDecides = 0; - - // total of all non-first-calls to decide() - private long decideTimeMultiple; - - // total of average time each test case uses for a Request - // (sum of : for each test case, average of all non-first-call calls to decide() ) - private long avgDecideTimeMultiple = 0; - - protected PDPEngineFactory getPDPEngineFactory() throws FactoryException { - if (this.pdpEngineFactory == null) { - this.pdpEngineFactory = PDPEngineFactory.newInstance(); - this.pdpEngineFactory.setScopeResolver(this.scopeResolver); - } - return this.pdpEngineFactory; - } - - public ConformanceTestEngine(ScopeResolver scopeResolverIn, boolean lenientRequestsIn, boolean lenientPoliciesIn, int iterationsIn) { - this.scopeResolver = scopeResolverIn; - this.lenientRequests = lenientRequestsIn; - this.lenientPolicies = lenientPoliciesIn; - this.iterations = iterationsIn; - } - - public ConformanceTestResult run(ConformanceTest conformanceTest) { - if (conformanceTest.getRequest() == null || conformanceTest.getResponse() == null || conformanceTest.getRepository() == null) { - logger.error("Incomplete Conformance Test: " + conformanceTest.getTestName()); - } - PDPEngineFactory thisPDPEngineFactory = null; - try { - thisPDPEngineFactory = this.getPDPEngineFactory(); - } catch (FactoryException ex) { - return new ConformanceTestResult(conformanceTest, ex); - } - - ConformanceTestResult conformanceTestResult = new ConformanceTestResult(conformanceTest, iterations); - - /* - * Load the request - */ - Request request = null; - boolean isLenient = DOMProperties.isLenient(); - try { - DOMProperties.setLenient(this.lenientRequests); - try { - request = DOMRequest.load(conformanceTest.getRequest()); - conformanceTestResult.setRequest(request); - } catch (Exception ex) { - logger.error("Exception loading Request file " + conformanceTest.getRequest().getAbsolutePath(), ex); - conformanceTestResult.setError(ex); - return conformanceTestResult; - - } - - /* - * Load the expected response - */ - Response response = null; - try { - response = DOMResponse.load(conformanceTest.getResponse()); - conformanceTestResult.setExpectedResponse(response); - } catch (Exception ex) { - logger.error("Exception loading Response file " + conformanceTest.getResponse().getAbsolutePath(), ex); - conformanceTestResult.setError(ex); - return conformanceTestResult; - } - - /* - * Set up the configuration for the policy finder - */ - conformanceTest.getRepository().setXACMLProperties(); - DOMProperties.setLenient(this.lenientPolicies); - - /* - * Create the engine - */ - PDPEngine pdpEngine = null; - try { - // pdpEngine = thisPDPEngineFactory.newEngine(conformanceTest.getRootPolicy(), conformanceTest.getReferencedPolicies(), pipFinderEngine); - pdpEngine = thisPDPEngineFactory.newEngine(); - } catch (Exception ex) { - logger.error("Exception getting PDP engine instance", ex); - conformanceTestResult.setError(ex); - return conformanceTestResult; - } - if (pdpEngine == null) { - logger.error("Null PDP engine"); - conformanceTestResult.setError(new NullPointerException("Null engine")); - return conformanceTestResult; - } - - /* - * Run the request - */ - long startTime, endTime; - long curDecideTime = this.firstDecideTime; - try { - startTime = System.nanoTime(); - response = pdpEngine.decide(request); - endTime = System.nanoTime(); -//System.out.println(endTime - startTime); - // add to total - this.firstDecideTime += endTime - startTime; - this.numberOfFirstDecides++; - // remember just this test - conformanceTestResult.setFirstCallTime(endTime - startTime); - conformanceTestResult.setActualResponse(response); - } catch (Exception ex) { - logger.error("Exception in decide", ex); - conformanceTestResult.setError(ex); - return conformanceTestResult; - } - if (response == null) { - logger.error("Null Response"); - conformanceTestResult.setError(new NullPointerException("Null Response")); - return conformanceTestResult; - } - - long localLoopTime = 0; - try { - // if user requested non-first-call calls to decide() to get performance info, run them now. - // We can ignore the result since we are only interested in how long they take to process the Request. - for (int i = 0 ; i < this.iterations ; i++) { - startTime = System.nanoTime(); - pdpEngine.decide(request); - endTime = System.nanoTime(); -//System.out.println(endTime - startTime); - // add to the global total for all tests - this.decideTimeMultiple += (endTime - startTime); - // remember just this one test's info - localLoopTime += (endTime - startTime); - } - } catch (Exception ex) { - logger.error("Exception in iterated decide", ex); - return conformanceTestResult; - } - - // add to total average for non-first-call times for all test cases - avgDecideTimeMultiple += (localLoopTime / iterations); -//System.out.println("localLoop="+localLoopTime + " it="+iterations + " avg=" + (localLoopTime / iterations) ); - // remember average time for just this test - conformanceTestResult.setAverageTotalLoopTime(localLoopTime/iterations); - - long elapsedDecideTime = this.firstDecideTime - curDecideTime; - logger.info("Decide Time: " + elapsedDecideTime + "ns"); - - return conformanceTestResult; - } finally { - DOMProperties.setLenient(isLenient); - } - } - - public long getFirstDecideTime() { - return this.firstDecideTime; - } - - public long getDecideTimeMultiple() { - return this.decideTimeMultiple; - } - - - public long getAvgFirstDecideTime() { - return this.firstDecideTime / numberOfFirstDecides; - } - public long getAvgDecideTimeMultiple() { - return this.avgDecideTimeMultiple / numberOfFirstDecides; - } -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTestResult.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTestResult.java deleted file mode 100644 index a6b789679..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTestResult.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.conformance; - -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.Response; - -/** - * ConformanceTestResult holds all of the objects for a single conformance test run. - * - * @version $Revision: 1.1 $ - */ -public class ConformanceTestResult { - private ConformanceTest conformanceTest; - private Request request; - private Response expectedResponse; - private Response actualResponse; - private ResponseMatchResult responseMatchResult; - private Exception error; - - // performance timings - private long firstCallTime; - private long averageTotalLoopTime; - - // how many non-first-call times the decide() was called - private int iterations; - - public ConformanceTestResult(ConformanceTest conformanceTestIn, int iterations) { - this.conformanceTest = conformanceTestIn; - this.iterations = iterations; - } - - public ConformanceTestResult(ConformanceTest conformanceTestIn, Exception errorIn) { - this.conformanceTest = conformanceTestIn; - this.error = errorIn; - } - - public int getIterations() { - return this.iterations; - } - - public ConformanceTest getConformanceTest() { - return this.conformanceTest; - } - public void setConformanceTest(ConformanceTest conformanceTestIn) { - this.conformanceTest = conformanceTestIn; - } - - public Request getRequest() { - return this.request; - } - public void setRequest(Request requestIn) { - this.request = requestIn; - } - - public Response getExpectedResponse() { - return this.expectedResponse; - } - public void setExpectedResponse(Response response) { - this.expectedResponse = response; - this.responseMatchResult = null; - } - - public Response getActualResponse() { - return this.actualResponse; - } - public void setActualResponse(Response response) { - this.actualResponse = response; - this.responseMatchResult = null; - } - - public ResponseMatchResult getResponseMatchResult() { - if (this.responseMatchResult == null && (this.actualResponse != null && this.expectedResponse != null)) { - this.computeResponseMatchResult(); - } - return this.responseMatchResult; - } - public void computeResponseMatchResult() { - if (this.expectedResponse != null && this.actualResponse != null) { - this.responseMatchResult = ResponseMatchResult.newInstance(this.expectedResponse, this.actualResponse); - } - } - public Exception getError() { - return this.error; - } - public void setError(Exception ex) { - this.error = ex; - } - - public long getFirstCallTime() { - return firstCallTime; - } - public void setFirstCallTime(long t) { - firstCallTime = t; - } - public long getAverageTotalLoopTime(){ - return averageTotalLoopTime; - } - public void setAverageTotalLoopTime(long t) { - averageTotalLoopTime = t; - } - - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTestSet.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTestSet.java deleted file mode 100644 index 2df4dbc2f..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ConformanceTestSet.java +++ /dev/null @@ -1,180 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.conformance; - -import java.io.File; -import java.io.IOException; -import java.nio.file.FileVisitResult; -import java.nio.file.FileVisitor; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -/** - * ConformanceTestSet represents a collection of ConformanceTests ordered by the test name. It has methods for - * scanning a directory to generate an ordered set. - * - * @version $Revision: 1.1 $ - */ -public class ConformanceTestSet { - private static final Logger logger = FlexLogger.getLogger(ConformanceTestSet.class); - private List listConformanceTests = new ArrayList<>(); - - protected List getListConformanceTests() { - return this.listConformanceTests; - } - - protected ConformanceTestSet() { - - } - - private static String getTestName(String fileName, int itemPos) { - return (itemPos == 0 ? "NULL" : fileName.substring(0, itemPos)); - } - - private static String getTestName(File file) { - String fileName = file.getName(); - int itemPos = fileName.indexOf("Policy"); - if (itemPos >= 0) { - return getTestName(fileName, itemPos); - } else if ((itemPos = fileName.indexOf("Request")) >= 0) { - return getTestName(fileName, itemPos); - } else if ((itemPos = fileName.indexOf("Response")) >= 0) { - return getTestName(fileName, itemPos); - } else if ((itemPos = fileName.indexOf("Repository")) >= 0) { - return getTestName(fileName, itemPos); - } else { - return null; - } - } - - public static ConformanceTestSet loadDirectory(File fileDir) throws IOException { - final Map mapConformanceTests = new HashMap(); - - Files.walkFileTree(fileDir.toPath(), new FileVisitor() { - @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { - logger.info("Scanning directory " + dir.getFileName()); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - File fileVisited = file.toFile(); - String fileName = fileVisited.getName(); - if (fileName.endsWith(".xml") || fileName.endsWith(".properties")) { - String testName = getTestName(fileVisited); - if (testName != null) { - ConformanceTest conformanceTest = mapConformanceTests.get(testName); - if (conformanceTest == null) { - logger.info("Added test " + testName); - conformanceTest = new ConformanceTest(testName); - mapConformanceTests.put(testName, conformanceTest); - } - if (fileName.endsWith("Policy.xml")) { - conformanceTest.getRepository().addRootPolicy(fileVisited); - } else if (fileName.endsWith("Repository.properties")) { - conformanceTest.getRepository().load(fileVisited); - } else if (fileName.endsWith("Request.xml")) { - conformanceTest.setRequest(fileVisited); - } else if (fileName.endsWith("Response.xml")) { - conformanceTest.setResponse(fileVisited); - } - } - } - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { - logger.warn("Skipped " + file.getFileName()); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { - return FileVisitResult.CONTINUE; - } - }); - - /* - * Sort the keyset and pull out the tests that have the required components - */ - List listTestNames = new ArrayList<>(); - listTestNames.addAll(mapConformanceTests.keySet()); - Collections.sort(listTestNames); - - ConformanceTestSet conformanceTestSet = new ConformanceTestSet(); - Iterator iterTestNames = listTestNames.iterator(); - while (iterTestNames.hasNext()) { - ConformanceTest conformanceTest = mapConformanceTests.get(iterTestNames.next()); - if (conformanceTest.isComplete()) { - conformanceTestSet.addConformanceTest(conformanceTest); - logger.debug("Added conformance test " + conformanceTest.getTestName()); - } else { - logger.warn("Incomplete conformance test " + conformanceTest.getTestName()); - } - } - - return conformanceTestSet; - - } - - public Iterator getConformanceTests() { - return this.listConformanceTests.iterator(); - } - - public void addConformanceTest(ConformanceTest conformanceTest) { - this.listConformanceTests.add(conformanceTest); - } - - public void addConformanceTestSet(ConformanceTestSet conformanceTestSet) { - this.listConformanceTests.addAll(conformanceTestSet.getListConformanceTests()); - } - - public static void main(String[] args) { - for (String dir : args) { - try { - ConformanceTestSet conformanceTestSet = ConformanceTestSet.loadDirectory(new File(dir)); - Iterator iterConformanceTests = conformanceTestSet.getConformanceTests(); - if (iterConformanceTests == null) { - System.out.println("No tests found in " + dir); - } else { - System.out.println("Tests found in " + dir); - while (iterConformanceTests.hasNext()) { - System.out.println(iterConformanceTests.next().toString()); - } - } - } catch (Exception ex) { - ex.printStackTrace(System.err); - } - } - } -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ResponseMatchResult.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ResponseMatchResult.java deleted file mode 100644 index f556bcc2e..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ResponseMatchResult.java +++ /dev/null @@ -1,137 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.conformance; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -import com.att.research.xacml.api.Response; -import com.att.research.xacml.api.Result; - -/** - * ResponseMatchResult provides information about how a {@link com.att.research.xacml.api.Response} object matches - * another Response object. - * - * @version $Revision: 1.1 $ - */ -public class ResponseMatchResult { - private List resultMatchResults = new ArrayList<>(); - - private boolean bAssociatedAdviceMatches = true; - private boolean bAttributesMatch = true; - private boolean bDecisionsMatch = true; - private boolean bStatusCodesMatch = true; - private boolean bObligationsMatch = true; - private boolean bPolicyIdentifiersMatch = true; - private boolean bPolicySetIdentifiersMatch = true; - private boolean bNumResultsMatch = true; - private boolean bUnknownFunction; - - protected void addResultMatchResult(ResultMatchResult resultMatchResult) { - this.resultMatchResults.add(resultMatchResult); - this.bAssociatedAdviceMatches = resultMatchResult.associatedAdviceMatches() && this.bAssociatedAdviceMatches; - this.bAttributesMatch = resultMatchResult.attributesMatch() && this.bAttributesMatch; - this.bDecisionsMatch = resultMatchResult.decisionsMatch() && this.bDecisionsMatch; - this.bStatusCodesMatch = resultMatchResult.statusCodesMatch() && this.bStatusCodesMatch; - this.bObligationsMatch = resultMatchResult.obligationsMatch() && this.bObligationsMatch; - this.bPolicyIdentifiersMatch = resultMatchResult.policyIdentifiersMatch() && this.bPolicyIdentifiersMatch; - this.bPolicySetIdentifiersMatch = resultMatchResult.policySetIdentifiersMatch() && this.bPolicySetIdentifiersMatch; - this.bUnknownFunction = resultMatchResult.unknownFunction() || this.bUnknownFunction; - } - - protected void setNumResultsMatch(boolean b) { - this.bNumResultsMatch = b; - } - - public ResponseMatchResult() { - } - - public static ResponseMatchResult newInstance(Response response1, Response response2) { - ResponseMatchResult responseMatchResult = new ResponseMatchResult(); - - Collection listResultsResponse1 = response1.getResults(); - Collection listResultsResponse2 = response2.getResults(); - if (listResultsResponse1.size() == 1 && listResultsResponse2.size() == 1) { - /* - * Just add a single ResultMatchResult comparing the results in the two responses - */ - responseMatchResult.addResultMatchResult(ResultMatchResult.newInstance(listResultsResponse1.iterator().next(), listResultsResponse2.iterator().next())); - } else { - /* - * Iterate over all of the results in the two responses and match them - */ - Iterator iterResponse1Results = listResultsResponse1.iterator(); - Iterator iterResponse2Results = listResultsResponse2.iterator(); - while ((iterResponse1Results != null && iterResponse1Results.hasNext()) || (iterResponse2Results != null && iterResponse2Results.hasNext())) { - Result result1 = (iterResponse1Results != null && iterResponse1Results.hasNext() ? iterResponse1Results.next() : null); - Result result2 = (iterResponse2Results != null && iterResponse2Results.hasNext() ? iterResponse2Results.next() : null); - if ((result1 == null || result2 == null) && responseMatchResult.numResultsMatch()) { - responseMatchResult.setNumResultsMatch(false); - } - responseMatchResult.addResultMatchResult(ResultMatchResult.newInstance(result1, result2)); - } - } - return responseMatchResult; - } - - public Iterator getResultMatchResults() { - return this.resultMatchResults.iterator(); - } - - public boolean numResultsMatch() { - return this.bNumResultsMatch; - } - - public boolean associatedAdviceMatches() { - return this.bAssociatedAdviceMatches; - } - - public boolean attributesMatch() { - return this.bAttributesMatch; - } - - public boolean decisionsMatch() { - return this.bDecisionsMatch; - } - - public boolean obligationsMatch() { - return this.bObligationsMatch; - } - - public boolean policyIdentifiersMatch() { - return this.bPolicyIdentifiersMatch; - } - - public boolean policySetIdentifiersMatch() { - return this.bPolicySetIdentifiersMatch; - } - - public boolean statusCodesMatch() { - return this.bStatusCodesMatch; - } - - public boolean unknownFunction() { - return this.bUnknownFunction; - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ResultMatchResult.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ResultMatchResult.java deleted file mode 100644 index f612c1a3c..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/conformance/ResultMatchResult.java +++ /dev/null @@ -1,136 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.conformance; - -import com.att.research.xacml.api.Result; -import com.att.research.xacml.std.StdStatusCode; -import com.att.research.xacml.util.ListUtil; - -/** - * ResultMatchResult provides information about how well a {@link com.att.research.xacml.api.Result} object matches - * another Result object. - * - * @version $Revision: 1.1 $ - */ -public class ResultMatchResult { - private boolean bAssociatedAdviceMatches = true; - private boolean bAttributesMatch = true; - private boolean bDecisionsMatch = true; - private boolean bObligationsMatch = true; - private boolean bPolicyIdentifiersMatch = true; - private boolean bPolicySetIdentifiersMatch = true; - private boolean bStatusCodesMatch = true; - private boolean bUnknownFunction = false; - - protected void setAssociatedAdviceMatches(boolean b) { - this.bAssociatedAdviceMatches = b; - } - protected void setAttributesMatch(boolean b) { - this.bAttributesMatch = b; - } - protected void setDecisionsMatch(boolean b) { - this.bDecisionsMatch = b; - } - protected void setObligationsMatch(boolean b) { - this.bObligationsMatch = b; - } - protected void setPolicyIdentifiersMatch(boolean b) { - this.bPolicyIdentifiersMatch = b; - } - protected void setPolicySetIdentifiersMatch(boolean b) { - this.bPolicySetIdentifiersMatch = b; - } - protected void setStatusCodesMatch(boolean b) { - this.bStatusCodesMatch = b; - } - protected void setUnknownFunction(boolean b) { - this.bUnknownFunction = b; - } - - public ResultMatchResult() { - } - - public static ResultMatchResult newInstance(Result result1, Result result2) { - ResultMatchResult resultMatchResult = new ResultMatchResult(); - if (result2 != null && result2.getStatus() != null && - result2.getStatus().getStatusCode().equals(StdStatusCode.STATUS_CODE_PROCESSING_ERROR) && - result2.getStatus().getStatusMessage() != null && - result2.getStatus().getStatusMessage().contains("Unknown Function") - ) { - resultMatchResult.setUnknownFunction(true); - } - if (result1 == null || result2 == null) { - resultMatchResult.setAssociatedAdviceMatches(false); - resultMatchResult.setAttributesMatch(false); - resultMatchResult.setDecisionsMatch(false); - resultMatchResult.setObligationsMatch(false); - resultMatchResult.setPolicyIdentifiersMatch(false); - resultMatchResult.setPolicySetIdentifiersMatch(false); - resultMatchResult.setStatusCodesMatch(false); - } else { - resultMatchResult.setAssociatedAdviceMatches(ListUtil.equalsAllowNulls(result1.getAssociatedAdvice(), result2.getAssociatedAdvice())); - resultMatchResult.setAttributesMatch(ListUtil.equalsAllowNulls(result1.getAttributes(), result2.getAttributes())); - resultMatchResult.setDecisionsMatch(result1.getDecision() == result2.getDecision()); - resultMatchResult.setObligationsMatch(ListUtil.equalsAllowNulls(result1.getObligations(), result2.getObligations())); - resultMatchResult.setPolicyIdentifiersMatch(ListUtil.equalsAllowNulls(result1.getPolicyIdentifiers(), result2.getPolicyIdentifiers())); - resultMatchResult.setPolicySetIdentifiersMatch(ListUtil.equalsAllowNulls(result1.getPolicySetIdentifiers(), result2.getPolicySetIdentifiers())); - if (result1.getStatus() == null || result1.getStatus().getStatusCode() == null || result2.getStatus() == null || result2.getStatus().getStatusCode() == null) { - resultMatchResult.setStatusCodesMatch(false); - } else { - resultMatchResult.setStatusCodesMatch(result1.getStatus().getStatusCode().equals(result2.getStatus().getStatusCode())); - } - } - return resultMatchResult; - } - - public boolean associatedAdviceMatches() { - return this.bAssociatedAdviceMatches; - } - - public boolean attributesMatch() { - return this.bAttributesMatch; - } - - public boolean decisionsMatch() { - return this.bDecisionsMatch; - } - - public boolean obligationsMatch() { - return this.bObligationsMatch; - } - - public boolean policyIdentifiersMatch() { - return this.bPolicyIdentifiersMatch; - } - - public boolean policySetIdentifiersMatch() { - return this.bPolicySetIdentifiersMatch; - } - - public boolean statusCodesMatch() { - return this.bStatusCodesMatch; - } - - public boolean unknownFunction() { - return this.bUnknownFunction; - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/CustomDataTypeFactory.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/CustomDataTypeFactory.java deleted file mode 100644 index 10f77666d..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/CustomDataTypeFactory.java +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.custom; - -import java.util.HashMap; -import java.util.Map; - -import com.att.research.xacml.api.DataType; -import com.att.research.xacml.api.DataTypeFactory; -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.std.datatypes.DataTypes; - -public class CustomDataTypeFactory extends DataTypeFactory { - private static final Map> mapIdentifiersToDataTypes = new HashMap<>(); - private static boolean mapNeedsInit = true; - - public static final DataTypePrivateKey DT_PRIVATEKEY = DataTypePrivateKey.newInstance(); - public static final DataTypePublicKey DT_PUBLICKEY = DataTypePublicKey.newInstance(); - - private static void registerDataType(DataType dataType) { - if (dataType != null && dataType.getId() != null) { - mapIdentifiersToDataTypes.put(dataType.getId(), dataType); - } - } - - private static void initMap() { - if (mapNeedsInit) { - synchronized(mapIdentifiersToDataTypes) { - if (mapNeedsInit) { - registerDataType(DataTypes.DT_ANYURI); - registerDataType(DataTypes.DT_BASE64BINARY); - registerDataType(DataTypes.DT_BOOLEAN); - registerDataType(DataTypes.DT_DATE); - registerDataType(DataTypes.DT_DATETIME); - registerDataType(DataTypes.DT_DAYTIMEDURATION); - registerDataType(DataTypes.DT_DNSNAME); - registerDataType(DataTypes.DT_DOUBLE); - registerDataType(DataTypes.DT_HEXBINARY); - registerDataType(DataTypes.DT_INTEGER); - registerDataType(DataTypes.DT_IPADDRESS); - registerDataType(DataTypes.DT_RFC822NAME); - registerDataType(DataTypes.DT_STRING); - registerDataType(DataTypes.DT_TIME); - registerDataType(DataTypes.DT_X500NAME); - registerDataType(DataTypes.DT_XPATHEXPRESSION); - registerDataType(DataTypes.DT_YEARMONTHDURATION); - // - // These are the custom data types! - // - registerDataType(DT_PRIVATEKEY); - registerDataType(DT_PUBLICKEY); - // - // Done - // - mapNeedsInit = false; - } - } - } - } - - public CustomDataTypeFactory() { - initMap(); - } - - @Override - public DataType getDataType(Identifier dataTypeId) { - return mapIdentifiersToDataTypes.get(dataTypeId); - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/CustomFunctionDefinitionFactory.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/CustomFunctionDefinitionFactory.java deleted file mode 100644 index 80f130906..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/CustomFunctionDefinitionFactory.java +++ /dev/null @@ -1,90 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.custom; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.util.HashMap; -import java.util.Map; - -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacmlatt.pdp.policy.FunctionDefinition; -import com.att.research.xacmlatt.pdp.policy.FunctionDefinitionFactory; -import com.att.research.xacmlatt.pdp.std.StdFunctions; -import com.att.research.xacmlatt.pdp.std.functions.FunctionDefinitionBagOneAndOnly; - -public class CustomFunctionDefinitionFactory extends FunctionDefinitionFactory { - private static Map mapFunctionDefinitions = new HashMap<>(); - private static boolean needMapInit = true; - - public static final Identifier ID_FUNCTION_PRIVATEKEY_ONE_AND_ONLY = new IdentifierImpl("urn:com:att:research:xacml:custom:function:3.0:rsa:privatekey-one-and-only"); - public static final Identifier ID_FUNCTION_PUBLICKEY_ONE_AND_ONLY = new IdentifierImpl("urn:com:att:research:xacml:custom:function:3.0:rsa:publickey-one-and-only"); - - public static final FunctionDefinition FD_PRIVATEKEY_ONE_AND_ONLY = new FunctionDefinitionBagOneAndOnly(ID_FUNCTION_PRIVATEKEY_ONE_AND_ONLY, DataTypePrivateKey.newInstance()); - public static final FunctionDefinition FD_PUBLICKEY_ONE_AND_ONLY = new FunctionDefinitionBagOneAndOnly(ID_FUNCTION_PUBLICKEY_ONE_AND_ONLY, DataTypePublicKey.newInstance()); - - private static void register(FunctionDefinition functionDefinition) { - mapFunctionDefinitions.put(functionDefinition.getId(), functionDefinition); - } - - private static void initMap() { - if (needMapInit) { - synchronized(mapFunctionDefinitions) { - if (needMapInit) { - needMapInit = false; - Field[] declaredFields = StdFunctions.class.getDeclaredFields(); - for (Field field : declaredFields) { - if (Modifier.isStatic(field.getModifiers()) && - field.getName().startsWith(StdFunctions.FD_PREFIX) && - FunctionDefinition.class.isAssignableFrom(field.getType()) && - Modifier.isPublic(field.getModifiers()) - ) { - try { - register((FunctionDefinition)(field.get(null))); - } catch (IllegalAccessException ex) { - - } - } - } - // - // Our custom function - // - register(FunctionDefinitionDecrypt.newInstance()); - register(FD_PRIVATEKEY_ONE_AND_ONLY); - register(FD_PUBLICKEY_ONE_AND_ONLY); - } - } - } - } - - public CustomFunctionDefinitionFactory() { - initMap(); - } - - @Override - public FunctionDefinition getFunctionDefinition(Identifier functionId) { - return mapFunctionDefinitions.get(functionId); - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/DataTypePrivateKey.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/DataTypePrivateKey.java deleted file mode 100644 index b161f9072..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/DataTypePrivateKey.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.custom; - -import java.security.PrivateKey; - -import com.att.research.xacml.api.DataTypeException; -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.datatypes.DataTypeBase; - -public class DataTypePrivateKey extends DataTypeBase { - public static final Identifier DT_PRIVATEKEY = new IdentifierImpl("urn:com:att:research:xacml:custom:3.0:rsa:private"); - private static final DataTypePrivateKey singleInstance = new DataTypePrivateKey(); - - private DataTypePrivateKey() { - super(DT_PRIVATEKEY, PrivateKey.class); - } - - public static DataTypePrivateKey newInstance() { - return singleInstance; - } - - @Override - public PrivateKey convert(Object source) throws DataTypeException { - if (source == null || (source instanceof PrivateKey) ) { - return (PrivateKey) source; - } else if (source instanceof byte[]) { - return (PrivateKey) source; - } else if (source instanceof String) { - return (PrivateKey) (Object) ((String) source).getBytes(); - } - throw new DataTypeException(this, "Failed to convert \"" + source.getClass().getCanonicalName()); - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/DataTypePublicKey.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/DataTypePublicKey.java deleted file mode 100644 index c49caa399..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/DataTypePublicKey.java +++ /dev/null @@ -1,54 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.custom; - -import java.security.PublicKey; - -import com.att.research.xacml.api.DataTypeException; -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.datatypes.DataTypeBase; - -public class DataTypePublicKey extends DataTypeBase { - public static final Identifier DT_PUBLICKEY = new IdentifierImpl("urn:com:att:research:xacml:custom:3.0:rsa:public"); - private static final DataTypePublicKey singleInstance = new DataTypePublicKey(); - - public DataTypePublicKey() { - super(DT_PUBLICKEY, PublicKey.class); - } - - public static DataTypePublicKey newInstance() { - return singleInstance; - } - - @Override - public PublicKey convert(Object source) throws DataTypeException { - if (source == null || (source instanceof PublicKey) ) { - return (PublicKey) source; - } else if (source instanceof byte[]) { - return (PublicKey) source; - } else if (source instanceof String) { - return (PublicKey) (Object) ((String) source).getBytes(); - } - throw new DataTypeException(this, "Failed to convert \"" + source.getClass().getCanonicalName()); - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/FunctionDefinitionDecrypt.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/FunctionDefinitionDecrypt.java deleted file mode 100644 index ec7aff3b9..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/FunctionDefinitionDecrypt.java +++ /dev/null @@ -1,162 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.custom; - -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.util.List; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; - -import com.att.research.xacml.api.DataType; -import com.att.research.xacml.api.DataTypeException; -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.StdStatus; -import com.att.research.xacml.std.StdStatusCode; -import com.att.research.xacml.std.datatypes.DataTypeHexBinary; -import com.att.research.xacml.std.datatypes.DataTypeString; -import com.att.research.xacml.std.datatypes.HexBinary; -import com.att.research.xacmlatt.pdp.eval.EvaluationContext; -import com.att.research.xacmlatt.pdp.policy.ExpressionResult; -import com.att.research.xacmlatt.pdp.policy.FunctionArgument; -import com.att.research.xacmlatt.pdp.policy.FunctionDefinition; -import com.att.research.xacmlatt.pdp.std.functions.ConvertedArgument; - -public class FunctionDefinitionDecrypt implements FunctionDefinition { - public static final Identifier FD_RSA_DECRYPT = new IdentifierImpl("urn:com:att:research:xacml:custom:function:3.0:rsa:decrypt"); - private static final FunctionDefinitionDecrypt singleInstance = new FunctionDefinitionDecrypt(); - - public static FunctionDefinitionDecrypt newInstance() { - return singleInstance; - } - - @Override - public Identifier getId() { - return FD_RSA_DECRYPT; - } - - @Override - public Identifier getDataTypeId() { - return XACML3.ID_DATATYPE_STRING; - } - - @Override - public boolean returnsBag() { - return false; - } - - @Override - public ExpressionResult evaluate(EvaluationContext evaluationContext, List arguments) { - if (arguments == null || arguments.size() < 2) { - return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, expecting 2 arguments.")); - } - // - // What is the first argument? - // - FunctionArgument arg0 = arguments.get(0); - if (arg0.isBag()) { - // - // We don't support bags right now - // - return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, not expecting a bag for argument 0.")); - } - if (arg0.getValue().getDataTypeId().equals(XACML3.ID_DATATYPE_HEXBINARY) == false) { - // - // Should be a String - // - return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, expected a Hex Binary for argument 0.")); - } - // - // Convert the argument - // - ConvertedArgument data = new ConvertedArgument(arg0, DataTypeHexBinary.newInstance(), false); - if (! data.isOk()) { - return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, argument 0 failed to convert to Hex Binary.")); - } - // - // Ok - check the 2nd argument - // - FunctionArgument arg1 = arguments.get(1); - if (arg1.isBag()) { - // - // We don't support bags right now - // - return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, not expecting a bag for argument 1.")); - } - if (arg1.getValue().getDataTypeId().equals(DataTypePrivateKey.DT_PRIVATEKEY) || - arg1.getValue().getDataTypeId().equals(DataTypePublicKey.DT_PUBLICKEY)) { - // - // Ok - let's try to decrypt - // - Cipher cipher; - try { - cipher = Cipher.getInstance("RSA"); - if (arg1.getValue().getDataTypeId().equals(DataTypePrivateKey.DT_PRIVATEKEY)) { - // - // Using the private key - // - DataType pkDatatype = DataTypePrivateKey.newInstance(); - ConvertedArgument privateKey = new ConvertedArgument(arg1, pkDatatype, false); - if ( ! privateKey.isOk()) { - return ExpressionResult.newError(new StdStatus(privateKey.getStatus().getStatusCode(), "Decrypt: " + privateKey.getStatus().getStatusMessage())); - } - // - // Setup decryption - // - cipher.init(Cipher.DECRYPT_MODE, privateKey.getValue()); - } else if (arg1.getValue().getDataTypeId().equals(DataTypePublicKey.DT_PUBLICKEY)) { - // - // Using the private key - // - DataType pkDatatype = DataTypePublicKey.newInstance(); - ConvertedArgument publicKey = new ConvertedArgument(arg1, pkDatatype, false); - if ( ! publicKey.isOk()) { - return ExpressionResult.newError(new StdStatus(publicKey.getStatus().getStatusCode(), "Decrypt: " + publicKey.getStatus().getStatusMessage())); - } - // - // Setup decryption - // - cipher.init(Cipher.DECRYPT_MODE, publicKey.getValue()); - } - // - // Do the decryption - // - byte[] decryptedData = cipher.doFinal(data.getValue().getData()); - String decryptedString = new String(decryptedData); - // - // All good, return the decrypted string - // - return ExpressionResult.newSingle(DataTypeString.newInstance().createAttributeValue(decryptedString)); - } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | DataTypeException e) { - return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed: " + e.getLocalizedMessage())); - } - } - return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, expecting public/private key datatype for argument 1.")); - } - -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/TestBase.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/TestBase.java deleted file mode 100644 index a9b504dfd..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/TestBase.java +++ /dev/null @@ -1,1082 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.custom; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.GnuParser; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.apache.commons.io.IOUtils; -import org.apache.http.entity.ContentType; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.DataType; -import com.att.research.xacml.api.DataTypeException; -import com.att.research.xacml.api.DataTypeFactory; -import com.att.research.xacml.api.Decision; -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.RequestAttributes; -import com.att.research.xacml.api.Response; -import com.att.research.xacml.api.Result; -import com.att.research.xacml.api.pdp.PDPEngine; -import com.att.research.xacml.api.pdp.PDPEngineFactory; -import com.att.research.xacml.api.pdp.PDPException; -import com.att.research.xacml.api.pep.PEPException; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.StdAttributeValue; -import com.att.research.xacml.std.StdMutableAttribute; -import com.att.research.xacml.std.StdMutableRequest; -import com.att.research.xacml.std.StdMutableRequestAttributes; -import com.att.research.xacml.std.dom.DOMRequest; -import com.att.research.xacml.std.dom.DOMResponse; -import com.att.research.xacml.std.dom.DOMStructureException; -import com.att.research.xacml.std.json.JSONRequest; -import com.att.research.xacml.std.json.JSONResponse; -import com.att.research.xacml.std.json.JSONStructureException; -import com.att.research.xacml.util.FactoryException; -import com.att.research.xacml.util.XACMLProperties; -import com.google.common.base.Splitter; -import com.google.common.collect.Lists; - -/** - * This is a base class for setting up a test environment. Using properties files, it contains the - * necessary information for - * 1. defining and providing attributes - * 2. defining and instantiating the PDP engine - * 3. creating PEP requests and calling the PDP engine - * - * - */ -public class TestBase extends SimpleFileVisitor { - private static final Logger logger = FlexLogger.getLogger(TestBase.class); - - public class HelpException extends Exception { - private static final long serialVersionUID = 1L; - - } - - /** - * This private class holds information for properties defined for attribute - * generation. The user can configure the properties file such that attributes - * can be automatically generated and added into each request. - * - * - */ - class Generator { - Path file; - InputStream is; - BufferedReader reader; - List attributes = new ArrayList<>(); - - public Generator(Path path) { - this.file = path; - } - - /** - * read - reads in the next line of data - * - * @return String - a line from the csv containing attribute data - */ - public String read() { - String str = null; - if (is == null) { - try { - is = Files.newInputStream(file); - } catch (IOException e) { - logger.error(e); - return null; - } - } - if (reader == null) { - reader = new BufferedReader(new InputStreamReader(this.is)); - } - try { - str = reader.readLine(); - if (str == null) { - // - // No more strings, close up - // - this.close(); - } - if (logger.isDebugEnabled()) { - logger.debug(str); - } - } catch (IOException e) { - logger.error(e); - } - return str; - } - - public void close() { - if (this.reader != null) { - try { - this.reader.close(); - } catch (IOException idontcare) { - } finally { - this.reader = null; - this.is = null; - } - } - } - - } - - public static final String PROP_GENERATOR = "xacml.attribute.generator"; - - public static final String OPTION_HELP = "help"; - public static final String OPTION_TESTDIR = "dir"; - public static final String OPTION_TESTREST = "rest"; - public static final String OPTION_TESTURL = "url"; - public static final String OPTION_TESTOUTPUT = "output"; - public static final String OPTION_LOOP = "loop"; - public static final String OPTION_TESTNUMBERS = "testNumbers"; - - public static final String DEFAULT_RESTURL = "https://localhost:8080/pdp/"; // Modified for test purpose. Port no. 8443 to 8080 - - public static Options options = new Options(); - static { - options.addOption(new Option(OPTION_HELP, false, "Prints help.")); - options.addOption(new Option(OPTION_TESTDIR, true, "Directory path where all the test properties and data are located.")); - options.addOption(new Option(OPTION_TESTREST, false, "Test against RESTful PDP.")); - options.addOption(new Option(OPTION_TESTURL, true, "URL to the RESTful PDP. Default is " + DEFAULT_RESTURL)); - options.addOption(new Option(OPTION_TESTOUTPUT, true, "Specify a different location for dumping responses.")); - options.addOption(new Option(OPTION_LOOP, true, "Number of times to loop through the tests. Default is 1. A value of -1 runs indefinitely.")); - options.addOption(new Option(OPTION_TESTNUMBERS, true, "Comma-separated list of numbers found in the names of the test files to be run. Numbers must exactly match the file name, e.g. '02'. Used to limit testing to specific set of tests.")); - } - - protected String directory = null; - protected Path output = null; - protected boolean isREST; - protected URL restURL = null; - protected int loop = 1; - protected PDPEngine engine = null; - protected List generators = new ArrayList<>(); - protected static DataTypeFactory dataTypeFactory = null; - - private long permits = 0; - private long denies = 0; - private long notapplicables = 0; - private long indeterminates = 0; - - private long expectedPermits = 0; - private long expectedDenies = 0; - private long expectedNotApplicables = 0; - private long expectedIndeterminates = 0; - - private long generatedpermits = 0; - private long generateddenies = 0; - private long generatednotapplicables = 0; - private long generatedindeterminates = 0; - - private long responseMatches = 0; - private long responseNotMatches = 0; - - private String[] testNumbersArray = null; - - protected final Pattern pattern = Pattern.compile("Request[.]\\d+[.](Permit|Deny|NA|Indeterminate|Generate|Unknown)\\.(json|xml)"); - - public static boolean isJSON(Path file) { - return file.toString().endsWith(".json"); - } - - public static boolean isXML(Path file) { - return file.toString().endsWith(".xml"); - } - - public TestBase(String[] args) throws ParseException, MalformedURLException, HelpException { - // - // Finish Initialization - // - this.restURL = new URL(DEFAULT_RESTURL); - // - // Parse arguments - // - this.parseCommands(args); - } - - /** - * Parse in the command line arguments that the following parameters: - * - * @param args - command line arguments - * @throws ParseException - * @throws MalformedURLException - * @throws HelpException - */ - protected void parseCommands(String[] args) throws ParseException, MalformedURLException, HelpException { - // - // Parse the command line options - // - CommandLine cl; - cl = new GnuParser().parse(options, args); - // - // Check for what we have - // - if (cl.hasOption(OPTION_HELP)) { - new HelpFormatter().printHelp("Usage: -dir testdirectory OPTIONS", - options); - throw new HelpException(); - } - if (cl.hasOption(OPTION_TESTDIR)) { - this.directory = cl.getOptionValue(OPTION_TESTDIR); - } else { - throw new IllegalArgumentException("You must specify a test directory. -dir path/to/some/where"); - } - if (cl.hasOption(OPTION_TESTREST)) { - this.isREST = true; - } else { - this.isREST = false; - } - if (cl.hasOption(OPTION_TESTURL)) { - this.restURL = new URL(cl.getOptionValue(OPTION_TESTURL)); - } - if (cl.hasOption(OPTION_TESTOUTPUT)) { - this.output = Paths.get(cl.getOptionValue(OPTION_TESTOUTPUT)); - } else { - this.output = Paths.get(this.directory, "results"); - } - if (cl.hasOption(OPTION_LOOP)) { - this.loop = Integer.parseInt(cl.getOptionValue(OPTION_LOOP)); - } - if (cl.hasOption(OPTION_TESTNUMBERS)) { - String testNumberString = cl.getOptionValue(OPTION_TESTNUMBERS); - testNumbersArray = testNumberString.split(","); - // - // reset strings to include dots so they exactly match pattern in file name - // - for (int i = 0; i < testNumbersArray.length; i++) { - testNumbersArray[i] = "." + testNumbersArray[i] + "."; - } - } - } - - /** - * Using the command line options that were parsed, configures our test instance. - * - * @throws FactoryException - */ - protected void configure() throws FactoryException { - // - // Setup the xacml.properties file - // - if (this.directory == null) { - throw new IllegalArgumentException("Must supply a path to a test directory."); - } - Path pathDir = Paths.get(this.directory, "xacml.properties"); - if (Files.notExists(pathDir)) { - throw new IllegalArgumentException(pathDir.toString() + " does not exist."); - } - // - // Set it as the System variable so the XACML factories know where the properties are - // loaded from. - // - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, pathDir.toString()); - // - // Now we can create the data type factory - // - dataTypeFactory = DataTypeFactory.newInstance(); - // - // Load in what generators we are to create - // - String generators = XACMLProperties.getProperty(PROP_GENERATOR); - if (generators != null) { - // - // Parse the generators - // - for (String generator : Splitter.on(',').trimResults().omitEmptyStrings().split(generators)) { - this.configureGenerator(generator); - } - } - // - // If we are embedded, create our engine - // - if (this.isREST == false) { - PDPEngineFactory factory = PDPEngineFactory.newInstance(); - this.engine = factory.newEngine(); - } - // - // Remove all the responses from the results directory - // - this.removeResults(); - } - - /** - * Removes all the Response* files from the results directory. - * - */ - public void removeResults() { - try { - // - // Determine where the results are supposed to be written to - // - Path resultsPath; - if (this.output != null) { - resultsPath = this.output; - } else { - resultsPath = Paths.get(this.directory.toString(), "results"); - } - // - // Walk the files - // - Files.walkFileTree(resultsPath, new SimpleFileVisitor() { - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - if (file.getFileName().toString().startsWith("Response")) { - Files.delete(file); - } - return super.visitFile(file, attrs); - } - }); - } catch (IOException e) { - logger.error("Failed to removeRequests from " + this.directory + " " + e); - } - } - - /** - * Configure's a specific generator instance from the properties file. - * - * @param generator - */ - protected void configureGenerator(String generator) { - String prefix = PROP_GENERATOR + "." + generator; - String file = XACMLProperties.getProperty(prefix + ".file"); - // - // Create a generator object - // - Generator gen = new Generator(Paths.get(this.directory, file)); - this.generators.add(gen); - // - // Grab attributes - // - String attributes = XACMLProperties.getProperty(prefix + ".attributes"); - for (String attribute : Splitter.on(',').trimResults().omitEmptyStrings().split(attributes)) { - String attributePrefix = prefix + ".attributes." + attribute; - // - // Create an attribute value. It is simply a placeholder for the field within - // the CSV that contains the actual attribute value. It mainly holds the data type - // - Identifier datatype = new IdentifierImpl(XACMLProperties.getProperty(attributePrefix + ".datatype")); - Integer field = Integer.parseInt(XACMLProperties.getProperty(attributePrefix + ".field")); - StdAttributeValue value = new StdAttributeValue<>(datatype, field); - // - // Get the rest of the attribute properties - // - Identifier category = new IdentifierImpl(XACMLProperties.getProperty(attributePrefix + ".category")); - Identifier id = new IdentifierImpl(XACMLProperties.getProperty(attributePrefix + ".id")); - String issuer = XACMLProperties.getProperty(attributePrefix + ".issuer"); - boolean include = Boolean.parseBoolean(XACMLProperties.getProperty(attributePrefix + ".include", "false")); - // - // Now we have a skeleton attribute - // - gen.attributes.add(new StdMutableAttribute(category, id, value, issuer, include)); - } - } - - /** - * This runs() the test instance. It first configure's itself and then walks the - * requests directory issue each request to the PDP engine. - * - * @throws IOException - * @throws FactoryException - * - */ - public void run() throws IOException, FactoryException { - // - // Configure ourselves - // - this.configure(); - // - // Loop and run - // - int runs = 1; - do { - long lTimeStart = System.currentTimeMillis(); - logger.info("Run number: " + runs); - // - // Walk the request directory - // - Files.walkFileTree(Paths.get(this.directory.toString(), "requests"), this); - long lTimeEnd = System.currentTimeMillis(); - logger.info("Run elapsed time: " + (lTimeEnd - lTimeStart) + "ms"); - // - // Dump the stats - // - this.dumpStats(); - this.resetStats(); - // - // Increment - // - runs++; - } while ((this.loop == -1 ? true : runs <= this.loop)); - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - // - // Sanity check the file name - // - Matcher matcher = this.pattern.matcher(file.getFileName().toString()); - if (matcher.matches()) { - // - // if user has limited which files to use, check that here - // - if (testNumbersArray != null) { - String fileNameString = file.getFileName().toString(); - boolean found = false; - for (String numberString : testNumbersArray) { - if (fileNameString.contains(numberString)) { - found = true; - break; - } - } - if (found == false) { - // - // this test is not in the list to be run, so skip it - // - return super.visitFile(file, attrs); - } - } - try { - // - // Pull what this request is supposed to be - // - String group = null; - int count = matcher.groupCount(); - if (count >= 1) { - group = matcher.group(count-1); - } - // - // Send it - // - this.sendRequest(file, group); - } catch (Exception e) { - logger.error(e); - logger.error("Exception Occured"+e); - } - } - return super.visitFile(file, attrs); - } - - /** - * When a request file is encountered, this method is called send the request to the PDP engine. It will also dump - * the response object. If the group equals "Generate", then it will loop and send the request with generated attributes - * until that list is empty. - * - * @param file - Request file. Eg. Request-01-Permit.json - * @param group - This is the parsed out string of the request file that defines if it is a Permit/Deny/Generate etc. - * @throws Exception - */ - protected void sendRequest(Path file, String group) throws Exception { - logger.info(file.toString()); - int requestCount = 0; - do { - // - // Generate the request - // - Request request = this.generateRequest(file, group); - // - // Was something generated? - // - if (request == null) { - // - // Get out of the loop - // - logger.info("NULL request generated."); - break; - } - logger.info(request); - // - // Call the PDP - // - Response response = this.callPDP(request); - // - // Process the response - // - this.processResponse(file, request, response, group, requestCount); - // - // Is this a generated request? - // - if (group.equals("Generate")) { - // - // Yes, increment counter and move - // on to the next generated request. - // - requestCount++; - } else { - // - // Nope, exit the loop - // - break; - } - } while (group.equals("Generate")); - } - - /** - * Sends the request object to the PDP engine. Either the embedded engine or the RESTful engine. - * - * @param request - XACML request object - * @return Response - returns the XACML response object - */ - protected Response callPDP(Request request) { - // - // Send it to the PDP - // - Response response = null; - if (this.isREST) { - try { - String jsonString = JSONRequest.toString(request, false); - // - // Call RESTful PDP - // - response = this.callRESTfulPDP(new ByteArrayInputStream(jsonString.getBytes())); - } catch (Exception e) { - logger.error("Error in sending RESTful request: " + e, e); - } - } else { - // - // Embedded call to PDP - // - long lTimeStart = System.currentTimeMillis(); - try { - response = this.engine.decide(request); - } catch (PDPException e) { - logger.error(e); - } - long lTimeEnd = System.currentTimeMillis(); - logger.info("Elapsed Time: " + (lTimeEnd - lTimeStart) + "ms"); - } - return response; - } - - /** - * Reads the request file into a Request object based on its type. - * - * If the request has "Generate" in its filename, then this function will add - * generated attributes into the request. - * - * @param file - Request file. Eg. Request-01-Permit.json - * @param group - This is the parsed out string of the request file that defines if it is a Permit/Deny/Generate etc. - * @return - * @throws JSONStructureException - * @throws DOMStructureException - * @throws PEPException - */ - protected Request generateRequest(Path file, String group) throws JSONStructureException, DOMStructureException, PEPException { - // - // Convert to a XACML Request Object - // - Request request = null; - if (TestBase.isJSON(file)) { - request = JSONRequest.load(file.toFile()); - } else if (TestBase.isXML(file)) { - request = DOMRequest.load(file.toFile()); - } - if (request == null) { - throw new PEPException("Invalid Request File: " + file.toString()); - } - // - // Only if this request has "Generate" - // Request.XX.Generate.[json|xml] - // - if (group.equals("Generate")) { - // - // Add attributes to it - // - request = this.onNextRequest(request); - } - // - // Done - // - return request; - } - - /** - * Called to add in generated attributes into the request. - * - * @param request - * @return - */ - protected Request onNextRequest(Request request) { - // - // If we have no generators, just return - // - if (this.generators.isEmpty()) { - return request; - } - // - // Copy the request attributes - // - List attributes = new ArrayList<>(); - for (RequestAttributes a : request.getRequestAttributes()) { - attributes.add(new StdMutableRequestAttributes(a)); - } - // - // Iterate the generators - // - for (Generator generator : this.generators) { - // - // Read a row in - // - String line = generator.read(); - // - // Was something read? - // - if (line == null) { - // - // No more rows to read, return null - // - return null; - } - // - // Split the line - // - List fields = Lists.newArrayList(Splitter.on(',').trimResults().split(line)); - // - // Now work on the attributes - // - for (StdMutableAttribute attribute : generator.attributes) { - // - // Grab the attribute holder, which holds the datatype and field. There should - // be only ONE object in the collection. - // - AttributeValue value = attribute.getValues().iterator().next(); - Integer field = (Integer) value.getValue(); - // - // Is the field number valid? - // - if (field >= fields.size()) { - logger.error("Not enough fields: " + field + "(" + fields.size() + ")"); - return null; - } - // - // Determine what datatype it is - // - DataType dataTypeExtended = dataTypeFactory.getDataType(value.getDataTypeId()); - if (dataTypeExtended == null) { - logger.error("Failed to determine datatype"); - return null; - } - // - // Create the attribute value - // - try { - AttributeValue attributeValue = dataTypeExtended.createAttributeValue(fields.get(field)); - // - // Create the attribute - // - StdMutableAttribute newAttribute = new StdMutableAttribute(attribute.getCategory(), - attribute.getAttributeId(), - attributeValue, - attribute.getIssuer(), - attribute.getIncludeInResults()); - boolean added = false; - for (StdMutableRequestAttributes a : attributes) { - // - // Does the category exist? - // - if (a.getCategory().equals(attribute.getCategory())) { - // - // Yes - add in the new attribute value - // - a.add(newAttribute); - added = true; - break; - } - } - if (added == false) { - // - // New category - create it and add it in - // - StdMutableRequestAttributes a = new StdMutableRequestAttributes(); - a.setCategory(newAttribute.getCategory()); - a.add(newAttribute); - attributes.add(a); - } - } catch (DataTypeException e) { - logger.error(e); - return null; - } - } - } - // - // Now form our final request - // - StdMutableRequest newRequest = new StdMutableRequest(); - newRequest.setCombinedDecision(request.getCombinedDecision()); - newRequest.setRequestDefaults(request.getRequestDefaults()); - newRequest.setReturnPolicyIdList(request.getReturnPolicyIdList()); - newRequest.setStatus(request.getStatus()); - for (StdMutableRequestAttributes a : attributes) { - newRequest.add(a); - } - return newRequest; - } - - /** - * This makes an HTTP POST call to a running PDP RESTful servlet to get a decision. - * - * @param file - * @return - */ - protected Response callRESTfulPDP(InputStream is) { - Response response = null; - HttpURLConnection connection = null; - try { - - // - // Open up the connection - // - connection = (HttpURLConnection) this.restURL.openConnection(); - connection.setRequestProperty("Content-Type", "application/json"); - // - // Setup our method and headers - // - connection.setRequestMethod("POST"); - 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); - // - // Send the request - // - try (OutputStream os = connection.getOutputStream()) { - IOUtils.copy(is, os); - } - // - // Do the connect - // - connection.connect(); - if (connection.getResponseCode() == 200) { - // - // Read the response - // - ContentType contentType = null; - try { - contentType = ContentType.parse(connection.getContentType()); - - if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { - response = JSONResponse.load(connection.getInputStream()); - } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || - contentType.getMimeType().equalsIgnoreCase("application/xacml+xml") ) { - response = DOMResponse.load(connection.getInputStream()); - } else { - logger.error("unknown content-type: " + contentType); - } - - } catch (Exception e) { - String message = "Parsing Content-Type: " + connection.getContentType() + ", error=" + e.getMessage(); - logger.error(message, e); - } - - } else { - logger.error(connection.getResponseCode() + " " + connection.getResponseMessage()); - } - } catch (Exception e) { - logger.error(e); - } - - return response; - } - - /** - * This processes a response. Saves the response out to disk. If there is a corresponding response file for the request located - * in the "responses" sub-directory, then this method will compare that response file with what the engine returned to see if it - * matched. - * - * @param requestFile - * @param request - * @param response - * @param group - * @param count - * @throws Exception - */ - protected void processResponse(Path requestFile, Request request, Response response, String group, int count) throws Exception { - // - // Construct the output filename - // - Path responseFile = null; - Path resultFile = null; - int num = requestFile.getNameCount(); - if (num < 2) { - logger.error("Too few dir's in request filename."); - throw new Exception("Too few dir's in request filename. Format should be Request.[0-9]+.{Permit|Deny|NA|Indeterminate}.{json|xml}"); - } - String filename = requestFile.getFileName().toString(); - if (group.equals("Generate")) { - // - // Using count variable, construct a filename - // - // i.e. Response.03.Generate.{count}.json - // - filename = "Response" + filename.substring(filename.indexOf('.'), filename.lastIndexOf('.')) + String.format("%03d", count) + filename.substring(filename.lastIndexOf('.')); - } else { - // - // Construct filename - // - filename = "Response" + filename.substring(filename.indexOf('.')); - } - // - // Determine equivalent response file path - // - responseFile = Paths.get(requestFile.subpath(0, num - 2).toString(), "responses"); - if (Files.notExists(responseFile)) { - // - // Create it - // - logger.warn(responseFile.toString() + " does NOT exist, creating..."); - try { - Files.createDirectories(responseFile); - } catch (IOException e) { - logger.error(e); - throw new Exception("Cannot proceed without an output directory."); - } - } - responseFile = Paths.get(responseFile.toString(), filename); - // - // Determine path to write result file - // - if (this.output != null) { - // - // User specified an output path - // - resultFile = this.output; - } else { - // - // Default path - // - resultFile = Paths.get(requestFile.subpath(0, num - 2).toString(), "results"); - } - // - // Check if the path exists - // - if (Files.notExists(resultFile)) { - // - // Create it - // - logger.warn(resultFile.toString() + " does NOT exist, creating..."); - try { - Files.createDirectories(resultFile); - } catch (IOException e) { - logger.error(e); - throw new Exception("Cannot proceed without an output directory."); - } - } - // - // Add the filename to the path - // - resultFile = Paths.get(resultFile.toString(), filename); - // - // Check if there is an equivalent response in the response - // directory. If so, compare our response result with that one. - // - boolean succeeded = true; - if (responseFile != null && Files.exists(responseFile)) { - // - // Do comparison - // - Response expectedResponse = null; - if (TestBase.isJSON(responseFile)) { - expectedResponse = JSONResponse.load(responseFile); - } else if (TestBase.isXML(responseFile)) { - expectedResponse = DOMResponse.load(responseFile); - } - if (expectedResponse != null) { - // - // Do the compare - // - if (response == null) { - logger.error("NULL response returned."); - this.responseNotMatches++; - succeeded = false; - } else { - if (response.equals(expectedResponse)) { - logger.info("Response matches expected response."); - this.responseMatches++; - } else { - logger.error("Response does not match expected response."); - logger.error("Expected: "); - logger.error(expectedResponse.toString()); - this.responseNotMatches++; - succeeded = false; - } - } - } - } - // - // Write the response to the result file - // - logger.info("Request: " + requestFile.getFileName() + " response is: " + (response == null ? "null" : response.toString())); - if (resultFile != null && response != null) { - if (TestBase.isJSON(resultFile)) { - Files.write(resultFile, JSONResponse.toString(response, true).getBytes()); - } else if (TestBase.isXML(resultFile)) { - Files.write(resultFile, DOMResponse.toString(response, true).getBytes()); - } - } - // - // Stats - // - if (group.equals("Permit")) { - this.expectedPermits++; - } else if (group.equals("Deny")) { - this.expectedDenies++; - } else if (group.equals("NA")) { - this.expectedNotApplicables++; - } else if (group.equals("Indeterminate")) { - this.expectedIndeterminates++; - } - if (response != null) { - for (Result result : response.getResults()) { - Decision decision = result.getDecision(); - if (group.equals("Generate")) { - if (decision.equals(Decision.PERMIT)) { - this.generatedpermits++; - } else if (decision.equals(Decision.DENY)) { - this.generateddenies++; - } else if (decision.equals(Decision.NOTAPPLICABLE)) { - this.generatednotapplicables++; - } else if (decision.equals(Decision.INDETERMINATE)) { - this.generatedindeterminates++; - } - continue; - } - if (decision.equals(Decision.PERMIT)) { - this.permits++; - if (group.equals("Permit") == false) { - succeeded = false; - logger.error("Expected " + group + " got " + decision); - } - } else if (decision.equals(Decision.DENY)) { - this.denies++; - if (group.equals("Deny") == false) { - succeeded = false; - logger.error("Expected " + group + " got " + decision); - } - } else if (decision.equals(Decision.NOTAPPLICABLE)) { - this.notapplicables++; - if (group.equals("NA") == false) { - succeeded = false; - logger.error("Expected " + group + " got " + decision); - } - } else if (decision.equals(Decision.INDETERMINATE)) { - this.indeterminates++; - if (group.equals("Indeterminate") == false) { - succeeded = false; - logger.error("Expected " + group + " got " + decision); - } - } - } - } - if (succeeded) { - logger.info("REQUEST SUCCEEDED"); - } else { - logger.info("REQUEST FAILED"); - } - } - - protected void dumpStats() { - StringBuilder dump = new StringBuilder(); - dump.append(System.lineSeparator()); - dump.append("Permits: " + this.permits + " Expected: " + this.expectedPermits); - dump.append(System.lineSeparator()); - dump.append("Denies: " + this.denies + " Expected: " + this.expectedDenies); - dump.append(System.lineSeparator()); - dump.append("NA: " + this.notapplicables + " Expected: " + this.expectedNotApplicables); - dump.append(System.lineSeparator()); - dump.append("Indeterminates: " + this.indeterminates + " Expected: " + this.expectedIndeterminates); - dump.append(System.lineSeparator()); - dump.append("Generated Permits: " + this.generatedpermits); - dump.append(System.lineSeparator()); - dump.append("Generated Denies: " + this.generateddenies); - dump.append(System.lineSeparator()); - dump.append("Generated NA: " + this.generatednotapplicables); - dump.append(System.lineSeparator()); - dump.append("Generated Indeterminates: " + this.generatedindeterminates); - dump.append(System.lineSeparator()); - dump.append("Responses Matched: " + this.responseMatches); - dump.append(System.lineSeparator()); - dump.append("Responses NOT Matched: " + this.responseNotMatches); - - if (this.permits != this.expectedPermits || - this.denies != this.expectedDenies || - this.notapplicables != this.expectedNotApplicables || - this.indeterminates != this.expectedIndeterminates || - this.responseNotMatches > 0) { - logger.error(dump.toString()); - } else { - logger.info(dump.toString()); - } - } - - protected void resetStats() { - this.permits = 0; - this.denies = 0; - this.notapplicables = 0; - this.indeterminates = 0; - this.generatedpermits = 0; - this.generateddenies = 0; - this.generatednotapplicables = 0; - this.generatedindeterminates = 0; - this.responseMatches = 0; - this.responseNotMatches = 0; - } - - public static void main(String[] args) { - try { - new TestBase(args).run(); - } catch (ParseException | IOException | FactoryException e) { - logger.error(e); - } catch (HelpException e) { - } - } -} diff --git a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/TestCustom.java b/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/TestCustom.java deleted file mode 100644 index 84d8226be..000000000 --- a/ECOMP-PDP/src/test/java/org/openecomp/policy/pdp/test/custom/TestCustom.java +++ /dev/null @@ -1,392 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PDP - * ================================================================================ - * 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.pdp.test.custom; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.net.MalformedURLException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.security.InvalidKeyException; -import java.security.KeyPair; -import java.security.KeyPairGenerator; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.util.ArrayList; -import java.util.List; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.GnuParser; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.ParseException; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.DataType; -import com.att.research.xacml.api.DataTypeException; -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.RequestAttributes; -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.api.pep.PEPException; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.StdMutableAttribute; -import com.att.research.xacml.std.StdMutableRequest; -import com.att.research.xacml.std.StdMutableRequestAttributes; -import com.att.research.xacml.std.dom.DOMStructureException; -import com.att.research.xacml.std.json.JSONStructureException; -import com.att.research.xacml.util.FactoryException; - -/** - * TestCustom is an application that tests the extensibility and configurability of the AT&T XACML API. - * - * It creates a custom datatype definition factory that adds in custom data types for RSA - * PublicKey and PrivateKey. - * - * It creates a custom function definition factory that adds in custom decryption function for decrypting data. It - * also derives and loads custom functions for the RSA public/private key datatypes for the bag function: one-and-only. - * - * - */ -public class TestCustom extends TestBase { - private static final Logger logger = FlexLogger.getLogger(TestCustom.class); - - // - // Our public's - // - public static final String ALGORITHM = "RSA"; - public static final String PRIVATEKEY_FILE = "PrivateKey.key"; - public static final String PUBLICKEY_FILE = "PublicKey.key"; - - public static final String DECRYPTION_INPUT_STRING = "This is the SECRET value!"; - - public static final String DECRYPTION_INPUT_ID = "com:att:research:xacml:test:custom:encrypted-data"; - // - // Our keys - // - protected PublicKey publicKey = null; - protected PrivateKey privateKey = null; - // - // Our command line parameters - // - public static final String OPTION_GENERATE = "generate"; - - static { - options.addOption(new Option(OPTION_GENERATE, false, "Generate a private/public key pair.")); - } - - /** - * This function generates the public/private key pair. Should never have to call this again, this was - * called once to generate the keys. They were saved into the testsets/custom/datatype-function sub-directory. - */ - public void generateKeyPair() { - // - // Generate a RSA private/public key pair - // - KeyPairGenerator keyGen; - try { - keyGen = KeyPairGenerator.getInstance(ALGORITHM); - } catch (NoSuchAlgorithmException e) { - logger.error("failed to generate keypair: " + e); - return; - } - keyGen.initialize(1024); - final KeyPair key = keyGen.generateKeyPair(); - // - // Save the keys to disk - // - Path file = Paths.get(this.directory, PRIVATEKEY_FILE); - try (ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(file))) { - os.writeObject(key.getPrivate()); - } catch (IOException e) { - logger.error("Exception Occured"+e); - } - file = Paths.get(this.directory, PUBLICKEY_FILE); - try (ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(file))) { - os.writeObject(key.getPublic()); - } catch (IOException e) { - logger.error("Exception Occured"+e); - } - } - - public TestCustom(String[] args) throws ParseException, MalformedURLException, HelpException { - super(args); - } - - /* (non-Javadoc) - * - * Simply look for command line option: -generate - * This generates the public/private key. Shouldn't need to call it again, the keys have - * already been generated and saved. - * - * @see org.openecomp.policy.pdp.test.TestBase#parseCommands(java.lang.String[]) - */ - @Override - protected void parseCommands(String[] args) throws ParseException, MalformedURLException, HelpException { - // - // Have our parent class parse its options out - // - super.parseCommands(args); - // - // Parse the command line options - // - CommandLine cl; - cl = new GnuParser().parse(options, args); - if (cl.hasOption(OPTION_GENERATE)) { - // - // Really only need to do this once to setup the test. - // - this.generateKeyPair(); - } - } - - /* (non-Javadoc) - * - * After our parent class configure's itself, all this needs to do is read in - * the public/private key's into objects. - * - * @see org.openecomp.policy.pdp.test.TestBase#configure() - */ - @Override - protected void configure() throws FactoryException { - // - // Have our super do its thing - // - super.configure(); - // - // Read in the public key - // - try { - this.publicKey = (PublicKey) new ObjectInputStream(Files.newInputStream(Paths.get(this.directory, PUBLICKEY_FILE))).readObject(); - } catch (ClassNotFoundException | IOException e) { - logger.error(e); - } - // - // Read in the private key - // - try { - this.privateKey = (PrivateKey) new ObjectInputStream(Files.newInputStream(Paths.get(this.directory, PRIVATEKEY_FILE))).readObject(); - } catch (ClassNotFoundException | IOException e) { - logger.error(e); - } - } - - /* (non-Javadoc) - * - * Here we add 2 attributes into the request: 1) the private key, and 2) a String that was encrypted using the public key. - * - * The goal is to have the custom decrypt function use the private key to decrypt that string. - * - * @see org.openecomp.policy.pdp.test.TestBase#generateRequest(java.nio.file.Path, java.lang.String) - */ - @Override - protected Request generateRequest(Path file, String group) throws JSONStructureException, DOMStructureException, PEPException { - // - // Have our super class do its work - // - Request oldRequest = super.generateRequest(file, group); - // - // Copy the request attributes - // - List attributes = new ArrayList<>(); - for (RequestAttributes a : oldRequest.getRequestAttributes()) { - attributes.add(new StdMutableRequestAttributes(a)); - } - // - // We are supplying the private key as an attribute for the decryption function to use: - // - // (NOTE: Ideally this would be provided by a custom PIP provider, not the PEP) - // - // ID=com:att:research:xacml:test:custom:privatekey - // Issuer=com:att:research:xacml:test:custom - // Category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject - // Datatype=urn:com:att:research:xacml:custom:3.0:rsa:private - // - DataType dtExtended = dataTypeFactory.getDataType(DataTypePrivateKey.DT_PRIVATEKEY); - if (dtExtended == null) { - logger.error("Failed to get private key datatype."); - return null; - } - // - // Create the attribute value - // - try { - AttributeValue attributeValue = dtExtended.createAttributeValue(this.privateKey); - // - // Create the attribute - // - StdMutableAttribute newAttribute = new StdMutableAttribute(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT, - new IdentifierImpl("com:att:research:xacml:test:custom:privatekey"), - attributeValue, - "com:att:research:xacml:test:custom", - false); - boolean added = false; - for (StdMutableRequestAttributes a : attributes) { - // - // Does the category exist? - // - if (a.getCategory().equals(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT)) { - // - // Yes - add in the new attribute value - // - a.add(newAttribute); - added = true; - break; - } - } - if (added == false) { - // - // New category - create it and add it in - // - StdMutableRequestAttributes a = new StdMutableRequestAttributes(); - a.setCategory(newAttribute.getCategory()); - a.add(newAttribute); - attributes.add(a); - } - } catch (DataTypeException e) { - logger.error(e); - return null; - } - // - // We are also supplying this attribute which is the secret text encrypted with - // the public key. - // - // ID=com:att:research:xacml:test:custom:encrypted-data - // Issuer= - // Category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject - // Datatype=http://www.w3.org/2001/XMLSchema#hexBinary - // - // Encrypt it - // - byte[] encryptedData = null; - try { - Cipher cipher = Cipher.getInstance(ALGORITHM); - cipher.init(Cipher.ENCRYPT_MODE, this.publicKey); - // - // This is just a hack to test a decryption of the wrong value. - // - if (group.equals("Permit")) { - encryptedData = cipher.doFinal(DECRYPTION_INPUT_STRING.getBytes()); - } else { - encryptedData = cipher.doFinal("This is NOT the secret".getBytes()); - } - } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { - logger.error(e); - return null; - } - // - // Sanity check (for the Permit request) - // - try { - if (group.equals("Permit")) { - Cipher cipher = Cipher.getInstance(ALGORITHM); - cipher.init(Cipher.DECRYPT_MODE, this.privateKey); - byte[] decryptedData = cipher.doFinal(encryptedData); - if (new String(decryptedData).equals(DECRYPTION_INPUT_STRING)) { - logger.info("Sanity check passed: decrypted the encrypted data."); - } else { - logger.error("Sanity check failed to decrypt the encrypted data."); - return null; - } - } - } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { - logger.error(e); - } - // - // Get our datatype factory - // - dtExtended = dataTypeFactory.getDataType(XACML3.ID_DATATYPE_HEXBINARY); - if (dtExtended == null) { - logger.error("Failed to get hex binary datatype."); - return null; - } - // - // Create the attribute value - // - try { - AttributeValue attributeValue = dtExtended.createAttributeValue(encryptedData); - // - // Create the attribute - // - StdMutableAttribute newAttribute = new StdMutableAttribute(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT, - new IdentifierImpl("com:att:research:xacml:test:custom:encrypted-data"), - attributeValue, - null, - false); - boolean added = false; - for (StdMutableRequestAttributes a : attributes) { - // - // Does the category exist? - // - if (a.getCategory().equals(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT)) { - // - // Yes - add in the new attribute value - // - a.add(newAttribute); - added = true; - break; - } - } - if (added == false) { - // - // New category - create it and add it in - // - StdMutableRequestAttributes a = new StdMutableRequestAttributes(); - a.setCategory(newAttribute.getCategory()); - a.add(newAttribute); - attributes.add(a); - } - } catch (DataTypeException e) { - logger.error(e); - return null; - } - // - // Now form our final request - // - StdMutableRequest newRequest = new StdMutableRequest(); - newRequest.setCombinedDecision(oldRequest.getCombinedDecision()); - newRequest.setRequestDefaults(oldRequest.getRequestDefaults()); - newRequest.setReturnPolicyIdList(oldRequest.getReturnPolicyIdList()); - newRequest.setStatus(oldRequest.getStatus()); - for (StdMutableRequestAttributes a : attributes) { - newRequest.add(a); - } - return newRequest; - } - - public static void main(String[] args) { - try { - new TestCustom(args).run(); - } catch (ParseException | IOException | FactoryException e) { - logger.error(e); - } catch (HelpException e) { - } - } - -} diff --git a/ECOMP-PDP/src/test/resources/CSVPolicy.xml b/ECOMP-PDP/src/test/resources/CSVPolicy.xml deleted file mode 100644 index 7175fb500..000000000 --- a/ECOMP-PDP/src/test/resources/CSVPolicy.xml +++ /dev/null @@ -1,205 +0,0 @@ - - - - - This Policy handles the Take action and Advice action operations. - - - - - Check the CPU Utilization or Network Load - - Load - - - - 95 - - - - CPU - - - - 95 - - - - - - Permit to create a new VM with Obligation - - - - - If the Requirement has met create the VM - - true - - - - - - Action_Info - - - - - Create_NEW_VM - - - - - - Permit to create a new VM with Advice - - - - - create_adviceAction - - - - - - - - If the Requirement has met create the VM - - true - - - - - - Action_Info - - - - - Created New VM - - - http://localhost:8080/pdp/?type=hb - - - - - - - - - - - - - - - - Permit to remove a VM with Obligation - - - - - remove_Action - - - - - - - - If the resource usage is low then remove the VM - - true - - - - - - Action_Info - - - - - Remove_VM - - - - - - Permit to remove a VM with Advice - - - - - remove_adviceAction - - - - - - - - If the resource usage is low then remove the VM - - true - - - - - - Action_Info - - - - - Removed VM - - - http://localhost:8080/pdp/?type=hb - - - - - diff --git a/ECOMP-PDP/src/test/resources/log4j.properties b/ECOMP-PDP/src/test/resources/log4j.properties deleted file mode 100644 index d3d3f48b6..000000000 --- a/ECOMP-PDP/src/test/resources/log4j.properties +++ /dev/null @@ -1,42 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP -# ================================================================================ -# 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========================================================= -### - -# -# Use this properties for debugging and development. -# -# -# Set root logger level to DEBUG and its only appender to A1. -log4j.rootLogger=INFO, MAIN_LOG - -# A1 is set to be a ConsoleAppender. -log4j.appender.MAIN_LOG=org.apache.log4j.ConsoleAppender - -# A1 uses PatternLayout. -log4j.appender.MAIN_LOG.layout=org.apache.log4j.PatternLayout -log4j.appender.MAIN_LOG.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n - -# -# This is specifically for Xacml request/response logging -# -log4j.logger.xacml.request=INFO, REQUEST_LOG - -log4j.appender.REQUEST_LOG=org.apache.log4j.ConsoleAppender -log4j.appender.REQUEST_LOG.layout=org.apache.log4j.PatternLayout -log4j.appender.REQUEST_LOG.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} %m%n diff --git a/ECOMP-PDP/src/test/resources/logback.xml b/ECOMP-PDP/src/test/resources/logback.xml deleted file mode 100644 index ea027dcbb..000000000 --- a/ECOMP-PDP/src/test/resources/logback.xml +++ /dev/null @@ -1,253 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --> - - - - - - - - - - - - - - - - - - - - ${defaultPattern} - - - - - - - - - - - - - ${logDirectory}/${auditLogName}.log - - ${logDirectory}/${auditLogName}.%i.log.zip - - 1 - 9 - - - 5MB - - - ${defaultAuditPattern} - - - - - 256 - - - - - - - - ${logDirectory}/${metricsLogName}.log - - ${logDirectory}/${metricsLogName}.%i.log.zip - - 1 - 9 - - - 5MB - - - - ${defaultMetricPattern} - - - - - 256 - - - - - - - - ${logDirectory}/${errorLogName}.log - - ${logDirectory}/${errorLogName}.%i.log.zip - - 1 - 9 - - - ERROR - - - 5MB - - - ${defaultErrorPattern} - - - - - 256 - - - - - - - ${debugLogDirectory}/${debugLogName}.log - - ${debugLogDirectory}/${debugLogName}.%i.log.zip - - 1 - 9 - - - DEBUG - - - 5MB - - - ${debugLoggerPattern} - - - - - 256 - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ECOMP-PDP/src/test/resources/logging.properties b/ECOMP-PDP/src/test/resources/logging.properties deleted file mode 100644 index cd4ad799f..000000000 --- a/ECOMP-PDP/src/test/resources/logging.properties +++ /dev/null @@ -1,32 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP -# ================================================================================ -# 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========================================================= -### - -handlers = java.util.logging.ConsoleHandler, java.util.logging.FileHandler - -.level = FINE - -java.util.logging.SimpleFormatter.format=%4$s: %5$s %n - -java.util.logging.ConsoleHandler.level = FINEST -java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter - -java.util.logging.FileHandler.level = SEVERE -java.util.logging.FileHandler.pattern=%h/xacml_log%u.log -java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter diff --git a/ECOMP-PDP/src/test/resources/xacml.pip.properties b/ECOMP-PDP/src/test/resources/xacml.pip.properties deleted file mode 100644 index 739504faf..000000000 --- a/ECOMP-PDP/src/test/resources/xacml.pip.properties +++ /dev/null @@ -1,23 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP -# ================================================================================ -# 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========================================================= -### - -# -#Fri Mar 06 12:06:30 EST 2015 -xacml.pip.engines= diff --git a/ECOMP-PDP/src/test/resources/xacml.policy.properties b/ECOMP-PDP/src/test/resources/xacml.policy.properties deleted file mode 100644 index 889a63ad3..000000000 --- a/ECOMP-PDP/src/test/resources/xacml.policy.properties +++ /dev/null @@ -1,25 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP -# ================================================================================ -# 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========================================================= -### - -# -#Fri Mar 06 12:06:30 EST 2015 -xacml.referencedPolicies= -xacml.rootPolicies= - diff --git a/ECOMP-PDP/testclient.properties b/ECOMP-PDP/testclient.properties deleted file mode 100644 index 8e16d2397..000000000 --- a/ECOMP-PDP/testclient.properties +++ /dev/null @@ -1,21 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP -# ================================================================================ -# 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========================================================= -### - -test=test,MASTER diff --git a/ECOMP-PDP/testpdp.properties b/ECOMP-PDP/testpdp.properties deleted file mode 100644 index 6ae5501d3..000000000 --- a/ECOMP-PDP/testpdp.properties +++ /dev/null @@ -1,21 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP -# ================================================================================ -# 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========================================================= -### - -PDP_URL= , test, test diff --git a/ECOMP-PDP/xacml.pap.properties b/ECOMP-PDP/xacml.pap.properties deleted file mode 100644 index 13aef044f..000000000 --- a/ECOMP-PDP/xacml.pap.properties +++ /dev/null @@ -1,107 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP -# ================================================================================ -# 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========================================================= -### - -# -# This is our factory that will create our engine -# -xacml.PAP.papEngineFactory=org.openecomp.policy.xacml.std.pap.StdEngineFactory - -# -# Where we store our PAP PDP Group/Node information -# -xacml.pap.pdps=pdps -# -# Need the PAP's url (how PDPs will reach it) configured here -# because we need it to generate the URLs of the Policy Files -# sent to the PDPs in the configuration when the PAP is first brought up. -# (In other cases, such as the PDP calling the PAP, we could generate this URL, -# but for startup there is no other way to get it.) -# -# - -xacml.rest.pap.url=http://localhost:8070/pap/ - -# -# Upon startup, have the PAP servlet send latest configuration information to all -# the PDP nodes it knows about. -# -xacml.rest.pap.initiate.pdp=true -# -# Heartbeat from PAP to PDPs -# -# How much time (in milliseconds) between heartbeats -# (i.e. the time between completing the heartbeat with all PDPs and starting the next cycle) -# -xacml.rest.pap.heartbeat.interval=10000 -# -# Heartbeat connection timeout (in milliseconds) -# -xacml.rest.pap.heartbeat.timeout=10000 - -################################################################################################ -# Adding properties for getting properties previously used by PAP-ADMIN for creating Policies -# THis is part of the Policy Creation API project -################################################################################################ - -# Set your domain here: -xacml.rest.pap.domain=com - -# Location where all the user workspaces are located. -xacml.rest.pap.workspace=workspace - -# Location where the GIT repository is located -xacml.rest.pap.repository=repository - -# new Property Please mention your PAP-REST webapps Location here. -xacml.rest.config.webapps=C:\\Second Tomcat\\apache-tomcat-8.0.23\\webapps\\ConfigPAP\\ - -#Turn the audit on to synchronize the DB/file system -#xacml.rest.pap.run.audit.flag=true -#Turn the audit off to not synchronize the DB/file system -#xacml.rest.pap.run.audit.flag=false -xacml.rest.pap.run.audit.flag=false - -#Audit will synchronize the file system to match the contents of the DB -#xacml.rest.pap.filesystem.audit=true -#Audit will synchronize the DB to match the contents of the file system -#xacml.rest.pap.filesystem.audit=false -xacml.rest.pap.filesystem.audit=false - -# id -xacml.rest.pap.userid=testpap -# pass -xacml.rest.pap.password=alpha123 -# pdps file -xacml.rest.pdp.idfile=test.properties - -#Properties for db access -javax.persistence.jdbc.driver=org.h2.Driver -javax.persistence.jdbc.url=jdbc:h2:file:./sql/xacmlTest -javax.persistence.jdbc.user=sa -javax.persistence.jdbc.password= - -#Time in ms which a Policy DB transaction will wait to get the transaction lock object -xacml.rest.pap.transaction.waitms=1000 - -#Policy DB transaction timeout in ms after it has obtained the transaction lock object -xacml.rest.pap.transaction.timeoutms=500 - -#Policy Audit timeout in ms after it has obtained the transaction lock object -xacml.rest.pap.audit.timeoutms=5000 diff --git a/ECOMP-PDP/xacml.pdp.properties b/ECOMP-PDP/xacml.pdp.properties deleted file mode 100644 index ba5358d0b..000000000 --- a/ECOMP-PDP/xacml.pdp.properties +++ /dev/null @@ -1,86 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP -# ================================================================================ -# 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========================================================= -### - -# Default XACML Properties File for PDP RESTful servlet -# -# Standard API Factories -# -xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory -xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory -xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory -# NOT USED SEE BELOW xacml.pipFinderFactory=com.att.research.xacml.std.pip.StdPIPFinderFactory -xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory -# -# AT&T PDP Implementation Factories -# -xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory -xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory -xacml.att.functionDefinitionFactory=org.openecomp.policy.xacml.custom.EcompFunctionDefinitionFactory -# NOT USED SEE BELOW xacml.att.policyFinderFactory=org.openecomp.policy.pdp.std.StdPolicyFinderFactory - -# -# AT&T RESTful PDP Implementation Factories -# -xacml.pipFinderFactory=org.openecomp.policy.rest.impl.XACMLPdpPIPFinderFactory -xacml.att.policyFinderFactory=org.openecomp.policy.rest.XACMLPdpPolicyFinderFactory -# -# When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into -# into one PolicySet and use the given Policy Algorithm. -# -xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-deny-overrides -# -# PDP RESTful API properties -# -# Set this to the address where the XACML-PAP-REST servlet is running -# http://localhost:9090/pap/ -xacml.rest.pap.url=http://localhost:8070/pap/ -# -# Give the running PDP an ID for the PAP. The url that its running as is a good choice. -# The PAP identifies PDP's using the URL of the PDP. -# -xacml.rest.pdp.id=http://localhost:8082/pdp/ -# -# Set the directory where the PDP holds its Policy Cache and PIP Configuration -# -xacml.rest.pdp.config=config_testing - -xacml.rest.pdp.webapps=/webapps - -xacml.rest.pdp.configparams=../webapps/configparams -# -# Initialize register with PAP servlet -# -xacml.rest.pdp.register=true -# -# Sleep period in seconds between register attempts -# -xacml.rest.pdp.register.sleep=15 -# -# number of attempts to register. -1 means keep trying forever. -# -xacml.rest.pdp.register.retries=-1 -# -# max number of bytes in a POST of a XML/JSON request -# -xacml.rest.pdp.maxcontent=32767 -# -# testClient file -# -xacml.rest.pep.idfile = testclient.properties diff --git a/ECOMP-PDP/xacml.properties b/ECOMP-PDP/xacml.properties deleted file mode 100644 index 22e8ee093..000000000 --- a/ECOMP-PDP/xacml.properties +++ /dev/null @@ -1,46 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-PDP -# ================================================================================ -# 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========================================================= -### - -# Default XACML Properties File -# Standard API Factories -# -xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory -xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory -xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory -xacml.pipFinderFactory=com.att.research.xacml.std.pip.StdPIPFinderFactory - -# If there is a standard set of PIPEngines: -# xacml.pip.engines=engine1,engine2,...,engineN -# engine1.classname=com.att.research.xacmlpip.OraclePIP -# engine1.prop1=foo -# engine1.prop2=bar -# ... -# engine2.classname=com.att.research.xacmlpip.ActiveDirectoryPIP -# ... - -# AT&T PDP Implementation Factories -# -xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory -xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory -xacml.att.functionDefinitionFactory=com.att.research.xacmlatt.pdp.std.StdFunctionDefinitionFactory -xacml.att.policyFinderFactory=com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory - -# If there is a standard policy for the engine: -# xacml.att.stdPolicyFinderFactory.rootPolicyFile=/etc/stdpolicyset.xml diff --git a/ECOMP-REST/policyLogger.properties b/ECOMP-REST/policyLogger.properties deleted file mode 100644 index 2cd1c4bef..000000000 --- a/ECOMP-REST/policyLogger.properties +++ /dev/null @@ -1,44 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-REST -# ================================================================================ -# 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========================================================= -### - -################################### Set concurrentHashMap and timer info ####################### -#Timer initial delay and the delay between in milliseconds before task is to be execute. -timer.delay.time=1000 -#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. -check.interval= 30000 -#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. -event.expired.time=86400 -#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed -#to remove all expired records from this concurrentHashMap. -concurrentHashMap.limit=5000 -#Size of the concurrentHashMap - when its size drops to this point, stop the Timer -stop.check.point=2500 -################################### Set logging format ############################################# -# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println -logger.type=EELF -#################################### Set level for EELF or SYSTEMOUT logging ################################## -# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all -debugLogger.level=INFO -# Set level for metrics file. Set OFF to disable; set ON to enable -metricsLogger.level=ON -# Set level for error file. Set OFF to disable; set ON to enable -error.level=ON -# Set level for audit file. Set OFF to disable; set ON to enable -audit.level=ON diff --git a/ECOMP-REST/pom.xml b/ECOMP-REST/pom.xml deleted file mode 100644 index 77f60f0a8..000000000 --- a/ECOMP-REST/pom.xml +++ /dev/null @@ -1,114 +0,0 @@ - - - - - - 4.0.0 - - - org.openecomp.policy.engine - PolicyEngineSuite - 1.1.0-SNAPSHOT - - - ECOMP-REST - - ECOMP REST - - jar - - - - org.openecomp.policy.engine - ${project.version} - ECOMP-XACML - - - javax.servlet - javax.servlet-api - 3.1.0 - - - commons-logging - commons-logging - 1.1.3 - - - javax.servlet - servlet-api - - - - - com.google.guava - guava - 14.0.1 - - - com.google.code.gson - gson - 2.8.0 - - - junit - junit - 4.11 - test - - - org.mockito - mockito-core - 1.9.5 - - - org.springframework - spring-mock - 2.0.8 - - - com.mockrunner - mockrunner - 0.3.1 - - - org.eclipse.emf - org.eclipse.emf.ecore.xmi - 2.11.0-v20150123-0347 - - - org.eclipse.emf - org.eclipse.emf.ecore - 2.11.0-v20150123-0347 - - - org.eclipse.emf - org.eclipse.emf.common - 2.11.0-v20150123-0347 - - - org.json - json - [20090211,) - - - diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/XACMLRest.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/XACMLRest.java deleted file mode 100644 index 050d03bce..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/XACMLRest.java +++ /dev/null @@ -1,216 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest; - -import java.io.IOException; -import java.util.Enumeration; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import javax.servlet.ServletConfig; -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - -import com.att.research.xacml.util.XACMLProperties; - - -/** - * This static class is used by both the PDP and PAP servlet's. It contains some common - * static functions and objects used by both the servlet's. - * - * - */ -public class XACMLRest { - private static final Log logger = LogFactory.getLog(XACMLRest.class); - private static Properties restProperties = new Properties(); - - /** - * This must be called during servlet initialization. It sets up the xacml.?.properties - * file as a system property. If the System property is already set, then it does not - * do anything. This allows the developer to specify their own xacml.properties file to be - * used. They can 1) modify the default properties that comes with the project, or 2) change - * the WebInitParam annotation, or 3) specify an alternative path in the web.xml, or 4) set - * the Java System property to point to their xacml.properties file. - * - * The recommended way of overriding the default xacml.properties file is using a Java System - * property: - * - * -Dxacml.properties=/opt/app/xacml/etc/xacml.admin.properties - * - * This way one does not change any actual code or files in the project and can leave the - * defaults alone. - * - * @param config - The servlet config file passed from the javax servlet init() function - */ - public static void xacmlInit(ServletConfig config) { - // - // Get the XACML Properties File parameter first - // - String propFile = config.getInitParameter("XACML_PROPERTIES_NAME"); - if (propFile != null) { - // - // Look for system override - // - String xacmlPropertiesName = System.getProperty(XACMLProperties.XACML_PROPERTIES_NAME); - logger.info("\n\n" + xacmlPropertiesName + "\n" + XACMLProperties.XACML_PROPERTIES_NAME); - if (xacmlPropertiesName == null) { - // - // Set it to our servlet default - // - if (logger.isDebugEnabled()) { - logger.debug("Using Servlet Config Property for XACML_PROPERTIES_NAME:" + propFile); - } - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, propFile); - } else { - if (logger.isDebugEnabled()) { - logger.debug("Using System Property for XACML_PROPERTIES_NAME:" + xacmlPropertiesName); - } - } - } - // - // Setup the remaining properties - // - Enumeration params = config.getInitParameterNames(); - while (params.hasMoreElements()) { - String param = params.nextElement(); - if (! param.equals("XACML_PROPERTIES_NAME")) { - String value = config.getInitParameter(param); - //logger.info(param + "=" + config.getInitParameter(param)); - PolicyLogger.info(param + "=" + config.getInitParameter(param)); - restProperties.setProperty(param, value); - } - } - } - - /** - * Reset's the XACMLProperties internal properties object so we start - * in a fresh environment. Then adds back in our Servlet init properties that were - * passed in the javax Servlet init() call. - * - * This function is primarily used when a new configuration is passed in and the - * PDP servlet needs to load a new PDP engine instance. - * - * @param pipProperties - PIP configuration properties - * @param policyProperties - Policy configuration properties - */ - public static void loadXacmlProperties(Properties policyProperties, Properties pipProperties) { - try { - // - // Start fresh - // - XACMLProperties.reloadProperties(); - // - // Now load our init properties - // - XACMLProperties.getProperties().putAll(XACMLRest.restProperties); - // - // Load our policy properties - // - if (policyProperties != null) { - XACMLProperties.getProperties().putAll(policyProperties); - } - // - // Load our pip config properties - // - if (pipProperties != null) { - XACMLProperties.getProperties().putAll(pipProperties); - } - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Failed to put init properties into Xacml properties"); - } - // - // Dump them - // - if (logger.isDebugEnabled()) { - try { - logger.debug(XACMLProperties.getProperties().toString()); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Cannot dump properties"); - } - } - } - - /** - * Helper routine to dump the HTTP servlet request being serviced. Primarily for debugging. - * - * @param request - Servlet request (from a POST/GET/PUT/etc.) - */ - public static void dumpRequest(HttpServletRequest request) { - if (logger.isDebugEnabled()) { - // special-case for receiving heartbeat - don't need to repeatedly output all of the information in multiple lines - if (request.getMethod().equals("GET") && "hb".equals(request.getParameter("type")) ) { - //logger.debug("GET type=hb : heartbeat received"); - PolicyLogger.debug("GET type=hb : heartbeat received"); - return; - } - logger.debug(request.getMethod() + ":" + request.getRemoteAddr() + " " + request.getRemoteHost() + " " + request.getRemotePort()); - logger.debug(request.getLocalAddr() + " " + request.getLocalName() + " " + request.getLocalPort()); - Enumeration en = request.getHeaderNames(); - logger.debug("Headers:"); - while (en.hasMoreElements()) { - String element = en.nextElement(); - Enumeration values = request.getHeaders(element); - while (values.hasMoreElements()) { - String value = values.nextElement(); - logger.debug(element + ":" + value); - } - } - logger.debug("Attributes:"); - en = request.getAttributeNames(); - while (en.hasMoreElements()) { - String element = en.nextElement(); - logger.debug(element + ":" + request.getAttribute(element)); - } - logger.debug("ContextPath: " + request.getContextPath()); - if (request.getMethod().equals("PUT") || request.getMethod().equals("POST")) { - // POST and PUT are allowed to have parameters in the content, but in our usage the parameters are always in the Query string. - // More importantly, there are cases where the POST and PUT content is NOT parameters (e.g. it might contain a Policy file). - // Unfortunately the request.getParameterMap method reads the content to see if there are any parameters, - // and once the content is read it cannot be read again. - // Thus for PUT and POST we must avoid reading the content here so that the main code can read it. - logger.debug("Query String:" + request.getQueryString()); - try { - if (request.getInputStream() == null) { - logger.debug("Content: No content inputStream"); - } else { - logger.debug("Content available: " + request.getInputStream().available()); - } - } catch (Exception e) { - logger.debug("Content: inputStream exception: " + e.getMessage() + "; (May not be relevant)" +e); - } - } else { - logger.debug("Parameters:"); - Map params = request.getParameterMap(); - Set keys = params.keySet(); - for (String key : keys) { - String[] values = params.get(key); - logger.debug(key + "(" + values.length + "): " + (values.length > 0 ? values[0] : "")); - } - } - logger.debug("Request URL:" + request.getRequestURL()); - } - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/XACMLRestProperties.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/XACMLRestProperties.java deleted file mode 100644 index 04472f8fe..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/XACMLRestProperties.java +++ /dev/null @@ -1,456 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest; - -import com.att.research.xacml.util.XACMLProperties; - -/** - * These are XACML Properties that are relevant to the RESTful API interface for - * the PDP, PAP and AC interfaces. - * - * - */ -public class XACMLRestProperties extends XACMLProperties { - /** - * A unique identifier for the PDP servlet instance. Usually set to the URL - * it is running as in the J2EE container. - * - * Eg. http://localhost:8080/pdp/ - */ - public static final String PROP_PDP_ID = "xacml.rest.pdp.id"; - /** - * A PDP servlet's configuration directory. Holds the pip and policy - * configuration data as well as the local policy cache. - * - * Eg: /opt/app/xacml/config - */ - public static final String PROP_PDP_CONFIG = "xacml.rest.pdp.config"; - // Resilience feature- - public static final String PROP_PDP_WEBAPPS = "xacml.rest.pdp.webapps"; - //Closed Loop JSON table - public static final String PROP_ADMIN_CLOSEDLOOP = "xacml.rest.admin.closedLoopJSON"; - /** - * Set this property to true or false if the PDP servlet should register - * itself upon startup with the PAP servlet. - */ - public static final String PROP_PDP_REGISTER = "xacml.rest.pdp.register"; - /** - * Number of seconds the PDP will sleep while retrying registration with the - * PAP. This value must be greater or equal to 5. - */ - public static final String PROP_PDP_REGISTER_SLEEP = "xacml.rest.pdp.register.sleep"; - /** - * Number of retry attempts at registration with the PAP. A value of -1 - * indicates infinite retries. - */ - public static final String PROP_PDP_REGISTER_RETRIES = "xacml.rest.pdp.register.retries"; - /** - * Max content length accepted for an incoming POST XML/JSON request. - * Default is 32767 bytes. - */ - public static final String PROP_PDP_MAX_CONTENT = "xacml.rest.pdp.maxcontent"; - /** - * Custom HTTP header used by PDP to send the value of the PROP_PDP_ID - */ - public static final String PROP_PDP_HTTP_HEADER_ID = "X-XACML-PDP-ID"; - /** - * Custom HHTP header used by PDP to send its heartbeat value. - */ - public static final String PROP_PDP_HTTP_HEADER_HB = "X-XACML-PDP-HB"; - /* - * Custom HTTP header used by PDP to send the value of the - * X-XACML-PDP-JMX-PORT - */ - public static final String PROP_PDP_HTTP_HEADER_JMX_PORT = "X-XACML-PDP-JMX-PORT"; - /** - * The URL of the PAP servlet. Used by PDP servlet's to communicate. Because - * administrators can set whatever context they want to run the PAP servlet, - * it isn't easy to determine a return URL for the PAP servlet. This is - * especially true upon initialization. - */ - public static final String PROP_PAP_URL = "xacml.rest.pap.url"; - /** - * A comma divided list of urls pointing to avaiable PAP urls. - * If one or more fail, the other servers in the list can - * handle the requests. - */ - public static final String PROP_PAP_URLS = "xacml.rest.pap.urls"; - public static final String PROP_PAP_FAILED_URLS = "xacml.rest.pap.failedUrls"; - public static final String PROP_PAP_SUCCEEDED_URLS = "xacml.rest.pap.succeededUrls"; - //public static final String PROP_PAP_FAILED_URL_TIME = "xacml.rest.pap.failedUrlTime"; - - /** - * Upon startup, have the PAP servlet send latest configuration information - * to all the PDP nodes it knows about. - */ - public static final String PROP_PAP_INITIATE_PDP_CONFIG = "xacml.rest.pap.initiate.pdp"; - /** - * The interval the PAP servlet uses to send heartbeat requests to the PDP - * nodes. - */ - public static final String PROP_PAP_HEARTBEAT_INTERVAL = "xacml.rest.pap.heartbeat.interval"; - /** - * Timeout value used by the PAP servlet when trying to check the heartbeat - * of a PDP node. - */ - public static final String PROP_PAP_HEARTBEAT_TIMEOUT = "xacml.rest.pap.heartbeat.timeout"; - /* - * This is the domain you can setup for your organization, it should be a URI. - * Eg. com:sample:foo - */ - public static final String PROP_PAP_DOMAIN = "xacml.rest.pap.domain"; - - /* - * Local path to where user workspaces exist. The user workspace contains temporary files, the - * user's clone of the GIT repository, anything specific to the user, etc. - */ - public static final String PROP_PAP_WORKSPACE = "xacml.rest.pap.workspace"; - - /* - * Local path to where the GIT repository exists. - * - * Eg. /opt/app/xacml/repository - */ - public static final String PROP_PAP_REPOSITORY = "xacml.rest.pap.repository"; - - /* - * Database driver property - */ - public static final String PROP_PAP_DB_DRIVER = "javax.persistence.jdbc.driver"; - - /* - * Database url - */ - public static final String PROP_PAP_DB_URL = "javax.persistence.jdbc.url"; - - /* - * Database user - */ - public static final String PROP_PAP_DB_USER = "javax.persistence.jdbc.user"; - - /* - * Database password - */ - public static final String PROP_PAP_DB_PASSWORD = "javax.persistence.jdbc.password"; - - /* - * Time in ms which a Policy DB transaction will wait to get the transaction lock object - */ - public static final String PROP_PAP_TRANS_WAIT = "xacml.rest.pap.transaction.waitms"; - - /* - * Policy DB transaction timeout in ms after it has obtained the transaction lock object - */ - public static final String PROP_PAP_TRANS_TIMEOUT = "xacml.rest.pap.transaction.timeoutms"; - - /* - * Policy Audit transaction timeout in ms after it has obtained the transaction lock object - */ - public static final String PROP_PAP_AUDIT_TIMEOUT = "xacml.rest.pap.audit.timeoutms"; - - /* - * Value determines direction of audit. Value=true will synch the file system to contents of the DB. - * Value=false will synch the DB to the contents of the file system. - */ - public static final String PROP_PAP_AUDIT_FLAG = "xacml.rest.pap.filesystem.audit"; - - /* - * Value for enable/disable of audit functionality - */ - public static final String PROP_PAP_RUN_AUDIT_FLAG = "xacml.rest.pap.run.audit.flag"; - - /* - * Controls how long the timeout will be when a pap sends a notification to another pap - */ - public static final String PROP_PAP_NOTIFY_TIMEOUT = "xacml.rest.pap.notify.timeoutms"; - /* - * Value for Enable/Disable of AutoPush Flag. - */ - public static final String PROP_PAP_PUSH_FLAG = "xacml.rest.pap.autopush.flag"; - - /* - * Properties file for the AutoPush Functionality. - */ - public static final String PROP_PAP_PUSH_FILE = "xacml.rest.pap.autopush.file"; - - /* - * Local path to where the GIT repository exists. - * - * Eg. /opt/app/xacml/repository - */ - public static final String PROP_ADMIN_REPOSITORY = "xacml.rest.admin.repository"; - /* - * Local path to where user workspaces exist. The user workspace contains - * temporary files, the user's clone of the GIT repository, anything - * specific to the user, etc. - */ - public static final String PROP_ADMIN_WORKSPACE = "xacml.rest.admin.workspace"; - /* - * This is the domain you can setup for your organization, it should be a - * URI. - * - * Eg. com:sample:foo - */ - public static final String PROP_ADMIN_DOMAIN = "xacml.rest.admin.domain"; - /** - * PROP_ADMIN_USER_NAME is simply a name for the logged in user. - * - * AC authentication is out the scope of the web application itself. It is - * up to the developer to setup authentication as they please in the J2EE - * container used to run the web application. Whatever authentication - * mechanism they use, they should then set the attribute into the - * HttpSession object. The Admin Console will be able to read that value - * (default to "guest") in. - * - * ((HttpServletRequest) - * request).getSession().setAttribute("xacml.rest.admin.user.name", - * "Homer"); - * - */ - public static final String PROP_ADMIN_USER_NAME = "xacml.rest.admin.user.name"; - /** - * - * PROP_ADMIN_USER_ID is an id for the logged in user. - * - * Eg. hs1234 - * - * @see #PROP_ADMIN_USER_NAME for more information. - */ - public static final String PROP_ADMIN_USER_ID = "xacml.rest.admin.user.id"; - /** - * - * PROP_ADMIN_USER_EMAIL is a user's email address. - * - * @see #PROP_ADMIN_USER_NAME for more information. - */ - public static final String PROP_ADMIN_USER_EMAIL = "xacml.rest.admin.user.email"; - /** - * Directory path containing sub-directories where the Subscriber servlet - * puts files sent through data feeds. - */ - public static final String PROP_SUBSCRIBER_INCOMING = "xacml.subscriber.incoming"; - /** - * The specific data feed name for the Subscriber servlet to register for. - */ - public static final String PROP_SUBSCRIBER_FEED = "xacml.subscriber.feed"; - /** - * Value for the log time frame that is to be stored in the database any - * logs after this time frame will be removed. - */ - public static final String PROP_LOG_TIMEFRAME = "xacml.log.timeframe"; - /** - * Value for the DB connections used to store the log files. - */ - public static final String PROP_LOG_DB_DRIVER = "xacml.log.db.driver"; - public static final String PROP_LOG_DB_URL = "xacml.log.db.url"; - public static final String PROP_LOG_DB_USER = "xacml.log.db.user"; - public static final String PROP_LOG_DB_PASSWORD = "xacml.log.db.password"; - /* - * Value for JMX port for the PDP - */ - public static final String PROP_PDP_JMX_PORT = "xacml.jmx.port"; - - /* - * Value for refresh rate - */ - public static final String PROP_REFRESH_RATE = "xacml.refresh.rate"; - - // added for Security between Policy Components. - // 6/26 - /* - * PROP_PAP_USERID is the PAP Unique User ID - */ - public static final String PROP_PAP_USERID = "xacml.rest.pap.userid"; - /* - * PROP_PAP_PASS is the PAP password - */ - public static final String PROP_PAP_PASS = "xacml.rest.pap.password"; - /* - * PROP_PAP_PASS is the PAP password - */ - public static final String PROP_CONFIG_URL = "xacml.rest.config.url"; - /* - * PROP_PDP_USERID is the PDP Unique User ID - */ - public static final String PROP_PDP_USERID = "xacml.rest.pdp.userid"; - /* - * PROP_PDP_PASS is the PDP password - */ - public static final String PROP_PDP_PASS = "xacml.rest.pdp.password"; - /* - * PROP_PDP_IDFILE is the PDP Authentication File - */ - public static final String PROP_PDP_IDFILE = "xacml.rest.pdp.idfile"; - /* - * PROP_PEP_IDFILE is the Client Authentication File - */ - public static final String PROP_PEP_IDFILE = "xacml.rest.pep.idfile"; - /* - * webapps Location of the PAP-REST server - */ - public static final String PROP_PAP_WEBAPPS= "xacml.rest.config.webapps"; - /* - * Value for Notification Option - */ - public static final String PROP_NOTIFICATION_TYPE = "NOTIFICATION_TYPE"; - /* - * Value for Notification DMaaP servers - */ - public static final String PROP_NOTIFICATION_SERVERS = "NOTIFICATION_SERVERS"; - /* - * Value for Notification Delay - */ - public static final String PROP_NOTIFICATION_DELAY= "NOTIFICATION_DELAY"; - /* - * Value for Notification Topic - */ - public static final String PROP_NOTIFICATION_TOPIC= "NOTIFICATION_TOPIC"; - /* - * Value for Notification Topic - */ - public static final String PROP_UEB_API_KEY= "UEB_API_KEY"; - /* - * Value for Notification Topic - */ - public static final String PROP_UEB_API_SECRET= "UEB_API_SECRET"; - /* - * Closedloop Fault Policy Template Version - */ - public static final String TemplateVersion_Fault= "xacml.rest.closedLoopFault"; - /* - * Closedloop PM Policy Template Version - */ - public static final String TemplateVersion_PM= "xacml.rest.closedLoopPM"; - /* - * Value for model properties file - */ - public static final String PROP_ADMIN_MICROSERVICE = "xacml.rest.admin.microServiceModel"; - /* - * MicroService Policy Template Version - */ - public static final String TemplateVersion_MS= "xacml.rest.microServices"; - /* - * Firewall Policy Template Version - */ - public static final String TemplateVersion_FW= "xacml.rest.firewallPolicy"; - /* - * Size of SelectList for Users in MS - * - */ - public static final String PROP_USER_SELECTLIST_WINDOW_SIZE= "xacml.user.column.count"; - /* - * Audit function in pap admin to Update userinfo table to syncronize with Roles table - */ - public static final String PROP_ROLES_USERINFO_AUDIT= "xacml.audit.userInfo"; - /* - * test Environment LoginId - */ - public static final String PROP_TEST_ENVIRONMENT_LOGINID= "xacml.testEnvironment.loginId"; - /* - * Size of of the page length for sqlcontainer - * - */ - public static final String PROP_SQLCONTAINER_PAGE_LENGTH= "xacml.sqlcontainer.page.length"; - /* - * add values used to connect to restful api - * - */ - public static final String PROP_RESTFUL_INTERFACE= "xacm.restful.interface.file"; - /* - * add pattern to identify what values are designed as required - * - */ - public static final String PROP_XCORE_REQUIRED_PATTERN= "xacm.xcor.required.pattern"; - /* - * Time before a cache value is evicted - * - */ - public static final String PROP_CACHE_LIVE_TIME= "xacm.cache.live.time"; - /* - * Highest value allowed in priority - * - */ - public static final String PROP_PRIORITY_COUNT= "xacml.max.priority.count"; - /* - * The name of the PAP. Must be unique across the system - */ - public static final String PAP_RESOURCE_NAME="xacml.rest.pap.resource.name"; - /* - * The name of the site in which the PAP resides - */ - public static final String PAP_SITE_NAME="site_name"; - /* - * The node type of the PAP - really a no-op since it's value is pap - */ - public static final String PAP_NODE_TYPE="node_type"; - /* - * A list of the groups of resources/nodes on which the PAP is dependent. The members of a - * group are comma-separated and the groups are separated with semicolons. - */ - public static final String PAP_DEPENDENCY_GROUPS="dependency_groups"; - /* - * The (optional) period of time in seconds between executions of the integrity audit. - * Value < 0 : Audit does not run (default value if property is not present = -1) - * Value = 0 : Audit runs continuously - * Value > 0 : The period of time in seconds between execution of the audit on a particular node - */ - public static final String PAP_INTEGRITY_AUDIT_PERIOD_SECONDS = "integrity_audit_period_seconds"; - /* - * The name of the Admin. Must be unique across the system - */ - public static final String ADMIN_RESOURCE_NAME="xacml.rest.admin.resource.name"; - /* - * The name of the PDP. Must be unique across the system - */ - public static final String PDP_RESOURCE_NAME="xacml.rest.pdp.resource.name"; - /* - * Audit function in pap admin to Update userinfo table to syncronize with Roles table - */ - public static final String PROP_AUTOMATIC_POLICYPUSH= "xacml.automatic.push"; - /* - * Add Limit for Ecomp Portal Dashboard tab data - */ - public static final String PROP_ECOMP_LOGLIMIT = "xacml.ecomp.dashboard.logTableLimit"; - public static final String PROP_ECOMP_SYSTEMALERTLIMIT = "xacml.ecomp.dashboard.systemAlertTableLimit"; - /* - * Diff of the policies for the Firewall Feature. - */ - public static final String PROP_FW_GETURL = "FW_GETURL"; - public static final String PROP_FW_AUTHOURL = "FW_AUTHOURL"; - public static final String PROP_FW_PROXY = "FW_PROXY"; - public static final String PROP_FW_PORT = "FW_PORT"; - - /* - * The number of Risk Levels allowed - */ - public static final String ADMIN_RISK_LEVEL_COUNT="xacml.risk.level.count"; - /* - * The maxium Level displayed on the UI for Micro Services - */ - public static final String PROP_MODEL_LEVEL = "xacml.model.level"; - - /* - * Value for Incoming Notification tries - * - * */ - public static final String PROP_PAP_INCOMINGNOTIFICATION_TRIES = "xacml.rest.pap.incomingnotification.tries"; - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/XacmlAdminAuthorization.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/XacmlAdminAuthorization.java deleted file mode 100644 index 9a2dbdbdb..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/XacmlAdminAuthorization.java +++ /dev/null @@ -1,220 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; - -import com.att.research.xacml.api.DataTypeException; -import com.att.research.xacml.api.Decision; -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.Response; -import com.att.research.xacml.api.Result; -import com.att.research.xacml.api.pdp.PDPEngine; -import com.att.research.xacml.api.pdp.PDPEngineFactory; -import com.att.research.xacml.api.pdp.PDPException; -import com.att.research.xacml.std.annotations.RequestParser; -import com.att.research.xacml.std.annotations.XACMLAction; -import com.att.research.xacml.std.annotations.XACMLRequest; -import com.att.research.xacml.std.annotations.XACMLResource; -import com.att.research.xacml.std.annotations.XACMLSubject; -import com.att.research.xacml.util.FactoryException; - - - -public class XacmlAdminAuthorization { - private static Log logger = LogFactory.getLog(XacmlAdminAuthorization.class); - - private static UserInfo userId; - public static UserInfo getUserId() { - return userId; - } - - public void setUserId(UserInfo userId) { - XacmlAdminAuthorization.userId = userId; - } - - public enum AdminAction { - ACTION_ACCESS("access"), - ACTION_READ("read"), - ACTION_WRITE("write"), - ACTION_ADMIN("admin"); - - String action; - AdminAction(String a) { - this.action = a; - } - public String toString() { - return this.action; - } - } - - public enum AdminResource { - RESOURCE_APPLICATION("application"), - RESOURCE_POLICY_WORKSPACE("workspace"), - RESOURCE_POLICY_EDITOR("editor"), - RESOURCE_DICTIONARIES("dictionaries"), - RESOURCE_PDP_ADMIN("pdp_admin"), - RESOURCE_PIP_ADMIN("pip_admin"), - RESOURCE_SCOPES_SUPERADMIN("manage_scopes"); - - String resource; - AdminResource(String r) { - this.resource = r; - } - public String toString() { - return this.resource; - } - } - - public enum Role { - ROLE_GUEST("guest"), - ROLE_ADMIN("admin"), - ROLE_EDITOR("editor"), - ROLE_SUPERGUEST("super-guest"), - ROLE_SUPEREDITOR("super-editor"), - ROLE_SUPERADMIN("super-admin"); - - String userRole; - - Role(String a) { - this.userRole = a; - } - public String toString() { - return this.userRole; - } - } - - @XACMLRequest(ReturnPolicyIdList=true) - public class AuthorizationRequest { - - @XACMLSubject(includeInResults=true) - String userID; - - @XACMLAction() - String action; - - @XACMLResource() - String resource; - - public AuthorizationRequest(String userId, String action, String resource) { - this.userID = userId; - this.action = action; - this.resource = resource; - } - - public String getUserID() { - return userID; - } - - public void setUserID(String userID) { - this.userID = userID; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - public String getResource() { - return resource; - } - - public void setResource(String resource) { - this.resource = resource; - } - } - - // - // The PDP Engine - // - protected PDPEngine pdpEngine; - - public XacmlAdminAuthorization() { - PDPEngineFactory pdpEngineFactory = null; - try { - pdpEngineFactory = PDPEngineFactory.newInstance(); - if (pdpEngineFactory == null) { - logger.error("Failed to create PDP Engine Factory"); - PolicyLogger.error("Failed to create PDP Engine Factory"); - } - this.pdpEngine = pdpEngineFactory.newEngine(); - } catch (FactoryException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception create PDP Engine: " + e.getLocalizedMessage()); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XacmlAdminAuthorization", "Exception create PDP Engine"); - } - } - - public boolean isAuthorized(String userid, AdminAction action, AdminResource resource) { - logger.info("authorize: " + userid + " to " + action + " with " + resource); - if (this.pdpEngine == null) { - logger.warn("no pdp engine available to authorize"); - return false; - } - Request request; - try { - request = RequestParser.parseRequest(new AuthorizationRequest(userid, action.toString(), resource.toString())); - } catch (IllegalArgumentException | IllegalAccessException | DataTypeException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create request: " + e.getLocalizedMessage()); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XacmlAdminAuthorization", "Failed to create request"); - return false; - } - if (request == null) { - logger.error("Failed to parse request."); - PolicyLogger.error("Failed to parse request"); - return false; - } - logger.info("Request: " + request); - // - // Ask the engine - // - try { - Response response = this.pdpEngine.decide(request); - if (response == null) { - logger.error("Null response from PDP decide"); - PolicyLogger.error("Null response from PDP decide"); - } - // - // Should only be one result - // - if(response != null){ - for (Result result : response.getResults()) { - Decision decision = result.getDecision(); - logger.info("Decision: " + decision); - if (decision.equals(Decision.PERMIT)) { - return true; - } - } - } - } catch (PDPException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PDP Decide failed: " + e.getLocalizedMessage()); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XacmlAdminAuthorization", "PDP Decide failed"); - } - return false; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AddressGroupJson.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AddressGroupJson.java deleted file mode 100644 index 9d9ce64e1..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AddressGroupJson.java +++ /dev/null @@ -1,83 +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.rest.adapter; - - -import java.util.ArrayList; -import java.util.List; - -public class AddressGroupJson { - - protected String name; - protected String description; - protected List members; - - // name - public String getName() { - return name; - } - - public void setName(String value) { - this.name = value; - } - - public boolean equals(Object obj){ - if(obj == null){ - return false; - } - if(this.getClass() != obj.getClass()){ - return false; - } - AddressGroupJson servGroupobj=(AddressGroupJson) obj; - if(this.getName().equals(servGroupobj.getName())){ - return true; - } - return false; - } - - public int hashCode() { - return Integer.valueOf(name.charAt(0)+(name.charAt(1))); - } - - // description - public String getDescription() { - return description; - } - - public void setDescription(String value) { - this.description = value; - } - - public List getMembers() - { - if(members==null) - { - members= new ArrayList(); - } - return this.members; - } - - public void setMembers(List members) - { - this.members = members; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AddressJson.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AddressJson.java deleted file mode 100644 index d2361d807..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AddressJson.java +++ /dev/null @@ -1,52 +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.rest.adapter; - - -public class AddressJson { - - protected String type; - protected String name; - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - // type - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - /*public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - }*/ -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AddressMembers.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AddressMembers.java deleted file mode 100644 index f53f61c32..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AddressMembers.java +++ /dev/null @@ -1,46 +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.rest.adapter; - - - -public class AddressMembers { - - protected String type; - protected String value; - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AutoPushTabAdapter.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AutoPushTabAdapter.java deleted file mode 100644 index 7180f9a46..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/AutoPushTabAdapter.java +++ /dev/null @@ -1,42 +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.rest.adapter; - - -import java.util.ArrayList; - -public class AutoPushTabAdapter { - - private ArrayList pdpDatas; - private ArrayList policyDatas; - public ArrayList getPdpDatas() { - return pdpDatas; - } - public void setPdpDatas(ArrayList pdpDatas) { - this.pdpDatas = pdpDatas; - } - public ArrayList getPolicyDatas() { - return policyDatas; - } - public void setPolicyDatas(ArrayList policyDatas) { - this.policyDatas = policyDatas; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopFaultBody.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopFaultBody.java deleted file mode 100644 index 469b1075c..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopFaultBody.java +++ /dev/null @@ -1,280 +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.rest.adapter; - - - -public class ClosedLoopFaultBody { - - private boolean trinity; - private boolean vUSP; - private boolean mcr; - private boolean gama; - private boolean vDNS; - - private String vnfType; - private String vServices; - private String ECOMPname; - - private String closedLoopPolicyStatus; - private ClosedLoopSignatures triggerSignatures; - private String actions; - private int timeInterval; - private int timeOutvPRO; - private int timeOutRuby; - private int retrys; - private int agingWindow; - private String geoLink; - private String emailAddress; - private ClosedLoopSignatures verificationSignatures; - private ClosedLoopPolicyConditions conditions; - private ClosedLoopFaultTriggerUISignatures triggerSignaturesUsedForUI; - private ClosedLoopFaultTriggerUISignatures verificationSignaturesUsedForUI; - private int triggerTimeWindowUsedForUI; - private int verfificationTimeWindowUsedForUI; - private String pepName; - private String pepAction; - private String templateVersion; - private int trapMaxAgeUsedForUI; - - - public Integer getTrapMaxAgeUsedForUI() { - return trapMaxAgeUsedForUI; - } - - public void setTrapMaxAgeUsedForUI(int trapMaxAgeUsedForUI) { - this.trapMaxAgeUsedForUI = trapMaxAgeUsedForUI; - } - - public String getTemplateVersion() { - return templateVersion; - } - - public void setTemplateVersion(String templateVersion) { - this.templateVersion = templateVersion; - } - - public Integer getTimeOutvPRO() { - return timeOutvPRO; - } - - public void setTimeOutvPRO(int timeOutvPRO) { - this.timeOutvPRO = timeOutvPRO; - } - - - public Integer getTriggerTimeWindowUsedForUI() { - return triggerTimeWindowUsedForUI; - } - - public String getPepName() { - return pepName; - } - - public void setPepName(String pepName) { - this.pepName = pepName; - } - - public String getPepAction() { - return pepAction; - } - - public void setPepAction(String pepAction) { - this.pepAction = pepAction; - } - - public void setTriggerTimeWindowUsedForUI(int triggerTimeWindowUsedForUI) { - this.triggerTimeWindowUsedForUI = triggerTimeWindowUsedForUI; - } - - public Integer getVerfificationTimeWindowUsedForUI() { - return verfificationTimeWindowUsedForUI; - } - - public void setVerfificationTimeWindowUsedForUI( - int verfificationTimeWindowUsedForUI) { - this.verfificationTimeWindowUsedForUI = verfificationTimeWindowUsedForUI; - } - - public String getECOMPname(){ - return ECOMPname; - } - - public void setECOMPname(String ECOMPname){ - this.ECOMPname = ECOMPname; - } - - public String getvServices() { - return vServices; - } - public void setvServices(String vServices) { - this.vServices = vServices; - } - - public ClosedLoopFaultTriggerUISignatures getVerificationSignaturesUsedForUI() { - return verificationSignaturesUsedForUI; - } - public void setVerificationSignaturesUsedForUI( - ClosedLoopFaultTriggerUISignatures verificationSignaturesUsedForUI) { - this.verificationSignaturesUsedForUI = verificationSignaturesUsedForUI; - } - public ClosedLoopFaultTriggerUISignatures getTriggerSignaturesUsedForUI() { - return triggerSignaturesUsedForUI; - } - public void setTriggerSignaturesUsedForUI( - ClosedLoopFaultTriggerUISignatures triggerSignaturesUsedForUI) { - this.triggerSignaturesUsedForUI = triggerSignaturesUsedForUI; - } - public ClosedLoopPolicyConditions getConditions() { - return conditions; - } - public void setConditions(ClosedLoopPolicyConditions conditions) { - this.conditions = conditions; - } - - public String getVnfType() { - return vnfType; - } - public void setVnfType(String vnfType) { - this.vnfType = vnfType; - } - - public Integer getAgingWindow() { - return agingWindow; - } - public void setAgingWindow(int agingWindow) { - this.agingWindow = agingWindow; - } - - public String getClosedLoopPolicyStatus() { - return closedLoopPolicyStatus; - } - public void setClosedLoopPolicyStatus( - String closedLoopPolicyStatus) { - this.closedLoopPolicyStatus = closedLoopPolicyStatus; - } - public ClosedLoopSignatures getTriggerSignatures() { - return triggerSignatures; - } - public void setTriggerSignatures(ClosedLoopSignatures triggerSignatures) { - this.triggerSignatures = triggerSignatures; - } - public String getActions() { - return actions; - } - public void setActions(String actions) { - this.actions = actions; - } - public Integer getTimeInterval() { - return timeInterval; - } - public void setTimeInterval(int timeInterval) { - this.timeInterval = timeInterval; - } - public Integer getTimeOutRuby() { - return timeOutRuby; - } - public void setTimeOutRuby(int timeOutRuby) { - this.timeOutRuby = timeOutRuby; - } - public Integer getRetrys() { - return retrys; - } - public void setRetrys(int retrys) { - this.retrys = retrys; - } - public String getGeoLink() { - return geoLink; - } - public void setGeoLink(String geoLink) { - this.geoLink = geoLink; - } - public String getEmailAddress() { - return emailAddress; - } - public void setEmailAddress(String emailAddress) { - this.emailAddress = emailAddress; - } - public ClosedLoopSignatures getVerificationSignatures() { - return verificationSignatures; - } - public void setVerificationSignatures( - ClosedLoopSignatures verificationSignatures) { - this.verificationSignatures = verificationSignatures; - } - - /*public ArrayList getD2Services() { - return d2Services; - } - - public void setD2Services(ArrayList d2Services) { - this.d2Services = d2Services; - } - - public ArrayList getSiteNames() { - return siteNames; - } - - public void setSiteNames(ArrayList siteNames) { - this.siteNames = siteNames; - }*/ - - public boolean isvDNS() { - return vDNS; - } - - public void setvDNS(boolean vDNS) { - this.vDNS = vDNS; - } - - public boolean isTrinity() { - return trinity; - } - - public void setTrinity(boolean trinity) { - this.trinity = trinity; - } - - public boolean isvUSP() { - return vUSP; - } - - public void setvUSP(boolean vUSP) { - this.vUSP = vUSP; - } - - public boolean isMcr() { - return mcr; - } - - public void setMcr(boolean mcr) { - this.mcr = mcr; - } - - public boolean isGama() { - return gama; - } - - public void setGama(boolean gama) { - this.gama = gama; - } -} - diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopFaultTriggerUISignatures.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopFaultTriggerUISignatures.java deleted file mode 100644 index 1c1702e89..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopFaultTriggerUISignatures.java +++ /dev/null @@ -1,44 +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.rest.adapter; - - - -public class ClosedLoopFaultTriggerUISignatures { - - private String signatures; - - private String connectSignatures; - - public String getConnectSignatures() { - return connectSignatures; - } - public void setConnectSignatures(String connectSignatures) { - this.connectSignatures = connectSignatures; - } - public String getSignatures() { - return signatures; - } - public void setSignatures(String signatures) { - this.signatures = signatures; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPMBody.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPMBody.java deleted file mode 100644 index 419c7d7ea..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPMBody.java +++ /dev/null @@ -1,133 +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.rest.adapter; - - -import java.util.Map; - -public class ClosedLoopPMBody { - - private boolean trinity; - private boolean vUSP; - private boolean mcr; - private boolean gama; - private boolean vDNS; - private String geoLink; - private String vServices; - private String ECOMPname; - - private String emailAddress; - - private String serviceTypePolicyName; - - private Map attributes; - private String templateVersion; - - public String getTemplateVersion() { - return templateVersion; - } - - public void setTemplateVersion(String templateVersion) { - this.templateVersion = templateVersion; - } - - public String getECOMPname(){ - return ECOMPname; - } - - public void setECOMPname(String ECOMPname){ - this.ECOMPname = ECOMPname; - } - - public String getvServices() { - return vServices; - } - - public void setvServices(String vServices) { - this.vServices = vServices; - } - - public Map getAttributes() { - return attributes; - } - - public void setAttributes(Map map) { - this.attributes = map; - } - - public String getGeoLink() { - return geoLink; - } - - public void setGeoLink(String geoLink) { - this.geoLink = geoLink; - } - - public String getEmailAddress() { - return emailAddress; - } - - public void setEmailAddress(String emailAddress) { - this.emailAddress = emailAddress; - } - - public String getServiceTypePolicyName() { - return serviceTypePolicyName; - } - - public void setServiceTypePolicyName(String serviceTypePolicyName) { - this.serviceTypePolicyName = serviceTypePolicyName; - } - - public boolean isGama() { - return gama; - } - public void setGama(boolean gama) { - this.gama = gama; - } - public boolean isvDNS() { - return vDNS; - } - public void setvDNS(boolean vDNS) { - this.vDNS = vDNS; - } - - public boolean isTrinity() { - return trinity; - } - public void setTrinity(boolean trinity) { - this.trinity = trinity; - } - public boolean isvUSP() { - return vUSP; - } - public void setvUSP(boolean vUSP) { - this.vUSP = vUSP; - } - public boolean isMcr() { - return mcr; - } - public void setMcr(boolean mcr) { - this.mcr = mcr; - } - -} - diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPerformanceMetrics.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPerformanceMetrics.java deleted file mode 100644 index ad858a6af..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPerformanceMetrics.java +++ /dev/null @@ -1,36 +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.rest.adapter; - - -public class ClosedLoopPerformanceMetrics { - public static final String CLPM_UIFIELD_ONSET_MESSAGE = "Onset Message"; - public static final String CLPM_UIJSON_ONSET_MESSAGE = "attributes.OnsetMessage"; - - public static final String CLPM_UIFIELD_POLICY_NAME = "PolicyName"; - public static final String CLPM_UIJSON_POLICY_NAME = "attributes.PolicyName"; - - public static final String CLPM_UIFIELD_ABATEMENT_MESSAGE = "Abatement Message"; - public static final String CLPM_UIJSON_ABATEMENT_MESSAGE = "attributes.AbatementMessage"; - - public static final String CLPM_UIFIELD_GEOLINK = "Geo Link"; - public static final String CLPM_UIJSON_GEOLINK = "geoLink"; -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPolicy.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPolicy.java deleted file mode 100644 index 16db3c2b4..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPolicy.java +++ /dev/null @@ -1,61 +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.rest.adapter; - - -public class ClosedLoopPolicy { - public static final String CLFAULT_UIFIELD_D2_SERVICES_TRINITY = "Hosted Voice (Trinity)"; - public static final String CLFAULT_UIJSON_D2_SERVICES_TRINITY = "trinity"; - - public static final String CLFAULT_UIFIELD_D2_SERVICES_VUSP = "vUSP"; - public static final String CLFAULT_UIJSON_D2_SERVICES_VUSP = "vUSP"; - - public static final String CLFAULT_UIFIELD_D2_SERVICES_MCR = "MCR"; - public static final String CLFAULT_UIJSON_D2_SERVICES_MCR = "mcr"; - - public static final String CLFAULT_UIFIELD_D2_SERVICES_GAMMA = "Gamma"; - public static final String CLFAULT_UIJSON_D2_SERVICES_GAMMA = "gama"; - - public static final String CLFAULT_UIFIELD_D2_SERVICES_VDNS = "vDNS"; - public static final String CLFAULT_UIJSON_D2_SERVICES_VDNS = "vDNS"; - - public static final String CLFAULT_UIFIELD_EMAIL_ADDRESS = "Email Address"; - public static final String CLFAULT_UIJSON_EMAIL_ADDRESS = "emailAddress"; - - public static final String CLFAULT_UIFIELD_TRIGGER_SIGNATURE = "Trigger Signature"; - public static final String CLFAULT_UIJSON_TRIGGER_SIGNATURE = "triggerSignaturesUsedForUI.signatures"; - - public static final String CLFAULT_UIFIELD_VERIFICATION_SIGNATURE = "Verification Signature"; - public static final String CLFAULT_UIJSON_VERIFICATION_SIGNATURE = "verificationSignaturesUsedForUI.signatures"; - - public static final String CLFAULT_UIFIELD_CONNECT_ALL_TRAPS = "Connect All Traps"; - public static final String CLFAULT_UIJSON_CONNECT_ALL_TRAPS = "triggerSignaturesUsedForUI.connectSignatures"; - - public static final String CLFAULT_UIFIELD_CONNECT_ALL_FAULTS = "Connect All Faults"; - public static final String CLFAULT_UIJSON_CONNECT_ALL_FAULTS = "verificationSignaturesUsedForUI.connectSignatures"; - - public static final String CLFAULT_UIFIELD_POLICY_STATUS_ACTIVE = "Active"; - public static final String CLFAULT_UIJSON_POLICY_STATUS_ACTIVE = "ACTIVE"; - - public static final String CLFAULT_UIFIELD_POLICY_STATUS_INACTIVE = "InActive"; - public static final String CLFAULT_UIJSON_POLICY_STATUS_INACTIVE = "INACTIVE"; - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPolicyConditions.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPolicyConditions.java deleted file mode 100644 index ff7efdfbc..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPolicyConditions.java +++ /dev/null @@ -1,39 +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.rest.adapter; - - -public enum ClosedLoopPolicyConditions { - SEND("DCAE should send event notification"), - - NOTSEND("DCAE should not send event notification"); - private String name; - - private ClosedLoopPolicyConditions(String name){ - this.name = name; - } - - @Override - public String toString(){ - return this.name; - } -} - diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPolicyStatus.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPolicyStatus.java deleted file mode 100644 index 74138f448..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopPolicyStatus.java +++ /dev/null @@ -1,41 +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.rest.adapter; - - -public enum ClosedLoopPolicyStatus { - ACTIVE("active"), - - INACTIVE("inactive") - ; - - private String name; - - private ClosedLoopPolicyStatus(String name){ - this.name = name; - } - - @Override - public String toString(){ - return this.name; - } -} - diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopSignatures.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopSignatures.java deleted file mode 100644 index 793e93ed8..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ClosedLoopSignatures.java +++ /dev/null @@ -1,52 +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.rest.adapter; - - -public class ClosedLoopSignatures { - - private String signatures; - - private int timeWindow; - - private Integer trapMaxAge; - - public String getSignatures() { - return signatures; - } - public void setSignatures(String signatures) { - this.signatures = signatures; - } - - public Integer getTimeWindow() { - return timeWindow; - } - public void setTimeWindow(Integer timeWindow) { - this.timeWindow = timeWindow; - } - - public Integer getTrapMaxAge() { - return trapMaxAge; - } - public void setTrapMaxAge(Integer trapMaxAge) { - this.trapMaxAge = trapMaxAge; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/DeletePolicyCondition.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/DeletePolicyCondition.java deleted file mode 100644 index f34bc1d3e..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/DeletePolicyCondition.java +++ /dev/null @@ -1,38 +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.rest.adapter; - - -public enum DeletePolicyCondition { - ONE("Are you sure you want to delete Current Version of policy"), - - ALL("Are you sure you want to delete All Versions of policy"); - private String name; - - private DeletePolicyCondition(String name){ - this.name = name; - } - - @Override - public String toString(){ - return this.name; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/DeployNowJson.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/DeployNowJson.java deleted file mode 100644 index 6344fbfcb..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/DeployNowJson.java +++ /dev/null @@ -1,36 +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.rest.adapter; - - -public class DeployNowJson { - - protected boolean deployNow; - - // deployNow - public boolean getDeployNow() { - return deployNow; - } - - public void setDeployNow(boolean value) { - this.deployNow = value; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/GridData.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/GridData.java deleted file mode 100644 index f39156cf1..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/GridData.java +++ /dev/null @@ -1,54 +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.rest.adapter; - - -import java.util.ArrayList; - -public class GridData { - private ArrayList attributes; - private ArrayList transportProtocols; - private ArrayList appProtocols; - - public ArrayList getAttributes() { - return attributes; - } - - public void setAttributes(ArrayList attributes) { - this.attributes = attributes; - } - - public ArrayList getAppProtocols() { - return appProtocols; - } - - public void setAppProtocols(ArrayList appProtocols) { - this.appProtocols = appProtocols; - } - - public ArrayList getTransportProtocols() { - return transportProtocols; - } - - public void setTransportProtocols(ArrayList transportProtocols) { - this.transportProtocols = transportProtocols; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/IdMap.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/IdMap.java deleted file mode 100644 index 6efb53a0b..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/IdMap.java +++ /dev/null @@ -1,42 +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.rest.adapter; - - -public class IdMap { - - protected String astraId; - protected String vendorId; - - public String getAstraId() { - return astraId; - } - public void setAstraId(String astraId) { - this.astraId = astraId; - } - public String getVendorId() { - return vendorId; - } - public void setVendorId(String vendorId) { - this.vendorId = vendorId; - } - -} \ No newline at end of file diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PolicyExportAdapter.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PolicyExportAdapter.java deleted file mode 100644 index ce2d21083..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PolicyExportAdapter.java +++ /dev/null @@ -1,36 +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.rest.adapter; - - -import java.util.ArrayList; - -public class PolicyExportAdapter { - - private ArrayList policyDatas; - - public ArrayList getPolicyDatas() { - return policyDatas; - } - public void setPolicyDatas(ArrayList policyDatas) { - this.policyDatas = policyDatas; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PolicyRestAdapter.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PolicyRestAdapter.java deleted file mode 100644 index 27da724e2..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PolicyRestAdapter.java +++ /dev/null @@ -1,896 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-PAP-REST - * ================================================================================ - * 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.rest.adapter; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import javax.persistence.EntityManagerFactory; - -import org.openecomp.policy.rest.jpa.EcompName; - -public class PolicyRestAdapter { - - /* - * - * Note : Make Sure if any variables are added in PolicyRestAdapter.java, add them to PolicyElasticData.java file - * - * - * */ - - - //Common - private Object data; - private String policyName = null; - private String configBodyData = null; - private String configType = null; - private String policyID = null; - private String policyType = null; - private String comboPolicyType; - private String configPolicyType = null; - private String policyDescription = null; - private String ecompName = null; - private String configName = null; - private String ruleID = null; - private String parentPath; - private boolean isValidData = false; - private String adminNotification = null; - private boolean isEditPolicy = false; - private boolean isViewPolicy = false; - private boolean isDraft = false; - private Object policyData = null; - private String gitPath; - private boolean readOnly; - private String configHome; - private String configUrl; - private String finalPolicyPath; - private String version; - private String jsonBody; - private String apiflag; - private String prevJsonBody; - private Integer highestVersion; - private EntityManagerFactory entityManagerFactory = null; - private Boolean policyExists = false; - private String oldPolicyFileName = null; - private String domain = null; - private String userId; - private String newFileName; - private String clWarning = null; - private String newCLName = null; - private String existingCLName = null; - //Used by GUI - private EcompName ecompNameField; - private Object jsonBodyData; - private String dirPath; - private String configBodyPath; - private ArrayList attributes; - private ArrayList settings; - private ArrayList ruleAlgorithmschoices; - - private LinkedHashMap serviceTypePolicyName; - - private LinkedHashMap verticaMetrics; - private LinkedHashMap description; - private LinkedHashMap attributeFields; - - //ClosedLoop - private String clearTimeOut; - private String trapMaxAge; - private String verificationclearTimeOut; - private Map dynamicLayoutMap; - - //FireWall - private String fwPolicyType; - private ArrayList fwattributes; - private String parentForChild; - private String securityZone; - - //Action & Decision - private String ruleCombiningAlgId = null; - private Map dynamicFieldConfigAttributes; - private Map dynamicSettingsMap; - private Map dropDownMap; - private String actionPerformer = null; - private String actionAttribute = null; - private List dynamicRuleAlgorithmLabels; - private List dynamicRuleAlgorithmCombo; - private List dynamicRuleAlgorithmField1; - private List dynamicRuleAlgorithmField2; - private List dynamicVariableList; - private List dataTypeList; - private String actionAttributeValue; - private String ruleProvider; - private String actionBody = null; - private String actionDictHeader = null; - private String actionDictType = null; - private String actionDictUrl = null; - private String actionDictMethod = null; - private YAMLParams yamlparams; - - //Rainy Day Decision - private RainyDayParams rainyday; - private Map rainydayMap; - private List errorCodeList; - private List treatmentList; - - //MicroSerice - private String serviceType = null; - private String uuid = null; - private String location = null; - private String priority = null; - private String msLocation = null; - - //BRMS Policies - private String ruleName; - private Map brmsParamBody=null; - private String brmsController = null; - private ArrayList brmsDependency = null; - private LinkedHashMap ruleData; - private LinkedHashMap ruleListData; - private Map drlRuleAndUIParams=null; - - //Safe Policy - private String policyScope; - private String providerComboBox = null; - private String riskType; - private String riskLevel; - private String guard = null; - private String ttlDate; - private Map matching; - - private ArrayList triggerSignatures; - private ArrayList symptomSignatures; - private String logicalConnector; - private String policyStatus; - private String gocServerScope; - private String supressionType; - - - public ArrayList getTriggerSignatures() { - return triggerSignatures; - } - public void setTriggerSignatures(ArrayList triggerSignatures) { - this.triggerSignatures = triggerSignatures; - } - public ArrayList getSymptomSignatures() { - return symptomSignatures; - } - public void setSymptomSignatures(ArrayList symptomSignatures) { - this.symptomSignatures = symptomSignatures; - } - public String getLogicalConnector() { - return logicalConnector; - } - public void setLogicalConnector(String logicalConnector) { - this.logicalConnector = logicalConnector; - } - public String getPolicyStatus() { - return policyStatus; - } - public void setPolicyStatus(String policyStatus) { - this.policyStatus = policyStatus; - } - public String getGocServerScope() { - return gocServerScope; - } - public void setGocServerScope(String gocServerScope) { - this.gocServerScope = gocServerScope; - } - - public String getSupressionType() { - return supressionType; - } - public void setSupressionType(String supressionType) { - this.supressionType = supressionType; - } - - /********************************************************************************/ - - - - public String getComboPolicyType() { - return comboPolicyType; - } - public void setComboPolicyType(String comboPolicyType) { - this.comboPolicyType = comboPolicyType; - } - public String getGitPath() { - return gitPath; - } - public void setGitPath(String gitPath) { - this.gitPath = gitPath; - } - public String getOldPolicyFileName() { - return oldPolicyFileName; - } - public void setOldPolicyFileName(String oldPolicyFileName) { - this.oldPolicyFileName = oldPolicyFileName; - } - public String getDomainDir() { - return domain; - } - public void setDomainDir(String domain) { - this.domain = domain; - } - public Integer getHighestVersion() { - return highestVersion; - } - public void setHighestVersion(Integer highestVersion) { - this.highestVersion = highestVersion; - } - public Object getData() { - return data; - } - public void setData(Object data) { - this.data = data; - } - public String getPolicyName() { - return policyName; - } - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - public String getConfigBodyData() { - return configBodyData; - } - public void setConfigBodyData(String configBodyData) { - this.configBodyData = configBodyData; - } - public String getConfigType() { - return configType; - } - public void setConfigType(String configType) { - this.configType = configType; - } - public String getPolicyID() { - return policyID; - } - public void setPolicyID(String policyID) { - this.policyID = policyID; - } - public String getPolicyType() { - return policyType; - } - public void setPolicyType(String policyType) { - this.policyType = policyType; - } - public String getPolicyDescription() { - return policyDescription; - } - public void setPolicyDescription(String policyDescription) { - this.policyDescription = policyDescription; - } - public String getEcompName() { - return ecompName; - } - public void setEcompName(String ecompName) { - this.ecompName = ecompName; - } - public String getConfigName() { - return configName; - } - public void setConfigName(String configName) { - this.configName = configName; - } - public String getRuleID() { - return ruleID; - } - public void setRuleID(String ruleID) { - this.ruleID = ruleID; - } - public String getRuleCombiningAlgId() { - return ruleCombiningAlgId; - } - public void setRuleCombiningAlgId(String ruleCombiningAlgId) { - this.ruleCombiningAlgId = ruleCombiningAlgId; - } - public Map getDynamicFieldConfigAttributes() { - return dynamicFieldConfigAttributes; - } - public void setDynamicFieldConfigAttributes( - Map dynamicFieldConfigAttributes) { - this.dynamicFieldConfigAttributes = dynamicFieldConfigAttributes; - } - public String getParentPath() { - return parentPath; - } - public void setParentPath(String parentPath) { - this.parentPath = parentPath; - } - public boolean isEditPolicy() { - return isEditPolicy; - } - public void setEditPolicy(boolean isEditPolicy) { - this.isEditPolicy = isEditPolicy; - } - public boolean isViewPolicy() { - return isViewPolicy; - } - public void setViewPolicy(boolean isViewPolicy) { - this.isViewPolicy = isViewPolicy; - } - public Object getPolicyData() { - return policyData; - } - public void setPolicyData(Object policyData) { - this.policyData = policyData; - } - public boolean isReadOnly() { - return readOnly; - } - public void setReadOnly(boolean readOnly) { - this.readOnly = readOnly; - } - public String getUserGitPath() { - return gitPath; - } - public void setUserGitPath(String gitPath) { - this.gitPath = gitPath; - } - public boolean isValidData() { - return isValidData; - } - public void setValidData(boolean isValidData) { - this.isValidData = isValidData; - } - public String getAdminNotification() { - return adminNotification; - } - public void setAdminNotification(String adminNotification) { - this.adminNotification = adminNotification; - } - public String getConfigHome() { - return configHome; - } - public void setConfigHome(String configHome) { - this.configHome = configHome; - } - public String getConfigUrl() { - return configUrl; - } - public void setConfigUrl(String configUrl) { - this.configUrl = configUrl; - } - public String getFinalPolicyPath() { - return finalPolicyPath; - } - public void setFinalPolicyPath(String finalPolicyPath) { - this.finalPolicyPath = finalPolicyPath; - } - public String getVersion() { - return version; - } - public void setVersion(String version) { - this.version = version; - } - public String getJsonBody() { - return jsonBody; - } - public void setJsonBody(String jsonBody) { - this.jsonBody = jsonBody; - } - public String getPrevJsonBody() { - return prevJsonBody; - } - public void setPrevJsonBody(String prevJsonBody) { - this.prevJsonBody = prevJsonBody; - } - public String getApiflag() { - return apiflag; - } - public void setApiflag(String apiflag) { - this.apiflag = apiflag; - } - /** - * @return the actionPerformer - */ - public String getActionPerformer() { - return actionPerformer; - } - /** - * @param actionPerformer the actionPerformer to set - */ - public void setActionPerformer(String actionPerformer) { - this.actionPerformer = actionPerformer; - } - /** - * @return the actionAttribute - */ - public String getActionAttribute() { - return actionAttribute; - } - /** - * @param actionAttribute the actionAttribute to set - */ - public void setActionAttribute(String actionAttribute) { - this.actionAttribute = actionAttribute; - } - /** - * @return the dynamicRuleAlgorithmLabels - */ - public List getDynamicRuleAlgorithmLabels() { - return dynamicRuleAlgorithmLabels; - } - /** - * @param dynamicRuleAlgorithmLabels the dynamicRuleAlgorithmLabels to set - */ - public void setDynamicRuleAlgorithmLabels( - List dynamicRuleAlgorithmLabels) { - this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; - } - /** - * @return the dynamicRuleAlgorithmCombo - */ - public List getDynamicRuleAlgorithmCombo() { - return dynamicRuleAlgorithmCombo; - } - /** - * @param dynamicRuleAlgorithmCombo the dynamicRuleAlgorithmCombo to set - */ - public void setDynamicRuleAlgorithmCombo(List dynamicRuleAlgorithmCombo) { - this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; - } - /** - * @return the dynamicRuleAlgorithmField1 - */ - public List getDynamicRuleAlgorithmField1() { - return dynamicRuleAlgorithmField1; - } - /** - * @param dynamicRuleAlgorithmField1 the dynamicRuleAlgorithmField1 to set - */ - public void setDynamicRuleAlgorithmField1( - List dynamicRuleAlgorithmField1) { - this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; - } - /** - * @return the dynamicRuleAlgorithmField2 - */ - public List getDynamicRuleAlgorithmField2() { - return dynamicRuleAlgorithmField2; - } - /** - * @param dynamicRuleAlgorithmField2 the dynamicRuleAlgorithmField2 to set - */ - public void setDynamicRuleAlgorithmField2( - List dynamicRuleAlgorithmField2) { - this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; - } - public Map getDropDownMap() { - return dropDownMap; - } - public void setDropDownMap(Map dropDownMap) { - this.dropDownMap = dropDownMap; - } - - public Map getDynamicSettingsMap() { - return dynamicSettingsMap; - } - public void setDynamicSettingsMap(Map dynamicSettingsMap) { - this.dynamicSettingsMap = dynamicSettingsMap; - } - public List getDynamicVariableList() { - return dynamicVariableList; - } - public void setDynamicVariableList(List dynamicVariableList) { - this.dynamicVariableList = dynamicVariableList; - } - public List getDataTypeList() { - return dataTypeList; - } - public void setDataTypeList(List dataTypeList) { - this.dataTypeList = dataTypeList; - } - public boolean isDraft() { - return isDraft; - } - public void setDraft(boolean isDraft) { - this.isDraft = isDraft; - } - public String getConfigPolicyType() { - return configPolicyType; - } - public void setConfigPolicyType(String configPolicyType) { - this.configPolicyType = configPolicyType; - } - public String getServiceType() { - return serviceType; - } - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - public String getUuid() { - return uuid; - } - public void setUuid(String uuid) { - this.uuid = uuid; - } - public String getLocation() { - return location; - } - public void setLocation(String location) { - this.location = location; - } - public String getPriority() { - return priority; - } - public void setPriority(String priority) { - this.priority = priority; - } - public Map getBrmsParamBody() { - return brmsParamBody; - } - public void setBrmsParamBody(Map brmsParamBody) { - this.brmsParamBody = brmsParamBody; - } - public EntityManagerFactory getEntityManagerFactory() { - return entityManagerFactory; - } - public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) { - this.entityManagerFactory = entityManagerFactory; - } - /** - * @return the policyExists - */ - public Boolean getPolicyExists() { - return policyExists; - } - /** - * @param policyExists the policyExists to set - */ - public void setPolicyExists(Boolean policyExists) { - this.policyExists = policyExists; - } - public String getPolicyScope() { - return policyScope; - } - - public void setPolicyScope(String domainDir) { - this. policyScope=domainDir; - } - public String getProviderComboBox() { - return providerComboBox; - } - public void setProviderComboBox(String providerComboBox) { - this.providerComboBox = providerComboBox; - } - public String getRiskType() { - return riskType; - } - public void setRiskType(String riskType) { - this.riskType = riskType; - } - public String getGuard() { - return guard; - } - public void setGuard(String guard) { - this.guard = guard; - } - public String getRiskLevel() { - return riskLevel; - } - public void setRiskLevel(String riskLevel) { - this.riskLevel = riskLevel; - } - public String getTtlDate() { - return ttlDate; - } - public void setTtlDate(String ttlDate) { - this.ttlDate = ttlDate; - } - public String getBrmsController() { - return brmsController; - } - public void setBrmsController(String brmsController) { - this.brmsController = brmsController; - } - public ArrayList getBrmsDependency() { - return brmsDependency; - } - public void setBrmsDependency(ArrayList brmsDependency) { - this.brmsDependency = brmsDependency; - } - public Map getMatching() { - return matching; - } - public void setMatching(Map matching) { - this.matching = matching; - } - public String getUserId() { - return userId; - } - public void setUserId(String userId) { - this.userId = userId; - } - public String getNewFileName() { - return newFileName; - } - public void setNewFileName(String newFileName) { - this.newFileName = newFileName; - } - - public String getDomain() { - return domain; - } - public void setDomain(String domain) { - this.domain = domain; - } - public EcompName getEcompNameField() { - return ecompNameField; - } - public void setEcompNameField(EcompName ecompNameField) { - this.ecompNameField = ecompNameField; - } - public Object getJsonBodyData() { - return jsonBodyData; - } - public void setJsonBodyData(Object jsonBodyData) { - this.jsonBodyData = jsonBodyData; - } - public String getDirPath() { - return dirPath; - } - public void setDirPath(String dirPath) { - this.dirPath = dirPath; - } - public String getConfigBodyPath() { - return configBodyPath; - } - public void setConfigBodyPath(String configBodyPath) { - this.configBodyPath = configBodyPath; - } - public ArrayList getAttributes() { - return attributes; - } - public void setAttributes(ArrayList attributes) { - this.attributes = attributes; - } - public ArrayList getSettings() { - return settings; - } - public void setSettings(ArrayList settings) { - this.settings = settings; - } - public ArrayList getRuleAlgorithmschoices() { - return ruleAlgorithmschoices; - } - public void setRuleAlgorithmschoices(ArrayList ruleAlgorithmschoices) { - this.ruleAlgorithmschoices = ruleAlgorithmschoices; - } - public LinkedHashMap getServiceTypePolicyName() { - return serviceTypePolicyName; - } - public void setServiceTypePolicyName(LinkedHashMap serviceTypePolicyName) { - this.serviceTypePolicyName = serviceTypePolicyName; - } - public LinkedHashMap getVerticaMetrics() { - return verticaMetrics; - } - public void setVerticaMetrics(LinkedHashMap verticaMetrics) { - this.verticaMetrics = verticaMetrics; - } - public LinkedHashMap getDescription() { - return description; - } - public void setDescription(LinkedHashMap description) { - this.description = description; - } - public LinkedHashMap getAttributeFields() { - return attributeFields; - } - public void setAttributeFields(LinkedHashMap attributeFields) { - this.attributeFields = attributeFields; - } - 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 Map getDynamicLayoutMap() { - return dynamicLayoutMap; - } - public void setDynamicLayoutMap(Map dynamicLayoutMap) { - this.dynamicLayoutMap = dynamicLayoutMap; - } - public String getFwPolicyType() { - return fwPolicyType; - } - public void setFwPolicyType(String fwPolicyType) { - this.fwPolicyType = fwPolicyType; - } - public ArrayList getFwattributes() { - return fwattributes; - } - public void setFwattributes(ArrayList fwattributes) { - this.fwattributes = fwattributes; - } - public String getParentForChild() { - return parentForChild; - } - public void setParentForChild(String parentForChild) { - this.parentForChild = parentForChild; - } - public String getRuleName() { - return ruleName; - } - public void setRuleName(String ruleName) { - this.ruleName = ruleName; - } - public LinkedHashMap getRuleData() { - return ruleData; - } - public void setRuleData(LinkedHashMap ruleData) { - this.ruleData = ruleData; - } - public LinkedHashMap getRuleListData() { - return ruleListData; - } - public void setRuleListData(LinkedHashMap ruleListData) { - this.ruleListData = ruleListData; - } - public String getSecurityZone() { - return securityZone; - } - public void setSecurityZone(String securityZone) { - this.securityZone = securityZone; - } - public String getActionAttributeValue() { - return actionAttributeValue; - } - public void setActionAttributeValue(String actionAttributeValue) { - this.actionAttributeValue = actionAttributeValue; - } - public String getRuleProvider() { - return ruleProvider; - } - public void setRuleProvider(String ruleProvider) { - this.ruleProvider = ruleProvider; - } - public String getMsLocation() { - return msLocation; - } - public void setMsLocation(String msLocation) { - this.msLocation = msLocation; - } - public Map getDrlRuleAndUIParams() { - return drlRuleAndUIParams; - } - public void setDrlRuleAndUIParams(Map drlRuleAndUIParams) { - this.drlRuleAndUIParams = drlRuleAndUIParams; - } - public String getActionBody() { - return actionBody; - } - public void setActionBody(String actionBody) { - this.actionBody = actionBody; - } - public String getActionDictHeader() { - return actionDictHeader; - } - public void setActionDictHeader(String actionDictHeader) { - this.actionDictHeader = actionDictHeader; - } - public String getActionDictType() { - return actionDictType; - } - public void setActionDictType(String actionDictType) { - this.actionDictType = actionDictType; - } - public String getActionDictUrl() { - return actionDictUrl; - } - public void setActionDictUrl(String actionDictUrl) { - this.actionDictUrl = actionDictUrl; - } - public String getActionDictMethod() { - return actionDictMethod; - } - public void setActionDictMethod(String actionDictMethod) { - this.actionDictMethod = actionDictMethod; - } - public String getClWarning() { - return clWarning; - } - public void setClWarning(String clWarning) { - this.clWarning = clWarning; - } - public String getNewCLName() { - return newCLName; - } - public void setNewCLName(String newCLName) { - this.newCLName = newCLName; - } - public String getExistingCLName() { - return existingCLName; - } - public void setExistingCLName(String existingCLName) { - this.existingCLName = existingCLName; - } - public YAMLParams getYamlparams() { - return yamlparams; - } - public void setYamlparams(YAMLParams yamlparams) { - this.yamlparams = yamlparams; - } - /** - * @return the rainyday - */ - public RainyDayParams getRainyday() { - return rainyday; - } - /** - * @param rainyday the rainyday to set - */ - public void setRainyday(RainyDayParams rainyday) { - this.rainyday = rainyday; - } - /** - * @return the errorCodeList - */ - public List getErrorCodeList() { - return errorCodeList; - } - /** - * @param errorCodeList the errorCodeList to set - */ - public void setErrorCodeList(List errorCodeList) { - this.errorCodeList = errorCodeList; - } - /** - * @return the treatmentList - */ - public List getTreatmentList() { - return treatmentList; - } - /** - * @param treatmentList the treatmentList to set - */ - public void setTreatmentList(List treatmentList) { - this.treatmentList = treatmentList; - } - /** - * @return the rainydayMap - */ - public Map getRainydayMap() { - return rainydayMap; - } - /** - * @param rainydayMap the rainydayMap to set - */ - public void setRainydayMap(Map rainydayMap) { - this.rainydayMap = rainydayMap; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PrefixIPList.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PrefixIPList.java deleted file mode 100644 index 3de72ee68..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/PrefixIPList.java +++ /dev/null @@ -1,72 +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.rest.adapter; - - - -import java.util.ArrayList; -import java.util.List; - - -public class PrefixIPList { - protected String name; - protected String description; - protected List members; - - 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; - } - - public List getMembers() - { - if(members==null) - { - members= new ArrayList(); - } - return this.members; - } - - public void setMembers(List members) - { - this.members = members; - } - /*public String getValue() { - return value; - } - - - public void setValue(String value) { - this.value = value; - }*/ - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/RainyDayParams.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/RainyDayParams.java deleted file mode 100644 index 8fdcc0ffb..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/RainyDayParams.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.openecomp.policy.rest.adapter; - -import java.util.ArrayList; -import java.util.List; - -public class RainyDayParams { - private String serviceType; - private String vnfType; - private String bbid; - private String workstep; - private ArrayList treatmentTableChoices; - private List errorcode; - private List treatment; - - /** - * @return the serviceType - */ - public String getServiceType() { - return serviceType; - } - /** - * @param serviceType the serviceType to set - */ - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - /** - * @return the vnfType - */ - public String getVnfType() { - return vnfType; - } - /** - * @param vnfType the vnfType to set - */ - public void setVnfType(String vnfType) { - this.vnfType = vnfType; - } - /** - * @return the workstep - */ - public String getWorkstep() { - return workstep; - } - /** - * @param workstep the workstep to set - */ - public void setWorkstep(String workstep) { - this.workstep = workstep; - } - /** - * @return the bbid - */ - public String getBbid() { - return bbid; - } - /** - * @param bbid the bbid to set - */ - public void setBbid(String bbid) { - this.bbid = bbid; - } - /** - * @return the treatmentTableChoices - */ - public ArrayList getTreatmentTableChoices() { - return treatmentTableChoices; - } - /** - * @param treatmentTableChoices the treatmentTableChoices to set - */ - public void setTreatmentTableChoices(ArrayList treatmentTableChoices) { - this.treatmentTableChoices = treatmentTableChoices; - } - /** - * @return the errorcode - */ - public List getErrorcode() { - return errorcode; - } - /** - * @param errorcode the errorcode to set - */ - public void setErrorcode(List errorcode) { - this.errorcode = errorcode; - } - /** - * @return the treatment - */ - public List getTreatment() { - return treatment; - } - /** - * @param treatment the treatment to set - */ - public void setTreatment(List treatment) { - this.treatment = treatment; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServiceGroupJson.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServiceGroupJson.java deleted file mode 100644 index 1dca60cbc..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServiceGroupJson.java +++ /dev/null @@ -1,83 +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.rest.adapter; - - -import java.util.ArrayList; -import java.util.List; - -public class ServiceGroupJson { - - protected String name; - protected String description; - protected List members; - - // name - public String getName() { - return name; - } - - public void setName(String value) { - this.name = value; - } - - public boolean equals(Object obj){ - if(obj == null){ - return false; - } - if(this.getClass() != obj.getClass()){ - return false; - } - ServiceGroupJson servGroupobj=(ServiceGroupJson) obj; - if(this.getName().equals(servGroupobj.getName())){ - return true; - } - return false; - } - - public int hashCode() { - return Integer.valueOf(name.charAt(0)+(name.charAt(1))); - } - - // description - public String getDescription() { - return description; - } - - public void setDescription(String value) { - this.description = value; - } - - public List getMembers() - { - if(members==null) - { - members= new ArrayList(); - } - return this.members; - } - - public void setMembers(List members) - { - this.members = members; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServiceListJson.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServiceListJson.java deleted file mode 100644 index 46aa2b55c..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServiceListJson.java +++ /dev/null @@ -1,111 +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.rest.adapter; - - - -public class ServiceListJson { - - protected String name; - protected String description; - protected String type; - protected String transportProtocol; - protected String appProtocol; - protected String ports; - // name - public String getName() { - return name; - } - - public void setName(String value) { - this.name = value; - } - - public boolean equals(Object obj){ - if(obj == null){ - return false; - } - if(this.getClass() != obj.getClass()){ - return false; - } - ServiceListJson servobj=(ServiceListJson) obj; - if(this.getName().equals(servobj.getName())){ - return true; - } - return false; - } - - public int hashCode() { - if(name!=null){ - return Integer.valueOf(name.charAt(0)+(name.charAt(1))); - }else{ - return 0; - } - } - - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - // type - public String getType() { - return type; - } - - public void setType(String value) { - this.type = value; - } - - // transportProtocol - public String getTransportProtocol() { - return transportProtocol; - } - - public void setTransportProtocol(String value) { - this.transportProtocol = value; - } - - // appProtocol - public String getAppProtocol() { - return appProtocol; - } - - public void setAppProtocol(String value) { - this.appProtocol = value; - } - - // ports - public String getPorts() { - return ports; - } - - public void setPorts(String value) { - this.ports = value; - } - - - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServiceMembers.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServiceMembers.java deleted file mode 100644 index a88df5174..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServiceMembers.java +++ /dev/null @@ -1,48 +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.rest.adapter; - - - -public class ServiceMembers { - - protected String type; - protected String name; - - // type - public String getType() { - return type; - } - - public void setType(String value) { - this.type = value; - } - - // transportProtocol - public String getName() { - return name; - } - - public void setName(String value) { - this.name = value; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServicesJson.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServicesJson.java deleted file mode 100644 index c64af9a3c..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/ServicesJson.java +++ /dev/null @@ -1,44 +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.rest.adapter; - - -public class ServicesJson { - - protected String type; - protected String name; - // type - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getName() { - return name; - } - - public void setName(String value) { - this.name = value; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/TagDefines.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/TagDefines.java deleted file mode 100644 index 0af88912a..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/TagDefines.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.adapter; - -public class TagDefines { - String key; - String value; - - public String getKey() { - return key; - } - public void setKey(String key) { - this.key = key; - } - public String getValue() { - return value; - } - public void setValue(String value) { - this.value = value; - } - - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/Tags.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/Tags.java deleted file mode 100644 index 43bff884c..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/Tags.java +++ /dev/null @@ -1,59 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.adapter; - - -import java.util.List; - - -public class Tags { - String ruleName; - List tags; - String tagPickerName; - String networkRole; - - public String getRuleName() { - return ruleName; - } - public void setRuleName(String ruleName) { - this.ruleName = ruleName; - } - public List getTags() { - return tags; - } - public void setTags(List tags) { - this.tags = tags; - } - public String getTagPickerName() { - return tagPickerName; - } - - public void setTagPickerName(String tagPickerName) { - this.tagPickerName = tagPickerName; - } - public String getNetworkRole() { - return networkRole; - } - public void setNetworkRole(String networkRole) { - this.networkRole = networkRole; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/Term.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/Term.java deleted file mode 100644 index e5e0a7b00..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/Term.java +++ /dev/null @@ -1,201 +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.rest.adapter; - - - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - - -public class Term { - - String position; - protected String ruleName; - protected List fromZones; - protected List toZones; - protected boolean negateSource; //hardcoded - protected boolean negateDestination; //hardcoded - protected List sourceList; - protected List destinationList; - protected List sourceServices; - protected Set destServices; - protected String action; - protected String description; - boolean enabled; //hardcoded - boolean log; //hardcoded - - //position - public String getPosition() { - return position; - } - - public void setPosition(String value) { - this.position = value; - } - - //RuleName - public String getRuleName() { - return ruleName; - } - - public void setRuleName(String value) { - this.ruleName = value; - } - - //From Zone - public List getFromZones() { - if (fromZones==null) - { - fromZones= new ArrayList(); - } - return fromZones; - } - - public void setFromZones(List fromZones) { - this.fromZones = fromZones; - } - - //To Zone - public List getToZones() { - if (toZones==null) - { - toZones= new ArrayList(); - } - return toZones; - } - - public void setToZones(List toZones) { - this.toZones = toZones; - } - - - //Negate Source - public boolean getNegateSource() { - return negateSource; - } - - public void setNegateSource(boolean negateSource) { - this.negateSource = negateSource; - } - - //Negate Destination - public boolean getNegateDestination() { - return negateDestination; - } - - public void setNegateDestination(boolean negateDestination) { - this.negateDestination = negateDestination; - } - - //SourceList - public List getSourceList() - { - if(sourceList==null) - { - sourceList= new ArrayList(); - } - return this.sourceList; - } - - public void setSourceList(List srcList) { - this.sourceList = srcList; - } - - //Destination List - public List getDestinationList() - { - if(destinationList==null) - { - destinationList= new ArrayList(); - } - return this.destinationList; - } - - public void setDestinationList(List destList) { - this.destinationList = destList; - } - - //Source Services - public List getSourceServices() { - if(sourceServices==null) - { - sourceServices= new ArrayList(); - } - return this.sourceServices; - } - - public void setSourceServices(List sourceServices) { - this.sourceServices = sourceServices; - } - - //Destination services. - public Set getDestServices() { - if(destServices==null) - { - destServices= new HashSet(); - } - return this.destServices; - } - - public void setDestServices(Set destServices) { - this.destServices = destServices; - } - - //Action - public String getAction() { - return action; - } - - public void setAction(String value) { - this.action = value; - } - - //description - public String getDescription() { - return description; - } - - public void setDescription(String desc) { - this.description = desc; - } - - //enabled - public boolean getEnabled() { - return enabled; - } - - public void setEnabled(boolean value) { - this.enabled = value; - } - - //Log - public boolean getLog() { - return log; - } - - public void setLog(boolean value) { - this.log = value; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/TermCollector.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/TermCollector.java deleted file mode 100644 index ca7c0dcae..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/TermCollector.java +++ /dev/null @@ -1,145 +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.rest.adapter; - - - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - - -public class TermCollector { - private String serviceTypeId; - private String configName; - private DeployNowJson deploymentOption; - private String securityZoneId; - private String vendorServiceId; - private VendorSpecificData vendorSpecificData= new VendorSpecificData(); - - protected Set serviceGroups; - protected Set addressGroups; - protected List firewallRuleList; - - protected List ruleToTag; - - public List getRuleToTag() { - return ruleToTag; - } - - public void setRuleToTag(List ruleToTag) { - this.ruleToTag = ruleToTag; - } - - //SecurityTypeId - public String getServiceTypeId() { - return serviceTypeId; - } - - public void setServiceTypeId(String serviceTypeId) { - this.serviceTypeId = serviceTypeId; - } - - //ConfigName - public String getConfigName() { - return configName; - } - - public void setConfigName(String configName) { - this.configName = configName; - } - - //DeploymentControl - public DeployNowJson getDeploymentOption() { - return deploymentOption; - } - - public void setDeploymentOption(DeployNowJson deploymentOption) { - this.deploymentOption = deploymentOption; - } - - //SecurityZoneId - public String getSecurityZoneId() { - return securityZoneId; - } - public void setSecurityZoneId(String securityZoneId) { - this.securityZoneId = securityZoneId; - } - - - //ServiceGroup - public Set getServiceGroups() { - if(serviceGroups==null) - { - serviceGroups= new HashSet(); - } - return this.serviceGroups; - } - - public void setServiceGroups(Set servListArray) { - this.serviceGroups = servListArray; - } - - //AddressGroup - public Set getAddressGroups() { - if(addressGroups==null) - { - addressGroups= new HashSet(); - } - return this.addressGroups; - } - - public void setAddressGroups(Set addressGroups) { - this.addressGroups = addressGroups; - } - - //FirewallRuleList - public List getFirewallRuleList() { - - if(firewallRuleList==null) - { - firewallRuleList= new ArrayList(); - } - return this.firewallRuleList; - } - - public void setFirewallRuleList(List firewallRuleList) { - this.firewallRuleList = firewallRuleList; - } - - //vendorServiceId - public String getVendorServiceId() { - return vendorServiceId; - } - - public void setVendorServiceId(String vendorServiceId) { - this.vendorServiceId = vendorServiceId; - } - - public VendorSpecificData getVendorSpecificData() { - return vendorSpecificData; - } - - public void setVendorSpecificData(VendorSpecificData vendorSpecificData) { - this.vendorSpecificData = vendorSpecificData; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/VendorSpecificData.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/VendorSpecificData.java deleted file mode 100644 index c8ca8e95d..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/VendorSpecificData.java +++ /dev/null @@ -1,38 +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.rest.adapter; - -import java.util.ArrayList; -import java.util.List; - -public class VendorSpecificData { - - private List idMap= new ArrayList(); - - public List getIdMap() { - return idMap; - } - - public void setIdMap(List idMap) { - this.idMap = idMap; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java deleted file mode 100644 index 194ba1a88..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/YAMLParams.java +++ /dev/null @@ -1,97 +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.rest.adapter; - -import java.util.List; - -public class YAMLParams { - private String actor; - private String recipe; - private String clname; - private String limit; - private String timeWindow; - private String timeUnits; - private String guardActiveStart; - private String guardActiveEnd; - private List blackList; - private List targets; - - public String getActor() { - return actor; - } - public void setActor(String actor) { - this.actor = actor; - } - public String getRecipe() { - return recipe; - } - public void setRecipe(String recipe) { - this.recipe = recipe; - } - public String getLimit() { - return limit; - } - public void setLimit(String limit) { - this.limit = limit; - } - public String getTimeWindow() { - return timeWindow; - } - public void setTimeWindow(String timeWindow) { - this.timeWindow = timeWindow; - } - public String getGuardActiveStart() { - return guardActiveStart; - } - public void setGuardActiveStart(String guardActiveStart) { - this.guardActiveStart = guardActiveStart; - } - public String getGuardActiveEnd() { - return guardActiveEnd; - } - public void setGuardActiveEnd(String guardActiveEnd) { - this.guardActiveEnd = guardActiveEnd; - } - public List getBlackList() { - return blackList; - } - public void setBlackList(List blackList) { - this.blackList = blackList; - } - public String getClname() { - return clname; - } - public void setClname(String clname) { - this.clname = clname; - } - public String getTimeUnits() { - return timeUnits; - } - public void setTimeUnits(String timeUnits) { - this.timeUnits = timeUnits; - } - public List getTargets() { - return targets; - } - public void setTargets(List targets) { - this.targets = targets; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/package-info.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/package-info.java deleted file mode 100644 index a78bbf203..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/adapter/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.adapter; \ No newline at end of file diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/dao/CommonClassDao.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/dao/CommonClassDao.java deleted file mode 100644 index 3d0da0e6b..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/dao/CommonClassDao.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.dao; - -import java.util.List; - -import org.openecomp.policy.rest.jpa.PolicyRoles; - -public interface CommonClassDao { - - //Common methods - List getData(@SuppressWarnings("rawtypes") Class className); - List getDataById(@SuppressWarnings("rawtypes") Class className, String columnName, String key); - List getDataByColumn(@SuppressWarnings("rawtypes") Class className, String columnName); - List checkDuplicateEntry(String value, String columnName, @SuppressWarnings("rawtypes") Class className); - Object getEntityItem(@SuppressWarnings("rawtypes") Class className, String columnName, String key); - List getDataByQuery(String query); - List getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, String columnName, List data); - void save(Object entity); - void delete(Object entity); - void update(Object entity); - void updateQuery(String query); - - //Group Policy Scope - List checkExistingGroupListforUpdate(String groupListValue, String groupNameValue); - - - //Roles - List getUserRoles(); - - - //ClosedLoops - void updateClAlarms(String clName, String alarms); - void updateClYaml(String clName, String yaml); - void deleteAll(); - - - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/dao/package-info.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/dao/package-info.java deleted file mode 100644 index 84cd76a92..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/dao/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.dao; diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ActionBodyEntity.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ActionBodyEntity.java deleted file mode 100644 index bda58b607..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ActionBodyEntity.java +++ /dev/null @@ -1,195 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Lob; -import javax.persistence.NamedQueries; -import javax.persistence.NamedQuery; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Version; -/* - * The Entity class to persist a policy object Action Body - */ - -import com.fasterxml.jackson.annotation.JsonBackReference; - -@Entity -@Table(name="ActionBodyEntity") -@NamedQueries({ - @NamedQuery(name=" ActionBodyEntity.findAll", query="SELECT e FROM ActionBodyEntity e "), - @NamedQuery(name="ActionBodyEntity.deleteAll", query="DELETE FROM ActionBodyEntity WHERE 1=1") -}) - -public class ActionBodyEntity implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="actionBodyId") - @JsonBackReference - private long actionBodyId; - - @Column(name="actionBodyName", nullable=false, length=255) - private String actionBodyName = ""; - - @Version - @Column(name="version") - private int version; - - @Lob - @Column(name="actionBody", nullable=false, columnDefinition="TEXT") - private String actionBody = "NoBody"; - - @Column(name="created_by", nullable=false, length=255) - private String createdBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Column(name="modified_by", nullable=false, length=255) - private String modifiedBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @Column(name="deleted", nullable=false) - private boolean deleted = false; - - public ActionBodyEntity() { - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - } - /** - * @return the configurationDataId - */ - public long getActionBodyId() { - return actionBodyId; - } - /** - * @param configurationDataId the configurationDataId to set - */ - public void setActionBodyName(String name) { - this.actionBodyName = name; - } - public String getActionBodyName(){ - return this.actionBodyName; - } - - /** - * @return the actionBody - */ - public String getActionBody() { - return actionBody; - } - /** - * @param configBody the configBody to set - */ - public void setActionBody(String body) { - this.actionBody = body; - } - /** - * @return the createdBy - */ - public String getCreatedBy() { - return createdBy; - } - /** - * @param createdBy the createdBy to set - */ - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - /** - * @return the modifiedBy - */ - public String getModifiedBy() { - return modifiedBy; - } - /** - * @param modifiedBy the modifiedBy to set - */ - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - /** - * @return the modifiedDate - */ - public Date getModifiedDate() { - return modifiedDate; - } - /** - * @param modifiedDate the modifiedDate to set - */ - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - /** - * @return the version - */ - public int getVersion() { - return version; - } - /** - * @return the createdDate - */ - public Date getCreatedDate() { - return createdDate; - } - - /** - * @return the deleted - */ - public boolean isDeleted() { - return deleted; - } - - /** - * @param deleted the deleted to set - */ - public void setDeleted(boolean deleted) { - this.deleted = deleted; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ActionList.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ActionList.java deleted file mode 100644 index 0fea71a1c..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ActionList.java +++ /dev/null @@ -1,103 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - -@Entity -@Table(name="actionlist") -@NamedQuery(name="ActionList.findAll", query="SELECT e FROM ActionList e ") -public class ActionList implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="actionname", nullable=false) - @OrderBy("asc") - private String actionName; - - @Column(name="description") - private String description; -/* - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate;*/ - - public ActionList() { - - } - public ActionList(String string, String userid) { - this(domain); - - } - public ActionList(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - public String getActionName() { - return this.actionName; - } - - public void setActionName(String actionName) { - this.actionName = actionName; - - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ActionPolicyDict.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ActionPolicyDict.java deleted file mode 100644 index f6c8965d2..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ActionPolicyDict.java +++ /dev/null @@ -1,211 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQueries; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - - -@Entity -@Table(name="ActionPolicyDict") -@NamedQueries({ - @NamedQuery(name="ActionPolicyDict.findAll", query="SELECT e FROM ActionPolicyDict e") -}) -public class ActionPolicyDict implements Serializable { - private static final long serialVersionUID = 1L; - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="ATTRIBUTE_NAME", nullable=false) - @OrderBy("asc") - private String attributeName; - - @Column(name="Type", nullable=false) - @OrderBy("asc") - private String type; - - @Column(name="URL", nullable=false) - @OrderBy("asc") - private String url; - - @Column(name="Method", nullable=false) - @OrderBy("asc") - private String method; - - @Column(name="Headers", nullable=true) - @OrderBy("asc") - private String header; - - @Column(name="Body", nullable=true) - @OrderBy("asc") - private String body; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - private static Log logger = LogFactory.getLog(ActionPolicyDict.class); - public ActionPolicyDict() { - - } - - public ActionPolicyDict(String string, String userid) { - this(string); - } - - public ActionPolicyDict(String domain) { - this.type = domain; - } - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy =XacmlAdminAuthorization.getUserId();; - } catch (Exception e) { - logger.error("Exception caused While adding Modified by Role"+e); - //PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "ActionPolicyDict", "Exception caused While adding Modified by Role"); - } - } - public int getId() { - return this.id; - } - public void setId(int id) { - this.id = id; - } - - public Date getCreatedDate() { - return this.createdDate; - } - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - public String getDescription() { - return this.description; - } - public void setDescription(String description) { - this.description = description; - } - - public Date getModifiedDate() { - return this.modifiedDate; - } - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - - public String getUrl() { - return url; - } - public void setUrl(String url) { - this.url = url; - } - public String getMethod() { - return method; - } - public void setMethod(String method) { - this.method = method; - } - public String getHeader() { - return header; - } - public void setHeader(String header) { - this.header = header; - } - - public String getBody() { - return body; - } - public void setBody(String body) { - this.body = body; - } - public String getAttributeName() { - return attributeName; - } - public void setAttributeName(String attributeName) { - this.attributeName = attributeName; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/AddressGroup.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/AddressGroup.java deleted file mode 100644 index 1b6430c21..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/AddressGroup.java +++ /dev/null @@ -1,114 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - -@Entity -@Table(name="AddressGroup") -@NamedQuery(name="AddressGroup.findAll", query="SELECT e FROM AddressGroup e ") -public class AddressGroup implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String name; - - @Column(name="prefixlist") - private String prefixList; - - - @Column(name="description") - private String description; - - public AddressGroup() { - - } - public AddressGroup(String string, String userid) { - this(domain); - - } - public AddressGroup(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getGroupName() { - return this.name; - } - - public void setGroupName(String serviceName) { - this.name = serviceName; - - } - - public String getPrefixList() { - return this.prefixList; - } - - public void setServiceList(String prefixList) { - this.prefixList = prefixList; - - } - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Attribute.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Attribute.java deleted file mode 100644 index f9d60ff4d..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Attribute.java +++ /dev/null @@ -1,363 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OneToMany; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Transient; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -/** - * The persistent class for the Attribute database table. - * - */ -@Entity -@Table(name="Attribute") -@NamedQuery(name="Attribute.findAll", query="SELECT a FROM Attribute a order by a.priority asc, a.xacmlId asc") -public class Attribute implements Serializable { - private static final long serialVersionUID = 1L; - private static final Log logger = LogFactory.getLog(Attribute.class); - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - //bi-directional many-to-one association to Category - @ManyToOne - @JoinColumn(name="constraint_type", nullable=true) - @JsonIgnore - private ConstraintType constraintType; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @Column(name="PRIORITY", nullable=true) - @OrderBy("asc") - private String priority; - - @Column(name="ATTRIBUTE_VALUE", nullable=true) - @OrderBy("asc") - private String attributeValue; - - @Column(name="xacml_id", unique = true, nullable=false) - @OrderBy("asc") - private String xacmlId = "urn"; - - //bi-directional many-to-one association to ConstraintValue - @OneToMany(mappedBy="attribute", orphanRemoval=true, cascade=CascadeType.REMOVE) - @JsonIgnore - private Set constraintValues = new HashSet<>(); - - //bi-directional many-to-one association to Category - @ManyToOne - @JoinColumn(name="category") - @JsonIgnore - private Category categoryBean; - - //bi-directional many-to-one association to Datatype - @ManyToOne - @JoinColumn(name="datatype") - private Datatype datatypeBean; - - @Column(name="is_designator", nullable=false) - @JsonIgnore - private char isDesignator = '1'; - - @Column(name="selector_path", nullable=true, length=2048) - private String selectorPath; - - - - @Transient - private String issuer = null; - - @Transient - private boolean mustBePresent = false; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - - public Attribute() { - } - - public Attribute(String domain) { - this.xacmlId = domain; - } - - public Attribute(Attribute copy) { - this(copy.getXacmlId() + ":(0)"); - this.constraintType = copy.getConstraintType(); - this.categoryBean = copy.getCategoryBean(); - this.datatypeBean = copy.getDatatypeBean(); - this.description = copy.getDescription(); - for (ConstraintValue value : copy.getConstraintValues()) { - ConstraintValue newValue = new ConstraintValue(value); - newValue.setAttribute(this); - this.addConstraintValue(newValue); - } - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy = XacmlAdminAuthorization.getUserId(); - } catch (Exception e) { - logger.error("Exception caused While adding Modified by Role"+e); - } - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public ConstraintType getConstraintType() { - return this.constraintType; - } - - public void setConstraintType(ConstraintType constraintType) { - this.constraintType = constraintType; - } - - public Date getCreatedDate() { - return this.createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Date getModifiedDate() { - return this.modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - - public String getXacmlId() { - return this.xacmlId; - } - -/* @Transient - public Identifier getXacmlIdentifier() { - return new IdentifierImpl(this.xacmlId); - }*/ - - public void setXacmlId(String xacmlId) { - this.xacmlId = xacmlId; - } - - public Set getConstraintValues() { - return this.constraintValues; - } - - public void setConstraintValues(Set constraintValues) { - for (ConstraintValue value : this.constraintValues) { - value.setAttribute(this); - } - this.constraintValues = constraintValues; - } - - public ConstraintValue addConstraintValue(ConstraintValue constraintValue) { - if (this.constraintValues == null) { - this.constraintValues = new HashSet<>(); - } - this.constraintValues.add(constraintValue); - constraintValue.setAttribute(this); - - return constraintValue; - } - - public ConstraintValue removeConstraintValue(ConstraintValue constraintValue) { - this.constraintValues.remove(constraintValue); - constraintValue.setAttribute(null); - - return constraintValue; - } - - public void removeAllConstraintValues() { - if (this.constraintValues == null) { - return; - } - for (ConstraintValue value : this.constraintValues) { - value.setAttribute(null); - } - this.constraintValues.clear(); - } - - public Category getCategoryBean() { - return this.categoryBean; - } - - public void setCategoryBean(Category categoryBean) { - this.categoryBean = categoryBean; - } - - public Datatype getDatatypeBean() { - return this.datatypeBean; - } - - public void setDatatypeBean(Datatype datatypeBean) { - this.datatypeBean = datatypeBean; - } - - public char getIsDesignator() { - return this.isDesignator; - } - - public void setIsDesignator(char is) { - this.isDesignator = is; - } - - public String getSelectorPath() { - return this.selectorPath; - } - - public void setSelectorPath(String path) { - this.selectorPath = path; - } - - @Transient - public String getIssuer() { - return issuer; - } - - @Transient - public void setIssuer(String issuer) { - this.issuer = issuer; - } - - @Transient - public boolean isMustBePresent() { - return mustBePresent; - } - - @Transient - public void setMustBePresent(boolean mustBePresent) { - this.mustBePresent = mustBePresent; - } - - @Transient - public boolean isDesignator() { - return (this.isDesignator == '1'); - } - - @Transient - public void setIsDesignator(boolean is) { - if (is) { - this.isDesignator = '1'; - } else { - this.isDesignator = '0'; - } - } - - public String getPriority() { - return priority; - } - - public void setPriority(String priority) { - this.priority = priority; - } - - public String getAttributeValue() { - return attributeValue; - } - - public void setAttributeValue(String attributeValue) { - this.attributeValue = attributeValue; - } -} - diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/AttributeAssignment.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/AttributeAssignment.java deleted file mode 100644 index 1e81213d3..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/AttributeAssignment.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -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.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.Table; - - -/** - * The persistent class for the ObadviceExpressions database table. - * - */ -@Entity -@Table(name="AttributeAssignment") -@NamedQuery(name="AttributeAssignment.findAll", query="SELECT a FROM AttributeAssignment a") -public class AttributeAssignment implements Serializable { - private static final long serialVersionUID = 1L; - - public static final String EXPRESSION_APPLY = "Apply"; - public static final String EXPRESSION_SELECTOR = "AttributeSelector"; - public static final String EXPRESSION_VALUE = "AttributeValue"; - public static final String EXPRESSION_FUNCTION = "Function"; - public static final String EXPRESSION_REFERENCE = "VarableReference"; - public static final String EXPRESSION_DESIGNATOR = "AttributeDesignator"; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="attribute_id") - private int attributeId; - - //bi-directional many-to-one association to Obadvice - @Column(name="expression", nullable=false) - private String expression; - - //bi-directional many-to-one association to Obadvice - @ManyToOne - private Obadvice obadvice; - - public AttributeAssignment() { - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public int getAttributeId() { - return this.attributeId; - } - - public void setAttributeId(int attributeId) { - this.attributeId = attributeId; - } - - public String getExpression() { - return expression; - } - - public void setExpression(String expression) { - this.expression = expression; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/BRMSController.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/BRMSController.java deleted file mode 100644 index afa6d94cf..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/BRMSController.java +++ /dev/null @@ -1,154 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="BRMSController") -@NamedQuery(name="BRMSController.findAll", query="SELECT b from BRMSController b ") -public class BRMSController implements Serializable{ - private static final long serialVersionUID = -8666947569754164177L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="controller_name", nullable=false, length=1024, unique=true) - @OrderBy("asc") - private String controllerName; - - @Column(name="description", nullable=true, length=1024) - private String description; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - @Column(name="controller", nullable=false) - private String controller; - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Date getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public Date getModifiedDate() { - return modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - public String getController() { - return controller; - } - - public void setController(String controller) { - this.controller = controller; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getControllerName() { - return controllerName; - } - - public void setControllerName(String controllerName) { - this.controllerName = controllerName; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/BRMSDependency.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/BRMSDependency.java deleted file mode 100644 index 9c4406948..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/BRMSDependency.java +++ /dev/null @@ -1,153 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -@Entity -@Table(name="BRMSDependency") -@NamedQuery(name="BRMSDependency.findAll", query="SELECT b from BRMSDependency b ") -public class BRMSDependency implements Serializable{ - private static final long serialVersionUID = -7005622785653160761L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="dependency_name", nullable=false, length=1024, unique=true) - @OrderBy("asc") - private String dependencyName; - - @Column(name="description", nullable=true, length=1024) - private String description; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - @Column(name="dependency", nullable=false) - private String dependency; - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Date getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public Date getModifiedDate() { - return modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - public String getDependency() { - return dependency; - } - - public void setDependency(String dependency) { - this.dependency = dependency; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getDependencyName() { - return dependencyName; - } - - public void setDependencyName(String dependencyName) { - this.dependencyName = dependencyName; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/BRMSParamTemplate.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/BRMSParamTemplate.java deleted file mode 100644 index 54661de0c..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/BRMSParamTemplate.java +++ /dev/null @@ -1,142 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.Lob; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.openecomp.policy.rest.jpa.UserInfo; - -/* - * JPA for the BRMS Param Template. - * - * @version: 0.1 - */ - - -@Entity -@Table(name="BRMSParamTemplate") -@NamedQuery(name="BRMSParamTemplate.findAll", query="SELECT b FROM BRMSParamTemplate b ") -public class BRMSParamTemplate implements Serializable{ - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="param_template_name", nullable=false, unique=true) - @OrderBy("asc") - private String ruleName; - - @Lob - @Column(name="rule",nullable=false) - private String rule; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public BRMSParamTemplate(){ - } - - public BRMSParamTemplate(String userid){ - - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - - public Date getCreatedDate() { - return this.createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getRule(){ - return this.rule; - } - - public void setRule(String rule){ - this.rule = rule; - } - - public String getRuleName(){ - return this.ruleName; - } - - public void setRuleName(String ruleName){ - this.ruleName = ruleName; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Category.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Category.java deleted file mode 100644 index 1f4243304..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Category.java +++ /dev/null @@ -1,218 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -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.OneToMany; -import javax.persistence.Table; -import javax.persistence.Transient; - -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.IdentifierImpl; -import com.fasterxml.jackson.annotation.JsonBackReference; - - -/** - * The persistent class for the Categories database table. - * - */ -@Entity -@Table(name="Category") -@NamedQuery(name="Category.findAll", query="SELECT c FROM Category c") -public class Category implements Serializable { - private static final long serialVersionUID = 1L; - - public static final char STANDARD = 'S'; - public static final char CUSTOM = 'C'; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="grouping", nullable=false, length=64) - private String grouping; - - @Column(name="is_standard", nullable=false) - private char isStandard; - - @Column(name="xacml_id", nullable=false, unique=true, length=255) - private String xacmlId; - - @Column(name="short_name", nullable=false, length=64) - private String shortName; - - //bi-directional many-to-one association to Attribute - @OneToMany(mappedBy="categoryBean") - @JsonBackReference - private Set attributes = new HashSet<>(); - - public Category() { - this.xacmlId = XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue(); - this.grouping = "subject"; - this.isStandard = Category.STANDARD; - this.shortName = "subject"; - } - - public Category(Identifier cat, String grouping, char isStandard) { - if (cat != null) { - this.xacmlId = cat.stringValue(); - } - this.isStandard = isStandard; - if (grouping != null) { - this.grouping = grouping; - } else { - this.grouping = Category.extractGrouping(this.xacmlId); - } - } - - public Category(Identifier cat, String grouping) { - this(cat, grouping, Category.STANDARD); - } - - public Category(Identifier cat, char standard) { - this(cat, null, standard); - } - - public Category(Identifier cat) { - this(cat, Category.STANDARD); - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getGrouping() { - return this.grouping; - } - - public void setGrouping(String grouping) { - this.grouping = grouping; - } - - public char getIsStandard() { - return this.isStandard; - } - - public void setIsStandard(char isStandard) { - this.isStandard = isStandard; - } - - public String getXacmlId() { - return this.xacmlId; - } - - public void setXacmlId(String xacmlId) { - this.xacmlId = xacmlId; - } - - public String getShortName() { - return this.shortName; - } - - public void setShortName(String shortName) { - this.shortName = shortName; - } - - public Set getAttributes() { - return this.attributes; - } - - public void setAttributes(Set attributes) { - this.attributes = attributes; - } - - public Attribute addAttribute(Attribute attribute) { - getAttributes().add(attribute); - attribute.setCategoryBean(this); - - return attribute; - } - - public Attribute removeAttribute(Attribute attribute) { - getAttributes().remove(attribute); - attribute.setCategoryBean(null); - - return attribute; - } - - @Transient - public boolean isStandard() { - return (this.isStandard == Category.STANDARD); - } - - @Transient - public boolean isCustom() { - return (this.isStandard == Category.CUSTOM); - } - - @Transient - public static String extractGrouping(String xacmlId) { - if (xacmlId == null) { - return null; - } - if (xacmlId.matches(".*:attribute\\-category:.*")) { - String[] parts = xacmlId.split("[:]"); - if (parts != null && parts.length > 0) { - return parts[parts.length - 1]; - } - } else if (xacmlId.matches(".*:[a-zA-Z]+[\\-]category:.*")) { - String[] parts = xacmlId.split("[:]"); - if (parts != null && parts.length > 0) { - for (String part : parts) { - int index = part.indexOf("-category"); - if (index > 0) { - return part.substring(0, index); - } - } - } - } - return null; - } - - @Transient - public Identifier getIdentifer() { - return new IdentifierImpl(this.xacmlId); - } - - @Transient - @Override - public String toString() { - return "Category [id=" + id + ", grouping=" + grouping - + ", isStandard=" + isStandard + ", xacmlId=" + xacmlId - + ", attributes=" + attributes + "]"; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ClosedLoopD2Services.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ClosedLoopD2Services.java deleted file mode 100644 index 391ed9714..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ClosedLoopD2Services.java +++ /dev/null @@ -1,175 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - * - */ -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - - -@Entity -@Table(name = "ClosedLoopD2Services") -@NamedQuery(name="ClosedLoopD2Services.findAll", query="SELECT c FROM ClosedLoopD2Services c ") -public class ClosedLoopD2Services implements Serializable{ - private static final long serialVersionUID = 1L; - - private static String domain; - - - @Id - @Column(name ="id") - @GeneratedValue(strategy = GenerationType.AUTO) - private int id; - - @Column(name="service_Name", nullable=false, unique=true) - @OrderBy("asc") - private String serviceName; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - private static Log LOGGER = LogFactory.getLog(ClosedLoopD2Services.class); - - public ClosedLoopD2Services(){ - - } - - public ClosedLoopD2Services(String string, String userid) { - this(domain); - } - - public ClosedLoopD2Services(String domain) { - this.serviceName = domain; - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy = XacmlAdminAuthorization.getUserId();; - } catch (Exception e) { - LOGGER.error("Exception caused While adding Modified by Role"+e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "ClosedLoopD2Services", "Exception caused While adding Modified by Role"); - } - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getServiceName() { - return serviceName; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Date getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public Date getModifiedDate() { - return modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ClosedLoopSite.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ClosedLoopSite.java deleted file mode 100644 index fd8b295b9..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ClosedLoopSite.java +++ /dev/null @@ -1,177 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -/* - * - */ -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - - -@Entity -@Table(name = "ClosedLoopSite") -@NamedQuery(name="ClosedLoopSite.findAll", query="SELECT c FROM ClosedLoopSite c ") -public class ClosedLoopSite implements Serializable{ - private static final long serialVersionUID = 1L; - - private static String domain; - - - @Id - @Column(name ="id") - @GeneratedValue(strategy = GenerationType.AUTO) - private int id; - - @Column(name="site_Name", nullable=false, unique=true) - @OrderBy("asc") - private String siteName; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - private static Log LOGGER = LogFactory.getLog(ClosedLoopSite.class); - - public ClosedLoopSite(){ - - } - - public ClosedLoopSite(String string, String userid) { - this(domain); - } - - public ClosedLoopSite(String domain) { - this.siteName = domain; - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy = XacmlAdminAuthorization.getUserId();; - } catch (Exception e) { - LOGGER.error("Exception caused While adding Modified by Role"+e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "ClosedLoopSite", "Exception caused While adding Modified by Role"); - } - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getSiteName() { - return siteName; - } - - public void setSiteName(String siteName) { - this.siteName = siteName; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Date getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public Date getModifiedDate() { - return modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ClosedLoops.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ClosedLoops.java deleted file mode 100644 index 5732832c6..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ClosedLoops.java +++ /dev/null @@ -1,99 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -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.NamedQueries; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.Table; - -@Entity -@Table(name="ClosedLoops") -@NamedQueries({ - @NamedQuery(name="ClosedLoops.findAll", query="SELECT e FROM ClosedLoops e"), - @NamedQuery(name="ClosedLoops.deleteAll", query="DELETE FROM ClosedLoops WHERE 1=1") -}) -public class ClosedLoops implements Serializable { - - /** - * - */ - private static final long serialVersionUID = -7796845092457926842L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="closedLoopControlName", nullable=false, length=255) - @OrderBy("asc") - private String closedLoopControlName; - - @Column(name="alarmConditions", nullable=true, length=255) - private String alarmConditions; - - @Column(name="yaml", nullable=true, length=1028) - private String yaml; - - public ClosedLoops() { - - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getClosedLoopControlName() { - return closedLoopControlName; - } - - public void setClosedLoopControlName(String closedLoopControlName) { - this.closedLoopControlName = closedLoopControlName; - } - - public String getAlarmConditions() { - return alarmConditions; - } - - public void setAlarmConditions(String alarmConditions) { - this.alarmConditions = alarmConditions; - } - - public String getYaml() { - return yaml; - } - - public void setYaml(String yaml) { - this.yaml = yaml; - } - -} \ No newline at end of file diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ConfigurationDataEntity.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ConfigurationDataEntity.java deleted file mode 100644 index bf42a7788..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ConfigurationDataEntity.java +++ /dev/null @@ -1,224 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Lob; -import javax.persistence.NamedQueries; -import javax.persistence.NamedQuery; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Version; -/* - * The Entity class to persist a policy object configuration data - */ - -import com.fasterxml.jackson.annotation.JsonBackReference; - -@Entity -@Table(name="ConfigurationDataEntity") -@NamedQueries({ - @NamedQuery(name="ConfigurationDataEntity.findAll", query="SELECT e FROM ConfigurationDataEntity e "), - @NamedQuery(name="ConfigurationDataEntity.deleteAll", query="DELETE FROM ConfigurationDataEntity WHERE 1=1") -}) - -public class ConfigurationDataEntity implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="configurationDataId") - @JsonBackReference - private long configurationDataId; - - @Column(name="configurationName", nullable=false, length=255) - private String configurationName = ""; - - @Version - @Column(name="version") - private int version; - - @Column(name="configType", nullable=false, length=255) - private String configType = "NoType"; - - @Lob - @Column(name="configBody", nullable=false, columnDefinition="TEXT") - private String configBody = "NoBody"; - - @Column(name="created_by", nullable=false, length=255) - private String createdBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Column(name="description", nullable=false, length=2048) - private String description = "NoDescription"; - - @Column(name="modified_by", nullable=false, length=255) - private String modifiedBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @Column(name="deleted", nullable=false) - private boolean deleted = false; - - public ConfigurationDataEntity() { - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - } - /** - * @return the configurationDataId - */ - public long getConfigurationDataId() { - return configurationDataId; - } - /** - * @param configurationDataId the configurationDataId to set - */ - public void setConfigurationName(String configurationName) { - this.configurationName = configurationName; - } - public String getConfigurationName(){ - return this.configurationName; - } - /** - * @return the configType - */ - public String getConfigType() { - return configType; - } - /** - * @param configType the configType to set - */ - public void setConfigType(String configType) { - this.configType = configType; - } - /** - * @return the configBody - */ - public String getConfigBody() { - return configBody; - } - /** - * @param configBody the configBody to set - */ - public void setConfigBody(String configBody) { - this.configBody = configBody; - } - /** - * @return the createdBy - */ - public String getCreatedBy() { - return createdBy; - } - /** - * @param createdBy the createdBy to set - */ - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - /** - * @return the description - */ - public String getDescription() { - return description; - } - /** - * @param description the description to set - */ - public void setDescription(String description) { - this.description = description; - } - /** - * @return the modifiedBy - */ - public String getModifiedBy() { - return modifiedBy; - } - /** - * @param modifiedBy the modifiedBy to set - */ - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - /** - * @return the modifiedDate - */ - public Date getModifiedDate() { - return modifiedDate; - } - /** - * @param modifiedDate the modifiedDate to set - */ - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - /** - * @return the version - */ - public int getVersion() { - return version; - } - /** - * @return the createdDate - */ - public Date getCreatedDate() { - return createdDate; - } - - /** - * @return the deleted - */ - public boolean isDeleted() { - return deleted; - } - - /** - * @param deleted the deleted to set - */ - public void setDeleted(boolean deleted) { - this.deleted = deleted; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ConstraintType.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ConstraintType.java deleted file mode 100644 index 60923d5a8..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ConstraintType.java +++ /dev/null @@ -1,121 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -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.OneToMany; -import javax.persistence.Table; - -@Entity -@Table(name="ConstraintType") -@NamedQuery(name="ConstraintType.findAll", query="SELECT a FROM ConstraintType a") -public class ConstraintType implements Serializable { - private static final long serialVersionUID = 1L; - - public static final String ENUMERATION_TYPE = "Enumeration"; - public static final String RANGE_TYPE = "Range"; - public static final String REGEXP_TYPE = "Regular Expression"; - - protected static final Map defaults = new HashMap<>(); - static { - defaults.put(ENUMERATION_TYPE, "Enumerate a set of values that the attribute may be set to during policy creation."); - defaults.put(RANGE_TYPE, "Set a range of min and/or max integer/double values the attribute can be set to during policy creation."); - defaults.put(REGEXP_TYPE, "Define a regular expression the attribute must match against during policy creation."); - } - private static final String[] RANGE_TYPES = {"minExclusive", "minInclusive", "maxExclusive", "maxInclusive"}; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="constraint_type", nullable=false, length=64) - private String constraintType; - - @Column(name="description", nullable=false, length=255) - private String description; - - //bi-directional many-to-one association to Attribute - @OneToMany(mappedBy="constraintType") - private Set attributes = new HashSet<>(); - - public ConstraintType() { - - } - - public ConstraintType(String constraintType) { - this(); - this.constraintType = constraintType; - } - - public ConstraintType(String constraintType, String description) { - this(constraintType); - this.description = description; - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getConstraintType() { - return constraintType; - } - - public void setConstraintType(String constraintType) { - this.constraintType = constraintType; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Set getAttributes() { - return attributes; - } - - public void setAttributes(Set attributes) { - this.attributes = attributes; - } - - public static String[] getRangeTypes() { - return RANGE_TYPES; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ConstraintValue.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ConstraintValue.java deleted file mode 100644 index 65eb6586a..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ConstraintValue.java +++ /dev/null @@ -1,116 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -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.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.Table; - - -/** - * The persistent class for the ConstraintValues database table. - * - */ -@Entity -@Table(name="ConstraintValues") -@NamedQuery(name="ConstraintValue.findAll", query="SELECT c FROM ConstraintValue c") -public class ConstraintValue implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="property") - private String property; - - @Column(name="value") - private String value; - - //bi-directional many-to-one association to Attribute - @ManyToOne - @JoinColumn(name="attribute_id") - private Attribute attribute; - - public ConstraintValue() { - } - - public ConstraintValue(String property, String value) { - this.property = property; - this.value = value; - } - - public ConstraintValue(ConstraintValue value) { - this.property = value.getProperty(); - this.value = value.getValue(); - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getProperty() { - return this.property; - } - - public void setProperty(String property) { - this.property = property; - } - - public String getValue() { - return this.value; - } - - public void setValue(String value) { - this.value = value; - } - - public Attribute getAttribute() { - return this.attribute; - } - - public void setAttribute(Attribute attribute) { - this.attribute = attribute; - } - - public ConstraintValue clone() { - ConstraintValue constraint = new ConstraintValue(); - - constraint.property = this.property; - constraint.value = this.value; - constraint.attribute = this.attribute; - - return constraint; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DCAEUsers.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DCAEUsers.java deleted file mode 100644 index fdad24419..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DCAEUsers.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - - -@Entity -@Table(name="DCAEUsers") -@NamedQuery(name="DCAEUsers.findAll", query="SELECT e FROM DCAEUsers e ") -public class DCAEUsers implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String name; - - @Column(name="description ") - private String description ; - - - public DCAEUsers() { - - } - public DCAEUsers(String string, String userid) { - this(domain); - - } - public DCAEUsers(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - - } - public String getDescriptionValue() { - return this.description ; - } - - public void setDescriptionValue(String description ) { - this.description = description ; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DCAEuuid.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DCAEuuid.java deleted file mode 100644 index 9e7225fc7..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DCAEuuid.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - - -@Entity -@Table(name="DCAEuuid") -@NamedQuery(name="DCAEuuid.findAll", query="SELECT e FROM DCAEuuid e ") -public class DCAEuuid implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String name; - - @Column(name="description") - private String description; - - - public DCAEuuid() { - - } - public DCAEuuid(String string, String userid) { - this(domain); - - } - public DCAEuuid(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DatabaseLockEntity.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DatabaseLockEntity.java deleted file mode 100644 index c24b13a0e..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DatabaseLockEntity.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name="DatabaseLockEntity") -public class DatabaseLockEntity implements Serializable { - private static final long serialVersionUID = 1L; - @Id - @Column(name="lock_key") - private int lock_key = 1; - public DatabaseLockEntity(){ - - } - public int getKey(){ - return lock_key; - } - public void setKey(int key){ - this.lock_key = key; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Datatype.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Datatype.java deleted file mode 100644 index 05e4fbc0c..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Datatype.java +++ /dev/null @@ -1,244 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.HashSet; -import java.util.Set; - -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.OneToMany; -import javax.persistence.Table; -import javax.persistence.Transient; - -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.std.IdentifierImpl; -import com.fasterxml.jackson.annotation.JsonBackReference; -import com.fasterxml.jackson.annotation.JsonIgnore; - - -/** - * The persistent class for the Datatype database table. - * - */ -@Entity -@Table(name="Datatype") -@NamedQuery(name="Datatype.findAll", query="SELECT d FROM Datatype d") -public class Datatype implements Serializable { - private static final long serialVersionUID = 1L; - - public static final char STANDARD = 'S'; - public static final char CUSTOM = 'C'; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="is_standard", nullable=false) - private char isStandard; - - @Column(name="xacml_id", nullable=false, unique=true, length=255) - private String xacmlId; - - @Column(name="short_name", nullable=false, length=64) - private String shortName; - - //bi-directional many-to-one association to Attribute - @OneToMany(mappedBy="datatypeBean") - @JsonBackReference - private Set attributes = new HashSet<>(); - - //bi-directional many-to-one association to Attribute - @OneToMany(mappedBy="datatypeBean") - @JsonIgnore - private Set functions = new HashSet<>(); - - //bi-directional many-to-one association to Attribute - @OneToMany(mappedBy="datatypeBean") - @JsonIgnore - private Set arguments = new HashSet<>(); - - public Datatype() { - this.xacmlId = XACML3.ID_DATATYPE_STRING.stringValue(); - this.isStandard = Datatype.STANDARD; - } - - - public Datatype(int id, Datatype dt) { - this.id = id; - this.isStandard = dt.isStandard; - this.xacmlId = dt.xacmlId; - this.shortName = dt.shortName; - // - // Make a copy? - // - this.attributes = new HashSet<>(); - } - - public Datatype(Identifier identifier, char standard) { - if (identifier != null) { - this.xacmlId = identifier.stringValue(); - - } - this.isStandard = standard; - } - - public Datatype(Identifier identifier) { - this(identifier, Datatype.STANDARD); - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public char getIsStandard() { - return this.isStandard; - } - - public void setIsStandard(char isStandard) { - this.isStandard = isStandard; - } - - public String getXacmlId() { - return this.xacmlId; - } - - public void setXacmlId(String xacmlId) { - this.xacmlId = xacmlId; - } - - public String getShortName() { - return shortName; - } - - public void setShortName(String shortName) { - this.shortName = shortName; - } - - public Set getAttributes() { - return this.attributes; - } - - public void setAttributes(Set attributes) { - this.attributes = attributes; - } - - public Attribute addAttribute(Attribute attribute) { - getAttributes().add(attribute); - attribute.setDatatypeBean(this); - - return attribute; - } - - public Attribute removeAttribute(Attribute attribute) { - getAttributes().remove(attribute); - attribute.setDatatypeBean(null); - - return attribute; - } - - public Set getFunctions() { - return this.functions; - } - - public void setFunctions(Set functions) { - this.functions = functions; - } - - public FunctionDefinition addFunction(FunctionDefinition function) { - getFunctions().add(function); - function.setDatatypeBean(this); - - return function; - } - - public FunctionDefinition removeAttribute(FunctionDefinition function) { - getFunctions().remove(function); - function.setDatatypeBean(null); - - return function; - } - - public Set getArguments() { - return this.arguments; - } - - public void setArguments(Set argument) { - this.arguments = argument; - } - - public FunctionArgument addArgument(FunctionArgument argument) { - getArguments().add(argument); - argument.setDatatypeBean(this); - - return argument; - } - - public FunctionArgument removeArgument(FunctionArgument argument) { - getArguments().remove(argument); - argument.setDatatypeBean(null); - - return argument; - } - - @Transient - public Identifier getIdentifer() { - return new IdentifierImpl(this.xacmlId); - } - - @Transient - public Identifier getIdentiferByShortName() { - return new IdentifierImpl(this.shortName); - } - - @Transient - public boolean isStandard() { - return (this.isStandard == Datatype.STANDARD); - } - - @Transient - public boolean isCustom() { - return (this.isStandard == Datatype.CUSTOM); - } - - @Transient - @Override - public String toString() { - return "Datatype [id=" + id + ", isStandard=" + isStandard - + ", xacmlId=" + xacmlId + ", shortName=" + shortName - + ", attributes=" + attributes + ", functions=" + functions - + ", arguments=" + arguments + "]"; - - //return "Datatype [shortName=" + shortName + "]"; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DecisionSettings.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DecisionSettings.java deleted file mode 100644 index 2d3e5b58a..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DecisionSettings.java +++ /dev/null @@ -1,235 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Transient; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - - -@Entity -@Table(name="DecisionSettings") -@NamedQuery(name="DecisionSettings.findAll", query="SELECT a FROM DecisionSettings a order by a.priority asc, a.xacmlId asc") -public class DecisionSettings implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @Column(name="PRIORITY", nullable=true) - @OrderBy("asc") - private String priority; - - @Column(name="xacml_id", unique = true, nullable=false) - @OrderBy("asc") - private String xacmlId = "urn"; - - //bi-directional many-to-one association to Datatype - @ManyToOne - @JoinColumn(name="datatype") - private Datatype datatypeBean; - - @Transient - private String issuer = null; - - @Transient - private boolean mustBePresent = false; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - public DecisionSettings() { - } - - public DecisionSettings(String domain) { - this.xacmlId = domain; - } - - public DecisionSettings(String domain, String user) { - this(domain); - } - public DecisionSettings(DecisionSettings copy, String user) { - this(copy.getXacmlId() + ":(0)", user); - this.datatypeBean = copy.getDatatypeBean(); - this.description = copy.getDescription(); - - } - - public String getDecisionSettings(){ - return this.xacmlId; - } - - public String setDecisionSettings(){ - return this.xacmlId; - } - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy = XacmlAdminAuthorization.getUserId();; - } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "DecisionSettings", "Exception caused While adding Modified by Role"); - } - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - - public Date getCreatedDate() { - return this.createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Date getModifiedDate() { - return this.modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - - public String getXacmlId() { - return this.xacmlId; - } - -/* @Transient - public Identifier getXacmlIdentifier() { - return new IdentifierImpl(this.xacmlId); - }*/ - - public void setXacmlId(String xacmlId) { - this.xacmlId = xacmlId; - } - - public Datatype getDatatypeBean() { - return this.datatypeBean; - } - - public void setDatatypeBean(Datatype datatypeBean) { - this.datatypeBean = datatypeBean; - } - - @Transient - public String getIssuer() { - return issuer; - } - - @Transient - public void setIssuer(String issuer) { - this.issuer = issuer; - } - - @Transient - public boolean isMustBePresent() { - return mustBePresent; - } - - @Transient - public void setMustBePresent(boolean mustBePresent) { - this.mustBePresent = mustBePresent; - } - - public String getPriority() { - return priority; - } - - public void setPriority(String priority) { - this.priority = priority; - } -} - diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DescriptiveScope.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DescriptiveScope.java deleted file mode 100644 index d4719cf41..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/DescriptiveScope.java +++ /dev/null @@ -1,181 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - - -@Entity -@Table(name = "DescriptiveScope") -@NamedQuery(name = "DescriptiveScope.findAll", query= "Select p from DescriptiveScope p") -public class DescriptiveScope implements Serializable { - private static final long serialVersionUID = 1L; - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "Id") - private int id; - - @Column(name="scopename", nullable=false) - @OrderBy("asc") - private String descriptiveScopeName; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Column(name="search", nullable=true) - @OrderBy("asc") - private String search; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - private static Log LOGGER = LogFactory.getLog(DescriptiveScope.class); - - public DescriptiveScope(){ - - } - - public DescriptiveScope(String string, String userid) { - this(string); - } - - public DescriptiveScope(String domain) { - this.descriptiveScopeName = domain; - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy =XacmlAdminAuthorization.getUserId();; - } catch (Exception e) { - LOGGER.error("Exception caused While adding Modified by Role"+e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "DescriptiveScope", "Exception caused While adding Modified by Role"); - } - } - - public int getId() { - return this.id; - } - public void setId(int id) { - this.id = id; - } - - public String getScopeName() { - return descriptiveScopeName; - } - - public void setScopeName(String descriptiveScopeName) { - this.descriptiveScopeName = descriptiveScopeName; - } - - public String getSearch() { - return search; - } - - public void setSearch(String search) { - this.search = search; - } - - public Date getCreatedDate() { - return this.createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Date getModifiedDate() { - return this.modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/EcompName.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/EcompName.java deleted file mode 100644 index 09dcd4738..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/EcompName.java +++ /dev/null @@ -1,167 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - - -@Entity -@Table(name="EcompName") -@NamedQuery(name="EcompName.findAll", query="SELECT e FROM EcompName e ") -public class EcompName implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="ecomp_Name", nullable=false, unique=true) - @OrderBy("asc") - private String ecompName; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - public EcompName() { - - } - - public EcompName(String string, String userid) { - this(domain); - } - - public EcompName(String domain) { - this.ecompName = domain; - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy =XacmlAdminAuthorization.getUserId(); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "EcompName", "Exception caused While adding Modified by Role"); - } - } - public String getEcompName() { - return this.ecompName; - } - - public void setEcompName(String ecompName) { - this.ecompName = ecompName; - - } - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public Date getCreatedDate() { - return this.createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Date getModifiedDate() { - return this.modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/EnforcingType.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/EnforcingType.java deleted file mode 100644 index f293bc0cb..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/EnforcingType.java +++ /dev/null @@ -1,96 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; - -import javax.persistence.*; - -/** - * Entity implementation class for Entity: EnforcingType - * - */ -@Entity -@Table(name="EnforcingType") -@NamedQuery(name="EnforcingType.findAll", query="SELECT e FROM EnforcingType e ") -public class EnforcingType implements Serializable { - - - private static final long serialVersionUID = 1L; - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - @Column(name="enforcingType", nullable=false, unique=true) - @OrderBy("asc") - private String enforcingType; - @Column(name="script", nullable=false, length=255) - private String script; - @Column(name="connectionQuery", nullable=false, length=255) - private String connectionQuery; - @Column(name="valueQuery", nullable=false, length=255) - private String valueQuery; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getEnforcingType() { - return enforcingType; - } - - public void setEnforcingType(String enforcingType) { - this.enforcingType = enforcingType; - } - - public String getScript() { - return script; - } - - public void setScript(String script) { - this.script = script; - } - - public String getConnectionQuery() { - return connectionQuery; - } - - public void setConnectionQuery(String connectionQuery) { - this.connectionQuery = connectionQuery; - } - - public String getValueQuery() { - return valueQuery; - } - - public void setValueQuery(String valueQuery) { - this.valueQuery = valueQuery; - } - - public EnforcingType() { - super(); - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FWTag.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FWTag.java deleted file mode 100644 index f10f6662c..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FWTag.java +++ /dev/null @@ -1,180 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - -@Entity -@Table(name = "FWTag") -@NamedQuery(name = "FWTag.findAll", query= "Select p from FWTag p") -public class FWTag implements Serializable { - private static final long serialVersionUID = 1L; - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "Id") - private int id; - - @Column(name="tagName", nullable=false) - @OrderBy("asc") - private String fwTagName; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Column(name="tagValues", nullable=true) - @OrderBy("asc") - private String tagValues; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - private static Log LOGGER = LogFactory.getLog(FWTag.class); - - public FWTag(){ - - } - - public FWTag(String string, String userid) { - this(string); - } - - public FWTag(String domain) { - this.fwTagName = domain; - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy =XacmlAdminAuthorization.getUserId();; - } catch (Exception e) { - LOGGER.error("Exception caused While adding Modified by Role"+e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FWTag", "Exception caused While adding Modified by Role"); - } - } - - public int getId() { - return this.id; - } - public void setId(int id) { - this.id = id; - } - - public String getFwTagName() { - return fwTagName; - } - - public void setFwTagName(String fwTagName) { - this.fwTagName = fwTagName; - } - - public String getTagValues() { - return tagValues; - } - - public void setTagValues(String tagValues) { - this.tagValues = tagValues; - } - - - public Date getCreatedDate() { - return this.createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Date getModifiedDate() { - return this.modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FWTagPicker.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FWTagPicker.java deleted file mode 100644 index 032f77f3c..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FWTagPicker.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - -@Entity -@Table(name = "FWTagPicker") -@NamedQuery(name = "FWTagPicker.findAll", query= "Select p from FWTagPicker p") -public class FWTagPicker implements Serializable { - private static final long serialVersionUID = 1L; - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "Id") - private int id; - - @Column(name="tagPickerName", nullable=false) - @OrderBy("asc") - private String tagPickerName; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Column(name="networkRole", nullable=true) - private String networkRole; - - @Column(name="tags", nullable=true) - @OrderBy("asc") - private String tagValues; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - private static Log logger = LogFactory.getLog(FWTagPicker.class); - - public FWTagPicker(){ - - } - - public FWTagPicker(String string, String userid) { - this(string); - } - - public FWTagPicker(String domain) { - this.tagPickerName = domain; - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy =XacmlAdminAuthorization.getUserId(); - } catch (Exception e) { - logger.error("Exception caused While adding Modified by Role"+e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "DescriptiveScope", "Exception caused While adding Modified by Role"); - } - } - - public int getId() { - return this.id; - } - public void setId(int id) { - this.id = id; - } - - public String getTagPickerName() { - return tagPickerName; - } - - public void setTagPickerName(String tagPickerName) { - this.tagPickerName = tagPickerName; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getNetworkRole() { - return networkRole; - } - - public void setNetworkRole(String networkRole) { - this.networkRole = networkRole; - } - - public String getTagValues() { - return tagValues; - } - - public void setTagValues(String tagValues) { - this.tagValues = tagValues; - } - - public Date getCreatedDate() { - return this.createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public Date getModifiedDate() { - return this.modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FirewallDictionaryList.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FirewallDictionaryList.java deleted file mode 100644 index 712172acb..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FirewallDictionaryList.java +++ /dev/null @@ -1,164 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -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.OrderBy; -import javax.persistence.Table; - - -@Entity -@Table(name="parentdictionaryitems") -@NamedQuery(name="FirewallDictionaryList.findAll", query="SELECT e FROM FirewallDictionaryList e") -public class FirewallDictionaryList implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="parentItemName", nullable=false) - @OrderBy("asc") - private String parentItemName; - - @Column(name="description") - private String description; - - @Column(name="addressList") - private String addressList; - - @Column(name="serviceList") - private String serviceList; - -/* @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy;*/ - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getParentItemName() { - return parentItemName; - } - - public String getDescription() { - return description; - } - - public String getAddressList() { - return addressList; - } - - public String getServiceList() { - return serviceList; - } - - public void setParentItemName(String parentItemName) { - this.parentItemName = parentItemName; - } - - public void setDescription(String description) { - this.description = description; - } - - public void setAddressList(String addressList) { - this.addressList = addressList; - } - - public void setServiceList(String serviceList) { - this.serviceList = serviceList; - } - - - /*public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - }*/ - - public FirewallDictionaryList() { - - } - - public FirewallDictionaryList(String string, String userid) { - this(domain); - } - public FirewallDictionaryList(String domain) { - this.parentItemName = domain; - } - - /*@PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - auditLogger.debug("Added New Term Name: "+this.parentItemName+" by "+this.userCreatedBy); - - } - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy =XacmlAdminAuthorization.getUserId();; - } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "TermList", "Exception caused While adding Modified by Role"); - } - auditLogger.debug("Updated Term Name: "+this.parentItemName+" by "+this.userModifiedBy); - } -*/ -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FunctionArgument.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FunctionArgument.java deleted file mode 100644 index c660fde06..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FunctionArgument.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; - -import javax.persistence.*; - - -/** - * The persistent class for the FunctionArguments database table. - * - */ -@Entity -@Table(name="FunctionArguments") -@NamedQuery(name="FunctionArgument.findAll", query="SELECT f FROM FunctionArgument f") -public class FunctionArgument implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy=GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="is_bag", nullable=false) - private int isBag; - - //bi-directional many-to-one association to FunctionDefinition - @ManyToOne - @JoinColumn(name="function_id") - private FunctionDefinition functionDefinition; - - @Column(name="arg_index", nullable=false) - private int argIndex; - - //bi-directional many-to-one association to Datatype - @ManyToOne - @JoinColumn(name="datatype_id") - private Datatype datatypeBean; - - public FunctionArgument() { - } - - public FunctionArgument(final FunctionArgument argument) { - this.argIndex = argument.argIndex; - this.datatypeBean = argument.datatypeBean; - this.isBag = argument.isBag; - this.functionDefinition = argument.functionDefinition; - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public int getArgIndex() { - return this.argIndex; - } - - public void setArgIndex(int argIndex) { - this.argIndex = argIndex; - } - - public Datatype getDatatypeBean() { - return this.datatypeBean; - } - - public void setDatatypeBean(Datatype datatypeBean) { - this.datatypeBean = datatypeBean; - } - - public FunctionDefinition getFunctionDefinition() { - return this.functionDefinition; - } - - public int getIsBag() { - return isBag; - } - - public void setIsBag(int isBag) { - this.isBag = isBag; - } - - public void setFunctionDefinition(FunctionDefinition functionDefinition) { - this.functionDefinition = functionDefinition; - } - - @Transient - @Override - public String toString() { - return "FunctionArgument [id=" + id + ", argIndex=" + argIndex - + ", datatypeBean=" + datatypeBean + ", isBag=" + isBag - + ", functionDefinition=" + functionDefinition + "]"; - } - - @Transient - public boolean isBag() { - return this.isBag == 1; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FunctionDefinition.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FunctionDefinition.java deleted file mode 100644 index c0ccef99a..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/FunctionDefinition.java +++ /dev/null @@ -1,219 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; - -import javax.persistence.*; - -import java.util.List; - - -/** - * The persistent class for the FunctionDefinition database table. - * - */ -@Entity -@Table(name="FunctionDefinition") -@NamedQueries({ - @NamedQuery(name="FunctionDefinition.findAll", query="SELECT f FROM FunctionDefinition f") -}) -public class FunctionDefinition implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy=GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="short_name", nullable=false, length=64) - private String shortname; - - @Column(name="xacml_id", nullable=false, length=255) - private String xacmlid; - - //bi-directional many-to-one association to Datatype - @ManyToOne - @JoinColumn(name="return_datatype", nullable=true) - private Datatype datatypeBean; - - @Column(name="is_bag_return", nullable=false) - private Integer isBagReturn; - - @Column(name="is_higher_order", nullable=false) - private Integer isHigherOrder; - - @Column(name="arg_lb", nullable=false) - private Integer argLb; - - @Column(name="arg_ub", nullable=false) - private Integer argUb; - - @Column(name="ho_arg_lb", nullable=true) - private Integer higherOrderArg_LB; - - @Column(name="ho_arg_ub", nullable=true) - private Integer higherOrderArg_UB; - - @Column(name="ho_primitive", nullable=true) - private Character higherOrderIsPrimitive; - - //bi-directional many-to-one association to FunctionArgument - @OneToMany(mappedBy="functionDefinition") - private List functionArguments; - - public FunctionDefinition() { - } - - public int getId() { - return this.id; - } - - public void setId(Integer id) { - this.id = id; - } - - public int getArgLb() { - return this.argLb; - } - - public void setArgLb(Integer argLb) { - this.argLb = argLb; - } - - public int getArgUb() { - return this.argUb; - } - - public void setArgUb(Integer argUb) { - this.argUb = argUb; - } - - public int getIsBagReturn() { - return isBagReturn; - } - - public void setIsBagReturn(Integer isBagReturn) { - this.isBagReturn = isBagReturn; - } - - public int getIsHigherOrder() { - return isHigherOrder; - } - - public void setIsHigherOrder(Integer isHigherOrder) { - this.isHigherOrder = isHigherOrder; - } - - public Datatype getDatatypeBean() { - return this.datatypeBean; - } - - public void setDatatypeBean(Datatype datatypeBean) { - this.datatypeBean = datatypeBean; - } - - public String getShortname() { - return this.shortname; - } - - public void setShortname(String shortname) { - this.shortname = shortname; - } - - public String getXacmlid() { - return this.xacmlid; - } - - public void setXacmlid(String xacmlid) { - this.xacmlid = xacmlid; - } - - public int getHigherOrderArg_LB() { - return higherOrderArg_LB; - } - - public void setHigherOrderArg_LB(Integer higherOrderArg_LB) { - this.higherOrderArg_LB = higherOrderArg_LB; - } - - public int getHigherOrderArg_UB() { - return higherOrderArg_UB; - } - - public void setHigherOrderArg_UB(Integer higherOrderArg_UB) { - this.higherOrderArg_UB = higherOrderArg_UB; - } - - public Character getHigherOrderIsPrimitive() { - return higherOrderIsPrimitive; - } - - public void setHigherOrderIsPrimitive(Character higherOrderIsPrimitive) { - this.higherOrderIsPrimitive = higherOrderIsPrimitive; - } - - public List getFunctionArguments() { - return this.functionArguments; - } - - public void setFunctionArguments(List functionArguments) { - this.functionArguments = functionArguments; - } - - public FunctionArgument addFunctionArgument(FunctionArgument functionArgument) { - getFunctionArguments().add(functionArgument); - functionArgument.setFunctionDefinition(this); - - return functionArgument; - } - - public FunctionArgument removeFunctionArgument(FunctionArgument functionArgument) { - getFunctionArguments().remove(functionArgument); - functionArgument.setFunctionDefinition(null); - - return functionArgument; - } - - @Transient - @Override - public String toString() { - return "FunctionDefinition [id=" + id + ", argLb=" + argLb + ", argUb=" - + argUb + ", isBagReturn=" + isBagReturn + ", isHigherOrder=" - + isHigherOrder + ", datatypeBean=" + datatypeBean - + ", shortname=" + shortname + ", xacmlid=" + xacmlid - + ", higherOrderArg_LB=" + higherOrderArg_LB - + ", higherOrderArg_UB=" + higherOrderArg_UB - + ", higherOrderIsPrimitive=" + higherOrderIsPrimitive - + ", functionArguments=" + functionArguments + "]"; - } - - @Transient - public boolean isBagReturn() { - return this.isBagReturn == 1; - } - - @Transient - public boolean isHigherOrder() { - return this.isHigherOrder == 1; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GlobalRoleSettings.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GlobalRoleSettings.java deleted file mode 100644 index 5b69cab32..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GlobalRoleSettings.java +++ /dev/null @@ -1,93 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.NamedQuery; -import javax.persistence.Table; - - -/** - * Entity implementation class for Entity: Administration - * - */ -@Entity -@Table(name="GlobalRoleSettings") -@NamedQuery(name="GlobalRoleSettings.findAll", query="SELECT g FROM GlobalRoleSettings g") -public class GlobalRoleSettings implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @Column(name="role", length=45) - private String role; - - @Column(name="lockdown") - private boolean lockdown; - - public GlobalRoleSettings() { - super(); - } - - public GlobalRoleSettings(boolean lockdown) { - this.role = org.openecomp.policy.rest.XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString(); - this.lockdown = lockdown; - } - - /** - * return the role - * - * @return the role - */ - public String getRole() { - return role; - } - - /** - * set role - * - * @param role the role to set - */ - public void setRole(String role) { - this.role = role; - } - - /** - * is the system locked down - * - * @return - */ - public boolean isLockdown() { - return lockdown; - } - - /** - * sets lockdown configuration - * - * @param lockdown - */ - public void setLockdown(boolean lockdown) { - this.lockdown = lockdown; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GroupEntity.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GroupEntity.java deleted file mode 100644 index 405a5d458..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GroupEntity.java +++ /dev/null @@ -1,270 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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========================================================= - */ - -/* - * AT&T - PROPRIETARY - * THIS FILE CONTAINS PROPRIETARY INFORMATION OF - * AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN - * ACCORDANCE WITH APPLICABLE AGREEMENTS. - * - * Copyright (c) 2013 AT&T Knowledge Ventures - * Unpublished and Not for Publication - * All Rights Reserved - */ -package org.openecomp.policy.rest.jpa; -/* - */ -import java.io.Serializable; -import java.util.Date; -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.JoinTable; -import javax.persistence.ManyToMany; -import javax.persistence.NamedQueries; -import javax.persistence.NamedQuery; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Version; - -import com.fasterxml.jackson.annotation.JsonManagedReference; - -/* - * The Entity class to persist a policy object and its configuration data - */ - -/** - * - */ -@Entity -//Add a non-unique index and a constraint that says the combo of policyName and scopeId must be unique -@Table(name="GroupEntity") - -@NamedQueries({ - @NamedQuery(name="GroupEntity.findAll", query="SELECT e FROM GroupEntity e "), - @NamedQuery(name="GroupEntity.deleteAll", query="DELETE FROM GroupEntity WHERE 1=1") -}) - -public class GroupEntity implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @Column (name="groupKey", nullable=false) - @GeneratedValue(strategy = GenerationType.AUTO) - private long groupKey; - - @Column (name="groupId", nullable=false) - private String groupId; - - @Column(name="groupName", nullable=false, unique=false, length=255) - private String groupName; - - @Version - @Column(name="version") - private int version; - - @ManyToMany(cascade = CascadeType.ALL) - @JoinTable(name="PolicyGroupEntity",joinColumns={@JoinColumn(name="groupKey")}, inverseJoinColumns={@JoinColumn(name="policyId")}) - @JsonManagedReference - private List policies; - - @Column(name="created_by", nullable=false, length=255) - private String createdBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Column(name="description", nullable=false, length=2048) - private String description = "NoDescription"; - - @Column(name="modified_by", nullable=false, length=255) - private String modifiedBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @Column(name="defaultGroup", nullable=false) - private boolean defaultGroup = false; - @Column(name="deleted", nullable=false) - private boolean deleted = false; - - public GroupEntity() { - super(); - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - } - - /** - * @return the policyId - */ - public String getGroupId() { - return groupId; - } - public long getGroupKey(){ - return groupKey; - } - - public void setGroupId(String groupId){ - this.groupId = groupId; - } - - /** - * @param policyId cannot be set - */ - - public String getgroupName() { - return groupName; - } - - public void setGroupName(String groupName) { - this.groupName = groupName; - } - - public boolean isDefaultGroup(){ - return defaultGroup; - } - - public void setDefaultGroup(boolean isDefaultGroup){ - this.defaultGroup = isDefaultGroup; - } - - - - /** - * @return the configurationDataEntity - */ - public List getPolicies() { - return policies; - } - - /** - * @param configurationDataEntity the configurationDataEntity to set - */ - public void addPolicyToGroup(PolicyEntity policy) { - if(!this.policies.contains(policy)){ - this.policies.add(policy); - } - } - public void removePolicyFromGroup(PolicyEntity policy){ - this.policies.remove(policy); - } - - - - /** - * @return the createdBy - */ - public String getCreatedBy() { - return createdBy; - } - - /** - * @param createdBy the createdBy to set - */ - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - /** - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * @param description the description to set - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * @return the modifiedBy - */ - public String getModifiedBy() { - return modifiedBy; - } - - /** - * @param modifiedBy the modifiedBy to set - */ - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - /** - * @return the version - */ - public int getVersion() { - return version; - } - - /** - * @return the createdDate - */ - public Date getCreatedDate() { - return createdDate; - } - - /** - * @return the modifiedDate - */ - public Date getModifiedDate() { - return modifiedDate; - } - - /** - * @return the deleted - */ - public boolean isDeleted() { - return deleted; - } - - /** - * @param deleted the deleted to set - */ - public void setDeleted(boolean deleted) { - this.deleted = deleted; - } - - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GroupPolicyScopeList.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GroupPolicyScopeList.java deleted file mode 100644 index a8e052282..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GroupPolicyScopeList.java +++ /dev/null @@ -1,111 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - - -@Entity -@Table(name="GroupPolicyScopeList") -@NamedQuery(name="GroupPolicyScopeList.findAll", query="SELECT e FROM GroupPolicyScopeList e ") -public class GroupPolicyScopeList implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String name; - - @Column(name="groupList") - private String groupList; - - @Column(name="description") - private String description; - - public GroupPolicyScopeList() { - - } - public GroupPolicyScopeList(String string, String userid) { - this(domain); - - } - public GroupPolicyScopeList(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getGroupName() { - return this.name; - } - - public void setGroupName(String serviceName) { - this.name = serviceName; - - } - - public String getGroupList() { - return this.groupList; - } - - public void setGroupList(String groupList) { - this.groupList = groupList; - - } - public String getDescription() { - return description; - } - public void setDescription(String description) { - this.description = description; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GroupServiceList.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GroupServiceList.java deleted file mode 100644 index d214e4694..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/GroupServiceList.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - - -@Entity -@Table(name="GroupServiceList") -@NamedQuery(name="GroupServiceList.findAll", query="SELECT e FROM GroupServiceList e ") -public class GroupServiceList implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String name; - - @Column(name="serviceList ") - private String serviceList; - - - public GroupServiceList() { - - } - public GroupServiceList(String string, String userid) { - this(domain); - - } - public GroupServiceList(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getGroupName() { - return this.name; - } - - public void setGroupName(String serviceName) { - this.name = serviceName; - - } - - public String getServiceList() { - return this.serviceList; - } - - public void setServiceList(String serviceList) { - this.serviceList = serviceList; - - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceAttribute.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceAttribute.java deleted file mode 100644 index e30379e1d..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceAttribute.java +++ /dev/null @@ -1,109 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - -@Entity -@Table(name="MicroServiceAttribute") -@NamedQuery(name="MicroServiceAttribute.findAll", query="SELECT e FROM MicroServiceAttribute e ") -public class MicroServiceAttribute implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String name; - - @Column(name="value") - private String value ; - - @Column(name="modelName") - private String modelName; - - - public MicroServiceAttribute() { - - } - public MicroServiceAttribute(String string, String userid) { - this(domain); - - } - public MicroServiceAttribute(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - - } - public String getValue() { - return this.value ; - } - - public void setValue(String value ) { - this.value = value ; - } - public String getModelName() { - return modelName; - } - public void setModelName(String modelName) { - this.modelName = modelName; - } - -} \ No newline at end of file diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceConfigName.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceConfigName.java deleted file mode 100644 index 0a1034c77..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceConfigName.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - - -@Entity -@Table(name="MicroServiceConfigName") -@NamedQuery(name="MicroServiceConfigName.findAll", query="SELECT e FROM MicroServiceConfigName e ") -public class MicroServiceConfigName implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String name; - - @Column(name="description ") - private String description ; - - - public MicroServiceConfigName() { - - } - public MicroServiceConfigName(String string, String userid) { - this(domain); - - } - public MicroServiceConfigName(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - - } - public String getDescriptionValue() { - return this.description ; - } - - public void setDescriptionValue(String description ) { - this.description = description ; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceLocation.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceLocation.java deleted file mode 100644 index a72f690ac..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceLocation.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - - -@Entity -@Table(name="MicroServiceLocation") -@NamedQuery(name="MicroServiceLocation.findAll", query="SELECT e FROM MicroServiceLocation e ") -public class MicroServiceLocation implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String name; - - @Column(name="description ") - private String description ; - - - public MicroServiceLocation() { - - } - public MicroServiceLocation(String string, String userid) { - this(domain); - - } - public MicroServiceLocation(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - - } - public String getDescriptionValue() { - return this.description ; - } - - public void setDescriptionValue(String description ) { - this.description = description ; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceModels.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceModels.java deleted file mode 100644 index c1eb24058..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/MicroServiceModels.java +++ /dev/null @@ -1,189 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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========================================================= - */ - -/* - * AT&T - PROPRIETARY - * THIS FILE CONTAINS PROPRIETARY INFORMATION OF - * AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN - * ACCORDANCE WITH APPLICABLE AGREEMENTS. - * - * Copyright (c) 2015 AT&T Knowledge Ventures - * Unpublished and Not for Publication - * All Rights Reserved - */ -package org.openecomp.policy.rest.jpa; - -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.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.Table; -/* - * JPA for the Micro Service Models. - * - * @version: 0.1 - */ - - -@Entity -@Table(name="MicroServiceModels") -@NamedQuery(name="MicroServiceModels.findAll", query="SELECT b FROM MicroServiceModels b ") -public class MicroServiceModels implements Serializable{ - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="modelName", nullable=false, unique=true) - @OrderBy("asc") - private String modelName; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Column(name="dependency", nullable=true, length=2048) - private String dependency; - - @Column(name="attributes", nullable=false, length=255) - private String attributes; - - @Column(name="ref_attributes", nullable=false, length=255) - private String ref_attributes; - - @Column (name="sub_attributes", nullable=false, length=2000) - private String sub_attributes; - - @Column (name="version", nullable=false, length=2000) - private String version; - - @Column (name="enumValues", nullable=false, length=2000) - private String enumValues; - - @Column (name="annotation", nullable=false, length=2000) - private String annotation; - - public String getSub_attributes() { - return sub_attributes; - } - - public void setSub_attributes(String sub_attributes) { - this.sub_attributes = sub_attributes; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - @ManyToOne - @JoinColumn(name="imported_by") - private UserInfo userCreatedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public MicroServiceModels(){ - } - - public MicroServiceModels(String userid){ - - } - - public String getAttributes() { - return attributes; - } - - public void setAttributes(String attributes) { - this.attributes = attributes; - } - - public String getRef_attributes() { - return ref_attributes; - } - - public void setRef_attributes(String ref_attributes) { - this.ref_attributes = ref_attributes; - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getDependency() { - return dependency; - } - - public void setDependency(String dependency) { - this.dependency = dependency; - } - - public String getModelName(){ - return this.modelName; - } - - public void setModelName(String modelName){ - this.modelName = modelName; - } - - public String getEnumValues() { - return enumValues; - } - - public void setEnumValues(String enumValues) { - this.enumValues = enumValues; - } - - public String getAnnotation() { - return annotation; - } - - public void setAnnotation(String annotation) { - this.annotation = annotation; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Obadvice.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Obadvice.java deleted file mode 100644 index 494092029..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Obadvice.java +++ /dev/null @@ -1,227 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; - -import javax.persistence.CascadeType; -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.OneToMany; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Transient; - -import com.att.research.xacml.api.Identifier; - -/** - * The persistent class for the Obadvice database table. - * - */ -@Entity -@Table(name="Obadvice") -@NamedQuery(name="Obadvice.findAll", query="SELECT o FROM Obadvice o") -public class Obadvice implements Serializable { - private static final long serialVersionUID = 1L; - - public static final String OBLIGATION = "Obligation"; - public static final String ADVICE = "Advice"; - public static final String EFFECT_PERMIT = "Permit"; - public static final String EFFECT_DENY = "Deny"; - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="type", nullable=false) - private String type; - - @Column(name="xacml_id", nullable=false, length=255) - private String xacmlId; - - @Column(name="fulfill_on", nullable=true, length=32) - private String fulfillOn; - - @Column(name="description", nullable=true, length=2048) - private String description; - - //bi-directional one-to-many association to Attribute Assignment - @OneToMany(mappedBy="obadvice", orphanRemoval=true, cascade=CascadeType.REMOVE) - private Set obadviceExpressions = new HashSet<>(2); - - @Column(name="created_by", nullable=false, length=255) - private String createdBy; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", nullable=false, updatable=false) - private Date createdDate; - - @Column(name="modified_by", nullable=false, length=255) - private String modifiedBy; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - public Obadvice() { - this.type = Obadvice.OBLIGATION; - this.fulfillOn = Obadvice.EFFECT_PERMIT; - } - - public Obadvice(String domain, String userid) { - this.xacmlId = domain; - this.type = Obadvice.OBLIGATION; - this.fulfillOn = Obadvice.EFFECT_PERMIT; - this.createdBy = userid; - this.modifiedBy = userid; - } - - public Obadvice(Identifier id, String userid) { - this(id.stringValue(), userid); - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getCreatedBy() { - return this.createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getFulfillOn() { - return this.fulfillOn; - } - - public void setFulfillOn(String fulfillOn) { - this.fulfillOn = fulfillOn; - } - - public String getModifiedBy() { - return this.modifiedBy; - } - - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - public String getType() { - return this.type; - } - - public void setType(String type) { - this.type = type; - } - - public String getXacmlId() { - return this.xacmlId; - } - - public void setXacmlId(String xacmlId) { - this.xacmlId = xacmlId; - } - - public Set getObadviceExpressions() { - return this.obadviceExpressions; - } - - public void setObadviceExpressions(Set obadviceExpressions) { - this.obadviceExpressions = obadviceExpressions; - } - - public ObadviceExpression addObadviceExpression(ObadviceExpression obadviceExpression) { - this.obadviceExpressions.add(obadviceExpression); - obadviceExpression.setObadvice(this); - - return obadviceExpression; - } - - public ObadviceExpression removeObadviceExpression(ObadviceExpression obadviceExpression) { - this.obadviceExpressions.remove(obadviceExpression); - obadviceExpression.setObadvice(null); - - return obadviceExpression; - } - - public void removeAllExpressions() { - if (this.obadviceExpressions == null) { - return; - } - for (ObadviceExpression expression : this.obadviceExpressions) { - expression.setObadvice(null); - } - this.obadviceExpressions.clear(); - } - - @Transient - public Obadvice clone() { - Obadvice obadvice = new Obadvice(); - - obadvice.type = this.type; - obadvice.xacmlId = this.xacmlId; - obadvice.fulfillOn = this.fulfillOn; - obadvice.description = this.description; - obadvice.createdBy = this.createdBy; - obadvice.modifiedBy = this.modifiedBy; - for (ObadviceExpression exp: this.obadviceExpressions) { - obadvice.addObadviceExpression(exp.clone()); - } - - return obadvice; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ObadviceExpression.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ObadviceExpression.java deleted file mode 100644 index 1908b9dc9..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ObadviceExpression.java +++ /dev/null @@ -1,123 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -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.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OneToOne; -import javax.persistence.Table; - - -/** - * The persistent class for the ObadviceExpressions database table. - * - */ -@Entity -@Table(name="ObadviceExpressions") -@NamedQuery(name="ObadviceExpression.findAll", query="SELECT o FROM ObadviceExpression o") -public class ObadviceExpression implements Serializable { - private static final long serialVersionUID = 1L; - - public static final String EXPRESSION_APPLY = "Apply"; - public static final String EXPRESSION_SELECTOR = "Attribute Selector"; - public static final String EXPRESSION_VALUE = "Attribute Value"; - public static final String EXPRESSION_FUNCTION = "Function"; - public static final String EXPRESSION_REFERENCE = "Varable Reference"; - public static final String EXPRESSION_DESIGNATOR = "Attribute Designator"; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - //unidirectional one-to-one association to Attribute - @OneToOne - @JoinColumn(name="attribute_id") - private Attribute attribute; - - @Column(name="type", nullable=false) - private String type; - - /* - @Lob - @Column(name="expression", nullable=false) - private byte[] expression; - */ - - //bi-directional many-to-one association to Obadvice - @ManyToOne - @JoinColumn(name="obadvice_id") - private Obadvice obadvice; - - public ObadviceExpression() { - type = EXPRESSION_VALUE; - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public Attribute getAttribute() { - return this.attribute; - } - - public void setAttribute(Attribute attribute) { - this.attribute = attribute; - } - - public String getType() { - return this.type; - } - - public void setType(String type) { - this.type = type; - } - - public Obadvice getObadvice() { - return this.obadvice; - } - - public void setObadvice(Obadvice obadvice) { - this.obadvice = obadvice; - } - - public ObadviceExpression clone() { - ObadviceExpression expression = new ObadviceExpression(); - - expression.attribute = this.attribute; - expression.type = this.type; - expression.obadvice = this.obadvice; - - return expression; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PEPOptions.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PEPOptions.java deleted file mode 100644 index ed520472c..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PEPOptions.java +++ /dev/null @@ -1,183 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - * - * */ -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - - -@Entity -@Table(name = "PEPOptions") -@NamedQuery(name = "PEPOptions.findAll", query= "Select p from PEPOptions p") -public class PEPOptions implements Serializable { - private static final long serialVersionUID = 1L; - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "Id") - private int id; - - @Column(name="PEP_NAME", nullable=false) - @OrderBy("asc") - private String pepName; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Column(name="Actions", nullable=true) - @OrderBy("asc") - private String actions; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - private static Log LOGGER = LogFactory.getLog(PEPOptions.class); - - public PEPOptions(){ - - } - - public PEPOptions(String string, String userid) { - this(string); - } - - public PEPOptions(String domain) { - this.pepName = domain; - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy =XacmlAdminAuthorization.getUserId();; - } catch (Exception e) { - LOGGER.error("Exception caused While adding Modified by Role"+e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PEPOptions", "Exception caused While adding Modified by Role"); - } - } - - public int getId() { - return this.id; - } - public void setId(int id) { - this.id = id; - } - - public String getPepName() { - return pepName; - } - - public void setPepName(String pepName) { - this.pepName = pepName; - } - - public String getActions() { - return actions; - } - - public void setActions(String actions) { - this.actions = actions; - } - - public Date getCreatedDate() { - return this.createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Date getModifiedDate() { - return this.modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPConfigParam.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPConfigParam.java deleted file mode 100644 index d3724363f..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPConfigParam.java +++ /dev/null @@ -1,147 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; - -import javax.persistence.*; - - -/** - * The persistent class for the PIPConfigParams database table. - * - */ -@Entity -@Table(name="PIPConfigParams") -@NamedQuery(name="PIPConfigParam.findAll", query="SELECT p FROM PIPConfigParam p") -public class PIPConfigParam implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy=GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="PARAM_NAME", nullable=false, length=1024) - private String paramName; - - @Column(name="PARAM_VALUE", nullable=false, length=2048) - private String paramValue; - - @Column(name="PARAM_DEFAULT", nullable=true, length=2048) - private String paramDefault = null; - - @Column(name="REQUIRED", nullable=false) - private char required = '0'; - - //bi-directional many-to-one association to PIPConfiguration - @ManyToOne - @JoinColumn(name="PIP_ID") - private PIPConfiguration pipconfiguration; - - public PIPConfigParam() { - } - - public PIPConfigParam(String param) { - this.paramName = param; - } - - public PIPConfigParam(String param, String value) { - this(param); - this.paramValue = value; - } - - public PIPConfigParam(PIPConfigParam param) { - this(param.getParamName(), param.getParamValue()); - this.paramDefault = param.getParamDefault(); - this.required = param.required; - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getParamName() { - return this.paramName; - } - - public void setParamName(String paramName) { - this.paramName = paramName; - } - - public String getParamValue() { - return this.paramValue; - } - - public void setParamValue(String paramValue) { - this.paramValue = paramValue; - } - - public String getParamDefault() { - return paramDefault; - } - - public void setParamDefault(String paramDefault) { - this.paramDefault = paramDefault; - } - - public char getRequired() { - return required; - } - - public void setRequired(char required) { - this.required = required; - } - - public PIPConfiguration getPipconfiguration() { - return this.pipconfiguration; - } - - public void setPipconfiguration(PIPConfiguration pipconfiguration) { - this.pipconfiguration = pipconfiguration; - } - - @Transient - public boolean isRequired() { - return (this.required == '1'); - } - - @Transient - public void setRequired(boolean required) { - if (required) { - this.setRequired('1'); - } else { - this.setRequired('0'); - } - } - - @Transient - @Override - public String toString() { - return "PIPConfigParam [id=" + id + ", paramName=" + paramName - + ", paramValue=" + paramValue + ", required=" + required + "]"; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPConfiguration.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPConfiguration.java deleted file mode 100644 index 70a0e845f..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPConfiguration.java +++ /dev/null @@ -1,537 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OneToMany; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Transient; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.xacml.api.XACMLErrorConstants; - -import com.att.research.xacml.api.pip.PIPException; -import com.att.research.xacml.std.pip.engines.StdConfigurableEngine; -import com.att.research.xacml.util.XACMLProperties; -import com.google.common.base.Joiner; -import com.google.common.base.Splitter; - - -/** - * The persistent class for the PIPConfiguration database table. - * - */ -@Entity -@Table(name="PIPConfiguration") -@NamedQuery(name="PIPConfiguration.findAll", query="SELECT p FROM PIPConfiguration p") -public class PIPConfiguration implements Serializable { - private static final long serialVersionUID = 1L; - private static final Log logger = LogFactory.getLog(PIPConfiguration.class); - - @Id - @GeneratedValue(strategy=GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="DESCRIPTION", nullable=true, length=2048) - private String description; - - @Column(name="NAME", nullable=false, length=255) - private String name; - - @Column(name="CLASSNAME", nullable=false, length=2048) - private String classname; - - @Column(name="ISSUER", nullable=true, length=1024) - private String issuer; - - @Column(name="READ_ONLY", nullable=false) - private char readOnly = '0'; - - @Column(name="REQUIRES_RESOLVER", nullable=false) - private char requiresResolvers; - - @Column(name="CREATED_BY", nullable=false, length=255) - private String createdBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="CREATED_DATE", nullable=false, updatable=false) - private Date createdDate; - - @Column(name="MODIFIED_BY", nullable=false, length=255) - private String modifiedBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="MODIFIED_DATE", nullable=false) - private Date modifiedDate; - - //bi-directional many-to-one association to PIPConfigParam - @OneToMany(mappedBy="pipconfiguration", orphanRemoval=true, cascade=CascadeType.REMOVE) - private Set pipconfigParams = new HashSet<>(); - - //bi-directional many-to-one association to PIPType - @ManyToOne - @JoinColumn(name="TYPE") - private PIPType piptype; - - //bi-directional many-to-one association to PIPResolver - @OneToMany(mappedBy="pipconfiguration", orphanRemoval=true, cascade=CascadeType.REMOVE) - private Set pipresolvers = new HashSet<>(); - - public PIPConfiguration() { - } - - public PIPConfiguration(PIPConfiguration config, String user) { - this.description = config.description; - this.name = config.name; - this.classname = config.classname; - this.issuer = config.issuer; - this.requiresResolvers = config.requiresResolvers; - this.readOnly = config.readOnly; - this.piptype = config.piptype; - for (PIPConfigParam param : config.pipconfigParams) { - this.addPipconfigParam(new PIPConfigParam(param)); - } - for (PIPResolver resolver : config.pipresolvers) { - this.addPipresolver(new PIPResolver(resolver)); - } - } - - public PIPConfiguration(String id, Properties properties) throws PIPException { - this.readProperties(id, properties); - } - - public PIPConfiguration(String id, Properties properties, String user) throws PIPException { - this.createdBy = user; - this.modifiedBy = user; - this.readProperties(id, properties); - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - public String getClassname() { - return classname; - } - - public void setClassname(String classname) { - this.classname = classname; - } - - public String getIssuer() { - return issuer; - } - - public void setIssuer(String issuer) { - this.issuer = issuer; - } - - public char getReadOnly() { - return readOnly; - } - - public void setReadOnly(char readOnly) { - this.readOnly = readOnly; - } - - public char getRequiresResolvers() { - return requiresResolvers; - } - - public void setRequiresResolvers(char requireResolvers) { - this.requiresResolvers = requireResolvers; - } - - public Set getPipconfigParams() { - return this.pipconfigParams; - } - - public void setPipconfigParams(Set pipconfigParams) { - this.pipconfigParams = pipconfigParams; - } - - public PIPConfigParam addPipconfigParam(PIPConfigParam pipconfigParam) { - getPipconfigParams().add(pipconfigParam); - pipconfigParam.setPipconfiguration(this); - - return pipconfigParam; - } - - public PIPConfigParam removePipconfigParam(PIPConfigParam pipconfigParam) { - if (pipconfigParam == null) { - return pipconfigParam; - } - getPipconfigParams().remove(pipconfigParam); - pipconfigParam.setPipconfiguration(null); - - return pipconfigParam; - } - - @Transient - public void clearConfigParams() { - while (this.pipconfigParams.isEmpty() == false) { - this.removePipconfigParam(this.pipconfigParams.iterator().next()); - } - } - - public PIPType getPiptype() { - return this.piptype; - } - - public void setPiptype(PIPType piptype) { - this.piptype = piptype; - } - - public Set getPipresolvers() { - return this.pipresolvers; - } - - public void setPipresolvers(Set pipresolvers) { - this.pipresolvers = pipresolvers; - } - - public PIPResolver addPipresolver(PIPResolver pipresolver) { - getPipresolvers().add(pipresolver); - pipresolver.setPipconfiguration(this); - - return pipresolver; - } - - public PIPResolver removePipresolver(PIPResolver pipresolver) { - getPipresolvers().remove(pipresolver); - pipresolver.setPipconfiguration(null); - - return pipresolver; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public Date getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public String getModifiedBy() { - return modifiedBy; - } - - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - public Date getModifiedDate() { - return modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - - @Transient - public boolean isReadOnly() { - return (this.readOnly == '1'); - } - - @Transient - public void setReadOnly(boolean readOnly) { - if (readOnly) { - this.readOnly = '1'; - } else { - this.readOnly = '0'; - } - } - - @Transient - public boolean requiresResolvers() { - return (this.requiresResolvers == '1'); - } - - @Transient - public void setRequiresResolvers(boolean requires) { - if (requires) { - this.requiresResolvers = '1'; - } else { - this.requiresResolvers = '0'; - } - } - - @Transient - public static Collection importPIPConfigurations(Properties properties) { - Collection configurations = new ArrayList<>(); - String engines = properties.getProperty(XACMLProperties.PROP_PIP_ENGINES); - if (engines == null || engines.isEmpty()) { - return configurations; - } - for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(engines)) { - PIPConfiguration configuration; - try { - String user = "super-admin"; - configuration = new PIPConfiguration(id, properties, user); - configuration.setCreatedBy(user); - configuration.setModifiedBy(user); - configurations.add(configuration); - } catch (PIPException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Import failed: " + e.getLocalizedMessage()); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PIPConfiguration", "Import failed"); - } - } - - return configurations; - } - - @Transient - protected void readProperties(String id, Properties properties) throws PIPException { - // - // Save the id if we don't have one already - // - - if (this.id == 0) { - try { - this.id = Integer.parseInt(id); - } catch (NumberFormatException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Convert id to integer failed: " + id); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PIPConfiguration", "Convert id to integer failed"); - } - } - // - // Get its classname, this MUST exist. - // - this.classname = properties.getProperty(id + ".classname"); - if (this.classname == null) { - throw new PIPException("PIP Engine defined without a classname"); - } - // - // Go through each property - // - for (Object name : properties.keySet()) { - if (name.toString().startsWith(id) == false) { - continue; - } - if (name.equals(id + ".classname")) { - // - // We already saved this - // - } else if (name.equals(id + "." + StdConfigurableEngine.PROP_NAME)) { - this.name = properties.getProperty(name.toString()); - } else if (name.equals(id + "." + StdConfigurableEngine.PROP_DESCRIPTION)) { - this.description = properties.getProperty(name.toString()); - } else if (name.equals(id + "." + StdConfigurableEngine.PROP_ISSUER)) { - this.issuer = properties.getProperty(name.toString()); - } else if (name.equals(id + ".resolvers")) { - // - // It has resolvers, make sure this is set to true if - // it has been already. - // - this.setRequiresResolvers(true); - // - // Parse the resolvers - // - Collection resolvers = PIPResolver.importResolvers(id + ".resolver", - properties.getProperty(name.toString()), - properties,"super-admin" - ); - for (PIPResolver resolver : resolvers) { - this.addPipresolver(resolver); - } - } else if (name.toString().startsWith(id + ".resolver")) { - // - // Ignore, the PIPResolver will parse these values - // - } else { - // - // Config Parameter - // - this.addPipconfigParam(new PIPConfigParam(name.toString().substring(id.length() + 1), - properties.getProperty(name.toString()))); - } - } - // - // Make sure we have a name at least - // - if (this.name == null) { - this.name = id; - } - } - - - @Transient - public Map getConfiguration(String name) { - String prefix; - if (name == null) { - prefix = Integer.toString(this.id); - } else { - prefix = name; - } - if (prefix.endsWith(".") == false) { - prefix = prefix + "."; - } - Map map = new HashMap<>(); - map.put(prefix + "classname", this.classname); - map.put(prefix + "name", this.name); - if (this.description != null) { - map.put(prefix + "description", this.description); - } - if (this.issuer != null) { - map.put(prefix + "issuer", this.issuer); - } - - for (PIPConfigParam param : this.pipconfigParams) { - map.put(prefix + param.getParamName(), param.getParamValue()); - } - - List ids = new ArrayList<>(); - Iterator iter = this.pipresolvers.iterator(); - while (iter.hasNext()) { - PIPResolver resolver = iter.next(); - String id = Integer.toString(resolver.getId()); - Map resolverMap = resolver.getConfiguration(prefix + "resolver." + id); - map.putAll(resolverMap); - ids.add(id); - } - if (ids.size() > 0) { - map.put(prefix + "resolvers", Joiner.on(',').join(ids)); - } - return map; - } - - @Transient - public Properties generateProperties(String name) { - String prefix; - if (name == null) { - prefix = Integer.toString(this.id); - } else { - if (name.endsWith(".")) { - prefix = name; - } else { - prefix = name + "."; - } - } - Properties props = new Properties(); - props.setProperty("xacml.pip.engines", name); - props.setProperty(prefix + "classname", this.classname); - props.setProperty(prefix + "name", this.name); - if (this.description != null) { - props.setProperty(prefix + "description", this.description); - } - if (this.issuer != null && this.issuer.isEmpty() == false) { - props.setProperty(prefix + "issuer", this.issuer); - } - - for (PIPConfigParam param : this.pipconfigParams) { - props.setProperty(prefix + param.getParamName(), param.getParamValue()); - } - - List ids = new ArrayList<>(); - Iterator iter = this.pipresolvers.iterator(); - while (iter.hasNext()) { - PIPResolver resolver = iter.next(); - String id = Integer.toString(resolver.getId()); - resolver.generateProperties(props, prefix + "resolver." + id); - ids.add(id); - } - if (ids.size() > 0) { - props.setProperty(prefix + "resolvers", Joiner.on(',').join(ids)); - } - return props; - } - - @Transient - @Override - public String toString() { - return "PIPConfiguration [id=" + id + ", piptype=" + piptype - + ", classname=" + classname + ", name=" + name - + ", description=" + description + ", issuer=" + issuer - + ", readOnly=" + readOnly + ", requiresResolvers=" - + requiresResolvers + ", createdBy=" + createdBy - + ", createdDate=" + createdDate + ", modifiedBy=" + modifiedBy - + ", modifiedDate=" + modifiedDate + ", pipconfigParams=" - + pipconfigParams + ", pipresolvers=" + pipresolvers + "]"; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPResolver.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPResolver.java deleted file mode 100644 index 618c1a4ea..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPResolver.java +++ /dev/null @@ -1,365 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OneToMany; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Transient; - -import com.att.research.xacml.api.pip.PIPException; -import com.att.research.xacml.std.pip.engines.StdConfigurableEngine; -import com.google.common.base.Splitter; - - -/** - * The persistent class for the PIPResolver database table. - * - */ -@Entity -@Table(name="PIPResolver") -@NamedQuery(name="PIPResolver.findAll", query="SELECT p FROM PIPResolver p") -public class PIPResolver implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy=GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="DESCRIPTION", nullable=true, length=2048) - private String description; - - @Column(name="NAME", nullable=false, length=255) - private String name; - - @Column(name="ISSUER", nullable=true, length=1024) - private String issuer; - - @Column(name="CLASSNAME", nullable=false, length=2048) - private String classname; - - @Column(name="READ_ONLY", nullable=false) - private char readOnly = '0'; - - @Column(name="CREATED_BY", nullable=false, length=255) - private String createdBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="CREATED_DATE", nullable=false, updatable=false) - private Date createdDate; - - @Column(name="MODIFIED_BY", nullable=false, length=255) - private String modifiedBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="MODIFIED_DATE", nullable=false) - private Date modifiedDate; - - //bi-directional many-to-one association to PIPConfiguration - @ManyToOne - @JoinColumn(name="PIP_ID") - private PIPConfiguration pipconfiguration; - - //bi-directional many-to-one association to PIPResolverParam - @OneToMany(mappedBy="pipresolver", orphanRemoval=true, cascade=CascadeType.REMOVE) - private Set pipresolverParams = new HashSet<>(); - - public PIPResolver() { - } - - public PIPResolver(String prefix, Properties properties, String user) throws PIPException { - this.createdBy = user; - this.modifiedBy = user; - this.readOnly = '0'; - this.readProperties(prefix, properties); - } - - public PIPResolver(PIPResolver resolver) { - this.name = resolver.name; - this.description = resolver.description; - this.issuer = resolver.issuer; - this.classname = resolver.classname; - this.readOnly = resolver.readOnly; - for (PIPResolverParam param : this.pipresolverParams) { - this.addPipresolverParam(new PIPResolverParam(param)); - } - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - public String getIssuer() { - return issuer; - } - - public void setIssuer(String issuer) { - this.issuer = issuer; - } - - public String getClassname() { - return classname; - } - - public void setClassname(String classname) { - this.classname = classname; - } - - public char getReadOnly() { - return readOnly; - } - - public void setReadOnly(char readOnly) { - this.readOnly = readOnly; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public Date getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public String getModifiedBy() { - return modifiedBy; - } - - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - public Date getModifiedDate() { - return modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - - public PIPConfiguration getPipconfiguration() { - return this.pipconfiguration; - } - - public void setPipconfiguration(PIPConfiguration pipconfiguration) { - this.pipconfiguration = pipconfiguration; - } - - public Set getPipresolverParams() { - return this.pipresolverParams; - } - - public void setPipresolverParams(Set pipresolverParams) { - this.pipresolverParams = pipresolverParams; - } - - public PIPResolverParam addPipresolverParam(PIPResolverParam pipresolverParam) { - getPipresolverParams().add(pipresolverParam); - pipresolverParam.setPipresolver(this); - - return pipresolverParam; - } - - public PIPResolverParam removePipresolverParam(PIPResolverParam pipresolverParam) { - if (pipresolverParam == null) { - return pipresolverParam; - } - getPipresolverParams().remove(pipresolverParam); - pipresolverParam.setPipresolver(null); - - return pipresolverParam; - } - - @Transient - public void clearParams() { - while (this.pipresolverParams.isEmpty() == false) { - this.removePipresolverParam(this.pipresolverParams.iterator().next()); - } - } - - @Transient - public boolean isReadOnly() { - return (this.readOnly == '1'); - } - - @Transient - public void setReadOnly(boolean readOnly) { - if (readOnly) { - this.readOnly = '1'; - } else { - this.readOnly = '0'; - } - } - - @Transient - public static Collection importResolvers(String prefix, String list, Properties properties, String user) throws PIPException { - Collection resolvers = new ArrayList<>(); - for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) { - resolvers.add(new PIPResolver(prefix + "." + id, properties, user)); - } - return resolvers; - } - - @Transient - protected void readProperties(String prefix, Properties properties) throws PIPException { - // - // Get its classname, this MUST exist. - // - this.classname = properties.getProperty(prefix + ".classname"); - if (this.classname == null) { - throw new PIPException("PIP Engine defined without a classname"); - } - // - // Go through each property - // - for (Object name : properties.keySet()) { - if (name.toString().startsWith(prefix) == false) { - continue; - } - if (name.equals(prefix + ".classname")) { - // - // We already saved this - // - } else if (name.equals(prefix + "." + StdConfigurableEngine.PROP_NAME)) { - this.name = properties.getProperty(name.toString()); - } else if (name.equals(prefix + "." + StdConfigurableEngine.PROP_DESCRIPTION)) { - this.description = properties.getProperty(name.toString()); - } else if (name.equals(prefix + "." + StdConfigurableEngine.PROP_ISSUER)) { - this.issuer = properties.getProperty(name.toString()); - } else { - this.addPipresolverParam(new PIPResolverParam(name.toString().substring(prefix.length() + 1), - properties.getProperty(name.toString()))); - } - } - } - - @Transient - public Map getConfiguration(String prefix) { - Map map = new HashMap<>(); - if (prefix.endsWith(".") == false) { - prefix = prefix + "."; - } - map.put(prefix + "classname", this.classname); - map.put(prefix + "name", this.name); - if (this.description != null) { - map.put(prefix + "description", this.description); - } - if (this.issuer != null && this.issuer.isEmpty() != false) { - map.put(prefix + "issuer", this.issuer); - } - for (PIPResolverParam param : this.pipresolverParams) { - map.put(prefix + param.getParamName(), param.getParamValue()); - } - return map; - } - - @Transient - public void generateProperties(Properties props, String prefix) { - if (prefix.endsWith(".") == false) { - prefix = prefix + "."; - } - props.setProperty(prefix + "classname", this.classname); - props.setProperty(prefix + "name", this.name); - if (this.description != null) { - props.setProperty(prefix + "description", this.description); - } - if (this.issuer != null && this.issuer.isEmpty() != false) { - props.setProperty(prefix + "issuer", this.issuer); - } - for (PIPResolverParam param : this.pipresolverParams) { - props.setProperty(prefix + param.getParamName(), param.getParamValue()); - } - } - - @Transient - @Override - public String toString() { - return "PIPResolver [id=" + id + ", classname=" + classname + ", name=" - + name + ", description=" + description + ", issuer=" + issuer - + ", readOnly=" + readOnly + ", createdBy=" + createdBy - + ", createdDate=" + createdDate + ", modifiedBy=" + modifiedBy - + ", modifiedDate=" + modifiedDate + ", pipresolverParams=" - + pipresolverParams + "]"; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPResolverParam.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPResolverParam.java deleted file mode 100644 index 957b105d1..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPResolverParam.java +++ /dev/null @@ -1,147 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; - -import javax.persistence.*; - - -/** - * The persistent class for the PIPResolverParams database table. - * - */ -@Entity -@Table(name="PIPResolverParams") -@NamedQuery(name="PIPResolverParam.findAll", query="SELECT p FROM PIPResolverParam p") -public class PIPResolverParam implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy=GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="PARAM_NAME", nullable=false, length=1024) - private String paramName; - - @Column(name="PARAM_VALUE", nullable=false, length=2048) - private String paramValue; - - @Column(name="PARAM_DEFAULT", nullable=true, length=2048) - private String paramDefault; - - @Column(name="REQUIRED", nullable=false) - private char required = '0'; - - //bi-directional many-to-one association to PIPResolver - @ManyToOne - @JoinColumn(name="ID_RESOLVER") - private PIPResolver pipresolver; - - public PIPResolverParam() { - } - - public PIPResolverParam(String name) { - this.paramName = name; - } - - public PIPResolverParam(String name, String value) { - this(name); - this.paramValue = value; - } - - public PIPResolverParam(PIPResolverParam param) { - this(param.getParamName(), param.getParamValue()); - this.paramDefault = param.getParamDefault(); - this.required = param.required; - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getParamName() { - return this.paramName; - } - - public void setParamName(String paramName) { - this.paramName = paramName; - } - - public String getParamValue() { - return this.paramValue; - } - - public void setParamValue(String paramValue) { - this.paramValue = paramValue; - } - - public String getParamDefault() { - return paramDefault; - } - - public void setParamDefault(String paramDefault) { - this.paramDefault = paramDefault; - } - - public char getRequired() { - return required; - } - - public void setRequired(char required) { - this.required = required; - } - - public PIPResolver getPipresolver() { - return this.pipresolver; - } - - public void setPipresolver(PIPResolver pipresolver) { - this.pipresolver = pipresolver; - } - - @Transient - public boolean isRequired() { - return this.required == '1'; - } - - @Transient - public void setRequired(boolean required) { - if (required) { - this.required = '1'; - } else { - this.required = '0'; - } - } - - @Transient - @Override - public String toString() { - return "PIPResolverParam [id=" + id + ", paramName=" + paramName - + ", paramValue=" + paramValue + ", required=" + required + "]"; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPType.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPType.java deleted file mode 100644 index 964a15412..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PIPType.java +++ /dev/null @@ -1,131 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.Set; - -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.OneToMany; -import javax.persistence.Table; -import javax.persistence.Transient; - - -/** - * The persistent class for the PIPType database table. - * - */ -@Entity -@Table(name="PIPType") -@NamedQuery(name="PIPType.findAll", query="SELECT p FROM PIPType p") -public class PIPType implements Serializable { - private static final long serialVersionUID = 1L; - - public static final String TYPE_SQL = "SQL"; - public static final String TYPE_LDAP = "LDAP"; - public static final String TYPE_CSV = "CSV"; - public static final String TYPE_HYPERCSV = "Hyper-CSV"; - public static final String TYPE_CUSTOM = "Custom"; - - @Id - @GeneratedValue(strategy=GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="type", nullable=false, length=45) - private String type; - - //bi-directional many-to-one association to PIPConfiguration - @OneToMany(mappedBy="piptype") - private Set pipconfigurations; - - public PIPType() { - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getType() { - return this.type; - } - - public void setType(String type) { - this.type = type; - } - - public Set getPipconfigurations() { - return this.pipconfigurations; - } - - public void setPipconfigurations(Set pipconfigurations) { - this.pipconfigurations = pipconfigurations; - } - - public PIPConfiguration addPipconfiguration(PIPConfiguration pipconfiguration) { - getPipconfigurations().add(pipconfiguration); - pipconfiguration.setPiptype(this); - - return pipconfiguration; - } - - public PIPConfiguration removePipconfiguration(PIPConfiguration pipconfiguration) { - getPipconfigurations().remove(pipconfiguration); - pipconfiguration.setPiptype(null); - - return pipconfiguration; - } - - @Transient - public boolean isSQL() { - return this.type.equals(TYPE_SQL); - } - - @Transient - public boolean isLDAP() { - return this.type.equals(TYPE_LDAP); - } - - @Transient - public boolean isCSV() { - return this.type.equals(TYPE_CSV); - } - - @Transient - public boolean isHyperCSV() { - return this.type.equals(TYPE_HYPERCSV); - } - - @Transient - public boolean isCustom() { - return this.type.equals(TYPE_CUSTOM); - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PdpEntity.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PdpEntity.java deleted file mode 100644 index c7d666056..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PdpEntity.java +++ /dev/null @@ -1,241 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQueries; -import javax.persistence.NamedQuery; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -/* - * The Entity class to persist a policy object and its configuration data - */ - -/** - * - */ -@Entity -//Add a non-unique index and a constraint that says the combo of policyName and scopeId must be unique -@Table(name="PdpEntity") -@NamedQueries({ - @NamedQuery(name="PdpEntity.findAll", query="SELECT e FROM PdpEntity e "), - @NamedQuery(name="PdpEntity.deleteAll", query="DELETE FROM PdpEntity WHERE 1=1") -}) - -public class PdpEntity implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - //@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seqPdp") - @GeneratedValue(strategy = GenerationType.AUTO) - @Column (name="pdpKey") - private long pdpKey; - - @Column (name="pdpId", nullable=false, unique=false, length=255) - private String pdpId; - - @Column(name="pdpName", nullable=false, unique=false, length=255) - private String pdpName; - - @Column(name="jmxPort", nullable=false, unique=false) - private int jmxPort; - - - @ManyToOne(optional=false) - @JoinColumn(name="groupKey", referencedColumnName="groupKey") - private GroupEntity groupEntity; - - @Column(name="created_by", nullable=false, length=255) - private String createdBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Column(name="description", nullable=false, length=2048) - private String description = "NoDescription"; - - @Column(name="modified_by", nullable=false, length=255) - private String modifiedBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @Column(name="deleted", nullable=false) - private boolean deleted = false; - - public PdpEntity() { - super(); - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - } - - public long getPdpKey(){ - return pdpKey; - } - /** - * @return the policyId - */ - public String getPdpId() { - return pdpId; - } - - public void setPdpId(String id){ - pdpId = id; - } - /** - * @param policyId cannot be set - */ - - public String getPdpName() { - return pdpName; - } - - public void setPdpName(String groupName) { - this.pdpName = groupName; - } - - - - /** - * @return the configurationDataEntity - */ - public GroupEntity getGroup() { - return groupEntity; - } - - /** - * @param configurationDataEntity the configurationDataEntity to set - */ - public void setGroup(GroupEntity group) { - this.groupEntity = group; - } - - - - /** - * @return the createdBy - */ - public String getCreatedBy() { - return createdBy; - } - - /** - * @param createdBy the createdBy to set - */ - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - /** - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * @param description the description to set - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * @return the modifiedBy - */ - public String getModifiedBy() { - return modifiedBy; - } - - /** - * @param modifiedBy the modifiedBy to set - */ - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - /** - * @return the version - */ - public int getJmxPort() { - return jmxPort; - } - - public void setJmxPort(int jmxPort){ - this.jmxPort = jmxPort; - } - - /** - * @return the createdDate - */ - public Date getCreatedDate() { - return createdDate; - } - - /** - * @return the modifiedDate - */ - public Date getModifiedDate() { - return modifiedDate; - } - - /** - * @return the deleted - */ - public boolean isDeleted() { - return deleted; - } - - /** - * @param deleted the deleted to set - */ - public void setDeleted(boolean deleted) { - this.deleted = deleted; - } - - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyAlgorithms.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyAlgorithms.java deleted file mode 100644 index eb46ae0dc..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyAlgorithms.java +++ /dev/null @@ -1,116 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -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 javax.persistence.Transient; - -import com.att.research.xacml.api.Identifier; - -@Entity -@Table(name="PolicyAlgorithms") -@NamedQuery(name="PolicyAlgorithms.findAll", query="SELECT d FROM PolicyAlgorithms d") -public class PolicyAlgorithms implements Serializable { - private static final long serialVersionUID = 1L; - - public static final char STANDARD = 'S'; - public static final char CUSTOM = 'C'; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="is_standard", nullable=false) - private char isStandard; - - @Column(name="xacml_id", nullable=false, unique=true, length=255) - private String xacmlId; - - @Column(name="short_name", nullable=false, length=64) - private String shortName; - - public PolicyAlgorithms(Identifier identifier, char standard) { - this.isStandard = standard; - if (identifier != null) { - this.xacmlId = identifier.stringValue(); - } - } - - public PolicyAlgorithms(Identifier identifier) { - this(identifier, PolicyAlgorithms.STANDARD); - } - - public PolicyAlgorithms() { - this(null, PolicyAlgorithms.STANDARD); - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public char getIsStandard() { - return this.isStandard; - } - - public void setIsStandard(char isStandard) { - this.isStandard = isStandard; - } - - @Transient - public boolean isStandard() { - return (this.isStandard == PolicyAlgorithms.STANDARD); - } - - @Transient - public boolean isCustom() { - return (this.isStandard == PolicyAlgorithms.CUSTOM); - } - - public String getXacmlId() { - return this.xacmlId; - } - - public void setXacmlId(String xacmlId) { - this.xacmlId = xacmlId; - } - - public String getShortName() { - return shortName; - } - - public void setShortName(String shortName) { - this.shortName = shortName; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyDBDaoEntity.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyDBDaoEntity.java deleted file mode 100644 index c395ab49a..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyDBDaoEntity.java +++ /dev/null @@ -1,150 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.NamedQueries; -import javax.persistence.NamedQuery; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -/* - * The Entity class to persist a PolicyDBDaoEntity object for registration of PolicyDBDao - */ - -/** - * - */ -@Entity -@Table(name="PolicyDBDaoEntity") - -@NamedQueries({ - @NamedQuery(name="PolicyDBDaoEntity.findAll", query="SELECT e FROM PolicyDBDaoEntity e "), - @NamedQuery(name="PolicyDBDaoEntity.deleteAll", query="DELETE FROM PolicyDBDaoEntity WHERE 1=1") -}) - -public class PolicyDBDaoEntity implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @Column(name="policyDBDaoUrl", nullable=false, unique=true) - private String policyDBDaoUrl; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - //username for the pap server that registered this PolicyDBDaoEntity - @Column(name="username") - private String username; - - //AES encrypted password for the pap server that registered this PolicyDBDaoEntity - @Column(name="password") - private String password; - - //A column to allow some descriptive text. For example: Atlanta data center - @Column(name="description", nullable=false, length=2048) - private String description = "NoDescription"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - public PolicyDBDaoEntity() { - super(); - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - } - - /** - * @return the policyDBDaoUrl - */ - public String getPolicyDBDaoUrl() { - return policyDBDaoUrl; - } - - /** - * @param url the policyDBDaoUrl to set - */ - public void setPolicyDBDaoUrl(String url) { - this.policyDBDaoUrl = url; - } - - /** - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * @param description the description to set - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * @return the createdDate - */ - public Date getCreatedDate() { - return createdDate; - } - - /** - * @return the modifiedDate - */ - public Date getModifiedDate() { - return modifiedDate; - } - - public String getUsername(){ - return this.username; - } - public void setUsername(String username){ - this.username = username; - } - public String getPassword(){ - return this.password; - } - public void setPassword(String password){ - this.password = password; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyEditorScopes.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyEditorScopes.java deleted file mode 100644 index daf97b3ed..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyEditorScopes.java +++ /dev/null @@ -1,159 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - -@Entity -@Table(name="PolicyEditorScopes") -@NamedQuery(name="PolicyEditorScopes.findAll", query="SELECT p FROM PolicyEditorScopes p ") -public class PolicyEditorScopes implements Serializable{ - private static final long serialVersionUID = 1L; - private static Log logger = LogFactory.getLog(PolicyEditorScopes.class); - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="scopeName", nullable=false, unique=true) - @OrderBy("asc") - private String scopeName; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - public PolicyEditorScopes() { - } - - public PolicyEditorScopes(String string, String userid) { - this(domain); - } - - public PolicyEditorScopes(String domain) { - this.scopeName = domain; - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy =XacmlAdminAuthorization.getUserId(); - } catch (Exception e) { - logger.error("Exception caused While adding Modified by Role"+e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyEditorScopes", "Exception caused While adding Modified by Role"); - } - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getScopeName() { - return scopeName; - } - - public void setScopeName(String scopeName) { - this.scopeName = scopeName; - } - - public Date getCreatedDate() { - return this.createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public Date getModifiedDate() { - return this.modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyEntity.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyEntity.java deleted file mode 100644 index 7b938e461..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyEntity.java +++ /dev/null @@ -1,308 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.Lob; -import javax.persistence.NamedQueries; -import javax.persistence.NamedQuery; -import javax.persistence.OneToOne; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; -import javax.persistence.Version; - -import com.fasterxml.jackson.annotation.JsonBackReference; -import com.fasterxml.jackson.annotation.JsonManagedReference; - -/* - * The Entity class to persist a policy object and its configuration data - */ - -/** - * - */ -@Entity -//Add a non-unique index and a constraint that says the combo of policyName and scopeId must be unique -@Table(name="PolicyEntity") - -@NamedQueries({ - @NamedQuery(name="PolicyEntity.findAll", query="SELECT e FROM PolicyEntity e "), - @NamedQuery(name="PolicyEntity.findAllByDeletedFlag", query="SELECT e FROM PolicyEntity e WHERE e.deleted = :deleted"), - @NamedQuery(name="PolicyEntity.FindById", query="SELECT e FROM PolicyEntity e WHERE e.policyId = :id"), - @NamedQuery(name="PolicyEntity.deleteAll", query="DELETE FROM PolicyEntity WHERE 1=1"), - @NamedQuery(name="PolicyEntity.findByNameAndScope", query="SELECT e FROM PolicyEntity e WHERE e.policyName = :name AND e.scope = :scope") -}) - -public class PolicyEntity implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column (name="policyId") - @JsonBackReference - private long policyId; - - @Column(name="policyName", nullable=false, unique=false, length=255) - private String policyName; - - //The scope is the directory structure in dot notation. For example: org.openecomp.myproject - @Column(name="scope", nullable=false, unique=false, length=255) - private String scope; - - @Version - @Column(name="version") - private int version; - - //not going to be used - @Column(name="policyVersion") - private int policyVersion = 0; - - @Lob - @Column(name="policyData", nullable=false, columnDefinition="TEXT") - private String policyData = "NoData"; - - @OneToOne(optional=true, orphanRemoval=true) - @JoinColumn(name="configurationDataId") - @JsonManagedReference - private ConfigurationDataEntity configurationDataEntity; - - @OneToOne(optional=true, orphanRemoval=true) - @JoinColumn(name="actionBodyId") - @JsonManagedReference - private ActionBodyEntity actionBodyEntity; - - @Column(name="created_by", nullable=false, length=255) - private String createdBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Column(name="description", nullable=false, length=2048) - private String description = "NoDescription"; - - @Column(name="modified_by", nullable=false, length=255) - private String modifiedBy = "guest"; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @Column(name="deleted", nullable=false) - private boolean deleted = false; - - public PolicyEntity() { - super(); - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - } - - /* - public void resetPolicyVersion(){ - this.policyVersion = 1; - } - public void advancePolicyVersion(){ - this.policyVersion++; - } - public int getPolicyVersion(){ - return this.policyVersion; - } - public void setPolicyVersion(int polVer){ - this.policyVersion = polVer; - } - */ - - /** - * @return the policyId - */ - public long getPolicyId() { - return policyId; - } - - /** - * @param policyId cannot be set - */ - - public String getPolicyName() { - return policyName; - } - - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - - /** - * @return the policyData - */ - public String getPolicyData() { - return policyData; - } - - /** - * @param policyData the policyData to set - */ - public void setPolicyData(String policyData) { - this.policyData = policyData; - } - - /** - * @return the configurationDataEntity - */ - public ConfigurationDataEntity getConfigurationData() { - return configurationDataEntity; - } - - /** - * @param configurationDataEntity the configurationDataEntity to set - */ - public void setConfigurationData(ConfigurationDataEntity configurationDataEntity) { - this.configurationDataEntity = configurationDataEntity; - } - - /** - * @return the actionBodyEntity - */ - public ActionBodyEntity getActionBodyEntity() { - return actionBodyEntity; - } - - /** - * @param actionBodyEntity the actionBodyEntity to set - */ - public void setActionBodyEntity(ActionBodyEntity actionBodyEntity) { - this.actionBodyEntity = actionBodyEntity; - } - - /** - * @return the scope - */ - public String getScope() { - return scope; - } - - /** - * @param scope the scope to set - */ - public void setScope(String scope) { - this.scope = scope; - } - - /** - * @return the createdBy - */ - public String getCreatedBy() { - return createdBy; - } - - /** - * @param createdBy the createdBy to set - */ - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - /** - * @return the description - */ - public String getDescription() { - return description; - } - - /** - * @param description the description to set - */ - public void setDescription(String description) { - this.description = description; - } - - /** - * @return the modifiedBy - */ - public String getModifiedBy() { - return modifiedBy; - } - - /** - * @param modifiedBy the modifiedBy to set - */ - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - - /** - * @return the version - */ - public int getVersion() { - return version; - } - - /** - * @return the createdDate - */ - public Date getCreatedDate() { - return createdDate; - } - - /** - * @return the modifiedDate - */ - public Date getModifiedDate() { - return modifiedDate; - } - - /** - * @return the deleted - */ - public boolean isDeleted() { - return deleted; - } - - /** - * @param deleted the deleted to set - */ - public void setDeleted(boolean deleted) { - this.deleted = deleted; - } - - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyGroupEntity.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyGroupEntity.java deleted file mode 100644 index 85c42ee48..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyGroupEntity.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.NamedQuery; -import javax.persistence.Table; - -@Entity -@Table(name="PolicyGroupEntity") -@NamedQuery(name="PolicyGroupEntity.findAll", query="SELECT p FROM PolicyGroupEntity p ") -public class PolicyGroupEntity implements Serializable{ - - private static final long serialVersionUID = 1L; - - @Id - @Column(name="groupKey") - private int groupKey; - - @Id - @Column(name="policyid") - private int policyid; - - public int getGroupKey() { - return groupKey; - } - - public void setGroupKey(int groupKey) { - this.groupKey = groupKey; - } - - public int getPolicyid() { - return policyid; - } - - public void setPolicyid(int policyid) { - this.policyid = policyid; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyManagement.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyManagement.java deleted file mode 100644 index 3f036d555..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyManagement.java +++ /dev/null @@ -1,162 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.sql.Clob; -import java.sql.Timestamp; - -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; - - -/** - * The persistent class for the roles database table. - * - */ -@Entity -@Table(name="policy_manangement") -@NamedQuery(name="PolicyManagement.findAll", query="SELECT r FROM PolicyManagement r") -public class PolicyManagement implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - - @Column(name="id") - private int id; - - @Column(name="POLICY_NAME", nullable=false, length=45) - private String policyName; - - @Column(name="scope", nullable=false, length=45) - private String scope; - - @Column(name="ECOMP_NAME", nullable=false, length=45) - private String ecompName; - - @Column(name="CONFIG_NAME", nullable=false, length=45) - private String configName; - - @Column(name="XML", nullable=false) - private Clob xml; - - @Column(name="CREATE_DATE_TIME", nullable=false) - private Timestamp createDateTime; - - - @Column(name="CREATED_BY", nullable=false, length=45) - private String createdBy; - - @Column(name="UPDATE_DATE_TIME", nullable=false) - private Timestamp updateDateTime; - - @Column(name="UPDATED_BY", nullable=false, length=45) - private String updatedBy; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getPolicyName() { - return policyName; - } - - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - - public String getScope() { - return scope; - } - - public void setScope(String scope) { - this.scope = scope; - } - - public String getEcompName() { - return ecompName; - } - - public void setEcompName(String ecompName) { - this.ecompName = ecompName; - } - - public String getConfigName() { - return configName; - } - - public void setConfigName(String configName) { - this.configName = configName; - } - - public Clob getXml() { - return xml; - } - - public void setXml(Clob xml) { - this.xml = xml; - } - - public Timestamp getCreateDateTime() { - return createDateTime; - } - - public void setCreateDateTime(Timestamp createDateTime) { - this.createDateTime = createDateTime; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public Timestamp getUpdateDateTime() { - return updateDateTime; - } - - public void setUpdateDateTime(Timestamp updateDateTime) { - this.updateDateTime = updateDateTime; - } - - public String getUpdatedBy() { - return updatedBy; - } - - public void setUpdatedBy(String updatedBy) { - this.updatedBy = updatedBy; - } - - - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyRoles.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyRoles.java deleted file mode 100644 index ede5d1020..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyRoles.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.Table; - -import org.openecomp.policy.rest.jpa.UserInfo; - - -/** - * The persistent class for the roles database table. - * - */ -@Entity -@Table(name="roles") -@NamedQuery(name="PolicyRoles.findAll", query="SELECT r FROM PolicyRoles r ") -public class PolicyRoles implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - - @Column(name="id") - private int id; - - @ManyToOne - @JoinColumn(name="loginid") - @OrderBy("asc") - private UserInfo loginId; - - public UserInfo getLoginId() { - return loginId; - } - - public void setLoginId(UserInfo loginId) { - this.loginId = loginId; - } - - @Column(name="scope", nullable=true, length=45) - private String scope; - - @Column(name="role", nullable=false, length=45) - private String role; - - public PolicyRoles() { - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getScope() { - return this.scope; - } - - public void setScope(String scope) { - this.scope = scope; - - } - public String getRole() { - return this.role; - } - - public void setRole(String role) { - this.role = role; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeClosedLoop.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeClosedLoop.java deleted file mode 100644 index 8315ed070..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeClosedLoop.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - - -@Entity -@Table(name="PolicyScopeClosedLoop") -@NamedQuery(name="PolicyScopeClosedLoop.findAll", query="SELECT e FROM PolicyScopeClosedLoop e ") -public class PolicyScopeClosedLoop implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String name; - - @Column(name="description ") - private String description ; - - public PolicyScopeClosedLoop() { - - } - public PolicyScopeClosedLoop(String string, String userid) { - this(domain); - - } - public PolicyScopeClosedLoop(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - - } - public String getDescriptionValue() { - return this.description ; - } - - public void setDescriptionValue(String description ) { - this.description = description ; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeResource.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeResource.java deleted file mode 100644 index 76eb40d3e..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeResource.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - - -@Entity -@Table(name="PolicyScopeResource") -@NamedQuery(name="PolicyScopeResource.findAll", query="SELECT e FROM PolicyScopeResource e ") -public class PolicyScopeResource implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String name; - - @Column(name="description ") - private String description ; - - public PolicyScopeResource() { - - } - public PolicyScopeResource(String string, String userid) { - this(domain); - - } - public PolicyScopeResource(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - - } - public String getDescriptionValue() { - return this.description ; - } - - public void setDescriptionValue(String description ) { - this.description = description ; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeService.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeService.java deleted file mode 100644 index 820616988..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeService.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - - -@Entity -@Table(name="PolicyScopeService") -@NamedQuery(name="PolicyScopeService.findAll", query="SELECT e FROM PolicyScopeService e ") -public class PolicyScopeService implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String name; - - @Column(name="description ") - private String description ; - - public PolicyScopeService() { - - } - public PolicyScopeService(String string, String userid) { - this(domain); - - } - public PolicyScopeService(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - - } - public String getDescriptionValue() { - return this.description ; - } - - public void setDescriptionValue(String description ) { - this.description = description ; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeType.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeType.java deleted file mode 100644 index 65fe6e5f7..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScopeType.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - - -@Entity -@Table(name="PolicyScopeType") -@NamedQuery(name="PolicyScopeType.findAll", query="SELECT e FROM PolicyScopeType e ") -public class PolicyScopeType implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String name; - - @Column(name="description ") - private String description ; - - public PolicyScopeType() { - - } - public PolicyScopeType(String string, String userid) { - this(domain); - - } - public PolicyScopeType(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - - } - public String getDescriptionValue() { - return this.description ; - } - - public void setDescriptionValue(String description ) { - this.description = description ; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScore.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScore.java deleted file mode 100644 index 3cd84eb2d..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyScore.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -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.NamedQueries; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.Table; - - -@Entity -@Table(name="POLICYSCORE") -@NamedQueries({ - @NamedQuery(name="POLICYSCORE.findAll", query="SELECT p FROM PolicyScore p"), - @NamedQuery(name="POLICYSCORE.deleteAll", query="DELETE FROM PolicyScore WHERE 1=1"), - @NamedQuery(name="POLICYSCORE.findByPolicyName", query="Select p from PolicyScore p where p.PolicyName=:pname") -}) -public class PolicyScore implements Serializable { - - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="POLICY_NAME", nullable=false) - @OrderBy("asc") - private String PolicyName; - - @Column(name="VERSIONEXTENSION", nullable=false) - @OrderBy("asc") - private String VersionExtension; - - @Column(name="POLICY_SCORE", nullable=true) - private String PolicyScore; - - public PolicyScore() { - - } - - public PolicyScore(String pName, String pScore) { - this(domain); - - } - public PolicyScore(String domain) { - - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - public String getPolicyName() { - return PolicyName; - } - public void setPolicyName(String policyName) { - PolicyName = policyName; - } - public String getVersionExtension() { - return VersionExtension; - } - - public void setVersionExtension(String versionExtension) { - VersionExtension = versionExtension; - } - public String getPolicyScore() { - return PolicyScore; - } - public void setPolicyScore(String policyScore) { - PolicyScore = policyScore; - } - - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyVersion.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyVersion.java deleted file mode 100644 index 4355693f3..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PolicyVersion.java +++ /dev/null @@ -1,183 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -//import java.sql.Clob; -import java.sql.Timestamp; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.NamedQueries; -import javax.persistence.NamedQuery; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - - -@Entity -@Table(name="PolicyVersion") -@NamedQueries({ - @NamedQuery(name="PolicyVersion.findAll", query="SELECT p FROM PolicyVersion p"), - @NamedQuery(name="PolicyVersion.deleteAll", query="DELETE FROM PolicyVersion WHERE 1=1"), - @NamedQuery(name="PolicyVersion.findByPolicyName", query="Select p from PolicyVersion p where p.policyName=:pname"), - @NamedQuery(name="PolicyVersion.findAllCount", query="SELECT COUNT(p) FROM PolicyVersion p") -}) -public class PolicyVersion implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - - @Column(name="id") - private int id; - - @Column(name="POLICY_NAME", nullable=false, length=255) - private String policyName; - - @Column(name="ACTIVE_VERSION") - private int activeVersion; - - @Column(name="HIGHEST_VERSION") - private int higherVersion; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", nullable=false) - private Date createdDate; - - - public int getActiveVersion() { - return activeVersion; - } - - public void setActiveVersion(int activeVersion) { - this.activeVersion = activeVersion; - } - - public int getHigherVersion() { - return higherVersion; - } - - public void setHigherVersion(int higherVersion) { - this.higherVersion = higherVersion; - } - - @Column(name="CREATED_BY", nullable=false, length=45) - private String createdBy; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - - @Column(name="modified_by", nullable=false, length=45) - private String modifiedBy; - - public PolicyVersion(String domain, String loginUserId) { - this(domain); - this.createdBy = loginUserId; - this.modifiedBy = loginUserId; - } - - public PolicyVersion(String domain) { - this.policyName = domain; - } - - public PolicyVersion(){ - - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - /* - * The modifiedBy must be set via the setModifiedBy() method since PolicyVersion - * has been moved to XACML-REST module for access from the XACML-PAP-REST module - - String userid = ((XacmlAdminUI) UI.getCurrent()).getLoginUserId(); - this.modifiedBy =userid; - * - */ - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getPolicyName() { - return policyName; - } - - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - - public Date getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Timestamp createdDate) { - this.createdDate = createdDate; - } - - public String getCreatedBy() { - return createdBy; - } - - public void setCreatedBy(String createdBy) { - this.createdBy = createdBy; - } - - public Date getModifiedDate() { - return modifiedDate; - } - - public void setModifiedDate(Timestamp modifiedDate) { - this.modifiedDate = modifiedDate; - } - - public String getModifiedBy() { - return modifiedBy; - } - - public void setModifiedBy(String modifiedBy) { - this.modifiedBy = modifiedBy; - } - -} - diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PortList.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PortList.java deleted file mode 100644 index 7bc4cf46a..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PortList.java +++ /dev/null @@ -1,104 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - -@Entity -@Table(name="portlist") -@NamedQuery(name="PortList.findAll", query="SELECT e FROM PortList e ") -public class PortList implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="portname", nullable=false) - @OrderBy("asc") - private String portName; - - @Column(name="description") - private String description; -/* - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate;*/ - - public PortList() { - - } - public PortList(String string, String userid) { - this(domain); - - } - public PortList(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getPortName() { - return this.portName; - } - - public void setPortName(String portName) { - this.portName = portName; - - } - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PrefixList.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PrefixList.java deleted file mode 100644 index e94afd4f1..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/PrefixList.java +++ /dev/null @@ -1,114 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - -@Entity -@Table(name="PrefixList") -@NamedQuery(name="PrefixList.findAll", query="SELECT e FROM PrefixList e ") -public class PrefixList implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="pl_name", nullable=false) - @OrderBy("asc") - private String prefixListName; - - @Column(name="description", nullable=false) - private String description; - - @Column(name="pl_value", nullable=false) - private String prefixListValue; -/* - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate;*/ - - public PrefixList() { - - } - public PrefixList(String string, String userid) { - this(domain); - - } - public PrefixList(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - public String getPrefixListName() { - return this.prefixListName; - } - - public void setPrefixListName(String prefixListName) { - this.prefixListName = prefixListName; - - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - - } - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getPrefixListValue() { - return this.prefixListValue; - } - - public void setPrefixListValue(String prefixListValue) { - this.prefixListValue = prefixListValue; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ProtocolList.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ProtocolList.java deleted file mode 100644 index d7cba8ffe..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ProtocolList.java +++ /dev/null @@ -1,105 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - -@Entity -@Table(name="protocollist") -@NamedQuery(name="ProtocolList.findAll", query="SELECT e FROM ProtocolList e ") -public class ProtocolList implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="protocolname", nullable=false) - @OrderBy("asc") - private String protocolName; - - @Column(name="description") - private String description; -/* - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate;*/ - - public ProtocolList() { - - } - public ProtocolList(String string, String userid) { - this(domain); - - } - public ProtocolList(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - public String getProtocolName() { - return this.protocolName; - } - - public void setProtocolName(String protocolName) { - this.protocolName = protocolName; - - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RainyDayTreatments.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RainyDayTreatments.java deleted file mode 100644 index 7219c7d36..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RainyDayTreatments.java +++ /dev/null @@ -1,118 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -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.OrderBy; -import javax.persistence.Table; - -import java.io.Serializable; - -/** - * The persistent class for the RainyDayTreatment database table. - * - */ -@Entity -@Table(name="RainyDayTreatments") -@NamedQuery(name="RainyDayTreatments.findAll", query="SELECT e FROM RainyDayTreatments e") -public class RainyDayTreatments implements Serializable { - /** - * - */ - private static final long serialVersionUID = -2491410352490381323L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="bbid", nullable=false, length=255) - @OrderBy("asc") - private String bbid; - - @Column(name="workstep", nullable=true, length=255) - private String workstep; - - @Column(name="treatments", nullable=true, length=1028) - private String treatments; - - public RainyDayTreatments() { - - } - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - /** - * @return the bbid - */ - public String getBbid() { - return bbid; - } - - /** - * @param bbid the bbid to set - */ - public void setBbid(String bbid) { - this.bbid = bbid; - } - - /** - * @return the workstep - */ - public String getWorkstep() { - return workstep; - } - - /** - * @param workstep the workstep to set - */ - public void setWorkstep(String workstep) { - this.workstep = workstep; - } - - /** - * @return the treatments - */ - public String getTreatments() { - return treatments; - } - - /** - * @param treatments the treatments to set - */ - public void setTreatments(String treatments) { - this.treatments = treatments; - } - - -} \ No newline at end of file diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RemoteCatalogValues.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RemoteCatalogValues.java deleted file mode 100644 index b2b4df75b..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RemoteCatalogValues.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - - -@Entity -@Table(name="RemoteCatalogValues") -@NamedQuery(name="RemoteCatalogValues.findAll", query="SELECT e FROM RemoteCatalogValues e ") -public class RemoteCatalogValues implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String name; - - @Column(name="value") - private String value; - - - public RemoteCatalogValues() { - - } - public RemoteCatalogValues(String string, String userid) { - this(domain); - - } - public RemoteCatalogValues(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RiskType.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RiskType.java deleted file mode 100644 index 077138e1f..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RiskType.java +++ /dev/null @@ -1,172 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - - -@Entity -@Table(name="RiskType") -@NamedQuery(name="RiskType.findAll", query="SELECT e FROM RiskType e ") -public class RiskType implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false, unique=true) - @OrderBy("asc") - private String name; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - private static Log LOGGER = LogFactory.getLog(RiskType.class); - - public RiskType() { - - } - - public RiskType(String string, String userid) { - this(domain); - } - - public RiskType(String domain) { - this.name = domain; - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy =XacmlAdminAuthorization.getUserId(); - } catch (Exception e) { - LOGGER.error("Exception caused While adding Modified by Role"+e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "RiskType", "Exception caused While adding Modified by Role"); - } - } - public String getRiskName() { - return this.name; - } - - public void setRiskName(String riskName) { - this.name = riskName; - - } - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public Date getCreatedDate() { - return this.createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Date getModifiedDate() { - return this.modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RuleAlgorithms.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RuleAlgorithms.java deleted file mode 100644 index 4ec0dff67..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/RuleAlgorithms.java +++ /dev/null @@ -1,125 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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========================================================= - */ - -/* - * AT&T - PROPRIETARY - * THIS FILE CONTAINS PROPRIETARY INFORMATION OF - * AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN - * ACCORDANCE WITH APPLICABLE AGREEMENTS. - * - * Copyright (c) 2014 AT&T Knowledge Ventures - * Unpublished and Not for Publication - * All Rights Reserved - */ -package org.openecomp.policy.rest.jpa; - -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 javax.persistence.Transient; - -import com.att.research.xacml.api.Identifier; - -@Entity -@Table(name="RuleAlgorithms") -@NamedQuery(name="RuleAlgorithms.findAll", query="SELECT d FROM RuleAlgorithms d") -public class RuleAlgorithms implements Serializable { - private static final long serialVersionUID = 1L; - - public static final char STANDARD = 'S'; - public static final char CUSTOM = 'C'; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="is_standard", nullable=false) - private char isStandard; - - @Column(name="xacml_id", nullable=false, unique=true, length=255) - private String xacmlId; - - @Column(name="short_name", nullable=false, length=64) - private String shortName; - - public RuleAlgorithms(Identifier id, char standard) { - if (id != null) { - this.xacmlId = id.stringValue(); - } - this.isStandard = standard; - } - public RuleAlgorithms(Identifier id) { - this(id, RuleAlgorithms.STANDARD); - } - - public RuleAlgorithms() { - this(null, RuleAlgorithms.STANDARD); - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public char getIsStandard() { - return this.isStandard; - } - - public void setIsStandard(char isStandard) { - this.isStandard = isStandard; - } - - @Transient - public boolean isStandard() { - return (this.isStandard == RuleAlgorithms.STANDARD); - } - - @Transient - public boolean isCustom() { - return (this.isStandard == RuleAlgorithms.CUSTOM); - } - - public String getXacmlId() { - return this.xacmlId; - } - - public void setXacmlId(String xacmlId) { - this.xacmlId = xacmlId; - } - - public String getShortName() { - return shortName; - } - - public void setShortName(String shortName) { - this.shortName = shortName; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/SafePolicyWarning.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/SafePolicyWarning.java deleted file mode 100644 index 8d3a0f277..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/SafePolicyWarning.java +++ /dev/null @@ -1,109 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - - -@Entity -@Table(name="SafePolicyWarning") -@NamedQuery(name="SafePolicyWarning.findAll", query="SELECT e FROM SafePolicyWarning e ") -public class SafePolicyWarning implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String name; - - @Column(name="message") - private String message ; - - @Column(name="riskType") - private String riskType ; - - public String getRiskType() { - return riskType; - } - public void setRiskType(String riskType) { - this.riskType = riskType; - } - public SafePolicyWarning() { - - } - public SafePolicyWarning(String string, String userid) { - this(domain); - - } - public SafePolicyWarning(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getName() { - return this.name; - } - - public String getMessage() { - return message; - } - public void setMessage(String message) { - this.message = message; - } - public void setName(String name) { - this.name = name; - - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/SecurityZone.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/SecurityZone.java deleted file mode 100644 index 5de032f8f..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/SecurityZone.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - -@Entity -@Table(name="securityzone") -@NamedQuery(name="SecurityZone.findAll", query="SELECT e FROM SecurityZone e ") -public class SecurityZone implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String zoneName; - - @Column(name="value") - private String zoneValue; - - - public SecurityZone() { - - } - public SecurityZone(String string, String userid) { - this(domain); - - } - public SecurityZone(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getZoneName() { - return this.zoneName; - } - - public void setZoneName(String zoneName) { - this.zoneName = zoneName; - - } - public String getZoneValue() { - return this.zoneValue; - } - - public void setZoneValue(String zoneValue) { - this.zoneValue = zoneValue; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ServiceList.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ServiceList.java deleted file mode 100644 index b3e473b1a..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/ServiceList.java +++ /dev/null @@ -1,154 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - -@Entity -@Table(name="servicegroup") -@NamedQuery(name="ServiceList.findAll", query="SELECT e FROM ServiceList e ") -public class ServiceList implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String serviceName; - - @Column(name="description") - private String serviceDesc; - - @Column(name="type") - private String serviceType; - - @Column(name="transportprotocol") - private String serviceTrasProtocol; - - @Column(name="appprotocol ") - private String serviceAppProtocol; - - @Column(name="ports") - private String servicePorts; - - - -/* - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate;*/ - - public ServiceList() { - - } - public ServiceList(String string, String userid) { - this(domain); - - } - public ServiceList(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getServiceName() { - return this.serviceName; - } - - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - - } - - public String getServiceDescription() { - return this.serviceDesc; - } - - public void setServiceDescription(String serviceDesc) { - this.serviceDesc = serviceDesc; - - } - - public String getServiceType() { - return this.serviceType; - } - - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - - public String getServiceTransProtocol() { - return this.serviceTrasProtocol; - } - - public void setServiceTransProtocol(String serviceTrasProtocol) { - this.serviceTrasProtocol = serviceTrasProtocol; - - } - - public String getServiceAppProtocol() { - return this.serviceAppProtocol; - } - - public void setServiceAppProtocol(String serviceAppProtocol) { - this.serviceAppProtocol = serviceAppProtocol; - - } - public String getServicePorts() { - return this.servicePorts; - } - - public void setServicePorts(String servicePorts) { - this.servicePorts = servicePorts; - - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/SystemLogDB.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/SystemLogDB.java deleted file mode 100644 index 6fa91ee03..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/SystemLogDB.java +++ /dev/null @@ -1,163 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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========================================================= - */ - -/* - * AT&T - PROPRIETARY - * THIS FILE CONTAINS PROPRIETARY INFORMATION OF - * AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN - * ACCORDANCE WITH APPLICABLE AGREEMENTS. - * - * Copyright (c) 2013 AT&T Knowledge Ventures - * Unpublished and Not for Publication - * All Rights Reserved - */ -package org.openecomp.policy.rest.jpa; - -import java.io.Serializable; -import java.util.Date; - -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 javax.persistence.Temporal; -import javax.persistence.TemporalType; - -/** - * The persistent class for the system log database table. - * -*/ -@Entity -@Table(name="SystemLogDB") -@NamedQuery(name="SystemLogDB.findAll", query="SELECT o FROM SystemLogDB o") -public class SystemLogDB implements Serializable { - private static final long serialVersionUID = 1L; - - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="type", nullable=false) - private String type; - - @Column(name="system", nullable=false, length=255) - private String system; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Column(name="remote", nullable=false, length=255) - private String remote; - - @Column(name="logtype", nullable=false, length=255) - private String logtype; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="date", nullable=false, updatable=false) - private Date date; - - public SystemLogDB() { - super(); - } - - public SystemLogDB(int id, String system, String description, String remote, - String type, String logtype) { - this.id = id; - this.system = system; - this.description = description; - this.remote = remote; - this.type = type; - this.logtype = logtype; - } - - public void SystemLogB (int id, String system, String description, String remote, String type, Date date, String logtype){ - this.id = id; - this.system = system; - this.description = description; - this.remote = remote; - this.type = type; - this.date = date; - this.logtype = logtype; - - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public Date getDate(){ - return this.date; - } - - public void setDate(Date date){ - this.date = date; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getType() { - return this.type; - } - - public void setType(String type) { - this.type = type; - - } - - public String getSystem() { - return this.system; - } - - public void setSystem(String system) { - this.system = system; - } - - public String getRemote() { - return this.remote; - } - - public void setRemote(String remote) { - this.remote = remote; - - } - public String getLogtype() { - return this.logtype; - } - - public void setLogtype(String logtype) { - this.logtype = logtype; - - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/TermList.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/TermList.java deleted file mode 100644 index 38bbf793a..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/TermList.java +++ /dev/null @@ -1,261 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - - -@Entity -@Table(name="TERM") -@NamedQuery(name="TermList.findAll", query="SELECT e FROM TermList e") -public class TermList implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="termName", nullable=false) - @OrderBy("asc") - private String termName; - - @Column(name="description") - private String termDescription; - - @Column(name="fromzone") - private String fromZone; - - @Column(name="tozone") - private String toZone; - - @Column(name="srcIPList") - private String srcIPList; - - @Column(name="destIPList") - private String destIPList; - - @Column(name="protocolList") - private String protocolList; - - @Column(name="portList") - private String portList; - - @Column(name="srcPortList") - private String srcPortList; - - @Column(name="destPortList") - private String destPortList; - - @Column(name="action") - private String action; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - private static Log LOGGER = LogFactory.getLog(TermList.class); - - public TermList() { - - } - - private static final Log auditLogger = LogFactory - .getLog("auditLogger"); - - public TermList(String string, String userid) { - this(domain); - } - public TermList(String domain) { - this.termName = domain; - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - auditLogger.debug("Added New Term Name: "+this.termName+" by "+this.userCreatedBy); - - } - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy =XacmlAdminAuthorization.getUserId();; - } catch (Exception e) { - LOGGER.error("Exception caused While adding Modified by Role"+e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "TermList", "Exception caused While adding Modified by Role"); - } - auditLogger.debug("Updated Term Name: "+this.termName+" by "+this.userModifiedBy); - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getTermName() { - return this.termName; - } - - public void setTermName(String termName) { - this.termName = termName; - } - - public String getTermDescription() { - return this.termDescription; - } - - public void setDescription(String termDescription) { - this.termDescription = termDescription; - } - - public String getFromZone() { - return this.fromZone; - } - - public void setFromZones(String fromZone) { - this.fromZone = fromZone; - } - - public String getToZone() { - return this.toZone; - } - - public void setToZones(String toZone) { - this.toZone = toZone; - } - - public String getSrcIPList() { - return this.srcIPList; - } - - public void setSrcIPList(String srcIPList) { - this.srcIPList = srcIPList; - } - - public String getDestIPList() { - return this.destIPList; - } - - public void setDestIPList(String destIPList) { - this.destIPList = destIPList; - } - - public String getProtocolList() { - return this.protocolList; - } - - public void setProtocolList(String protocolList) { - this.protocolList = protocolList; - } - - public String getPortList() { - return this.portList; - } - - public void setPortList(String portList) { - this.portList = portList; - } - - public String getSrcPortList() { - return this.srcPortList; - } - - public void setSrcPortList(String srcPortList) { - this.srcPortList = srcPortList; - } - - public String getDestPortList() { - return this.destPortList; - } - - public void setDestPortList(String destPortList) { - this.destPortList = destPortList; - } - - - public String getAction() { - return this.action; - } - - public void setAction(String action) { - this.action = action; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/UserInfo.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/UserInfo.java deleted file mode 100644 index 9dd771e6c..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/UserInfo.java +++ /dev/null @@ -1,76 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.NamedQuery; -import javax.persistence.Table; -import javax.persistence.Transient; - -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.std.IdentifierImpl; -import com.fasterxml.jackson.annotation.JsonBackReference; - -@Entity -@Table(name = "UserInfo") -@NamedQuery(name="UserInfo.findAll", query="SELECT u FROM UserInfo u ") -public class UserInfo implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - @Column(name="loginid", nullable=false, length=45) - private String userLoginId; - - @Column(name = "name", nullable = false, unique = true) - private String userName; - - public UserInfo(){ - this.userLoginId = userName; - - } - - public String getUserLoginId() { - return userLoginId; - } - - public void setUserLoginId(String loginid) { - this.userLoginId = loginid; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - - @Transient - @JsonBackReference - public Identifier getIdentiferByUserId() { - return new IdentifierImpl(this.userName); - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VMType.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VMType.java deleted file mode 100644 index e7ae197fc..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VMType.java +++ /dev/null @@ -1,102 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - - -@Entity -@Table(name="VMType") -@NamedQuery(name="VMType.findAll", query="SELECT e FROM VMType e ") -public class VMType implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="name", nullable=false) - @OrderBy("asc") - private String name; - - @Column(name="description") - private String description; - - - public VMType() { - - } - public VMType(String string, String userid) { - this(domain); - - } - public VMType(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VNFType.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VNFType.java deleted file mode 100644 index 693e27553..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VNFType.java +++ /dev/null @@ -1,173 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - - - -@Entity -@Table(name="VNFType") -@NamedQuery(name="VNFType.findAll", query="SELECT v FROM VNFType v ") -public class VNFType implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="vnf_type", nullable=false, unique=true) - @OrderBy("asc") - private String vnftype; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - private static Log LOGGER = LogFactory.getLog(VNFType.class); - - public VNFType() { - - } - - public String getVnftype() { - return vnftype; - } - - public void setVnftype(String vnftype) { - this.vnftype = vnftype; - } - - public VNFType(String string, String userid) { - this(domain); - } - - public VNFType(String domain) { - this.vnftype = domain; - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy =XacmlAdminAuthorization.getUserId();; - } catch (Exception e) { - LOGGER.error("Exception caused While adding Modified by Role"+e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "VNFType", "Exception caused While adding Modified by Role"); - } - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public Date getCreatedDate() { - return this.createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Date getModifiedDate() { - return this.modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VSCLAction.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VSCLAction.java deleted file mode 100644 index 7f42650a3..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VSCLAction.java +++ /dev/null @@ -1,173 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - - -@Entity -@Table(name="VSCLAction") -@NamedQuery(name="VSCLAction.findAll", query="SELECT v FROM VSCLAction v ") -public class VSCLAction implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="vscl_action", nullable=false, unique=true) - @OrderBy("asc") - private String vsclaction; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Column(name="description", nullable=true, length=2048) - private String description; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - private static Log LOGGER = LogFactory.getLog(VSCLAction.class); - - public VSCLAction() { - - } - - public VSCLAction(String string, String userid) { - this(domain); - } - - public VSCLAction(String domain) { - this.vsclaction = domain; - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy =XacmlAdminAuthorization.getUserId();; - } catch (Exception e) { - LOGGER.error("Exception caused While adding Modified by Role"+e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "VSCLAction", "Exception caused While adding Modified by Role"); - } - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getVsclaction() { - return vsclaction; - } - - public void setVsclaction(String vsclaction) { - this.vsclaction = vsclaction; - } - - - public Date getCreatedDate() { - return this.createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public Date getModifiedDate() { - return this.modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VarbindDictionary.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VarbindDictionary.java deleted file mode 100644 index 1bb56a067..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/VarbindDictionary.java +++ /dev/null @@ -1,184 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; - -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.NamedQuery; -import javax.persistence.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; -import javax.persistence.Temporal; -import javax.persistence.TemporalType; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.rest.XacmlAdminAuthorization; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - -@Entity -@Table(name="VarbindDictionary") -@NamedQuery(name = "VarbindDictionary.findAll", query = "Select v FROM VarbindDictionary v") -public class VarbindDictionary implements Serializable{ - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name = "Id") - private int id; - - @Column(name ="varbind_Name", nullable = false, unique = true) - @OrderBy("asc") - private String varbindName; - - @Column(name = "varbind_Description", nullable = true, length = 2048) - private String varbindDescription; - - @Column(name = "varbind_oid", nullable = false) - private String varbindOID; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="created_date", updatable=false) - private Date createdDate; - - @Temporal(TemporalType.TIMESTAMP) - @Column(name="modified_date", nullable=false) - private Date modifiedDate; - - @ManyToOne(optional = false) - @JoinColumn(name="created_by") - private UserInfo userCreatedBy; - - @ManyToOne(optional = false) - @JoinColumn(name="modified_by") - private UserInfo userModifiedBy; - - public UserInfo getUserCreatedBy() { - return userCreatedBy; - } - - public void setUserCreatedBy(UserInfo userCreatedBy) { - this.userCreatedBy = userCreatedBy; - } - - public UserInfo getUserModifiedBy() { - return userModifiedBy; - } - - public void setUserModifiedBy(UserInfo userModifiedBy) { - this.userModifiedBy = userModifiedBy; - } - - private static Log LOGGER = LogFactory.getLog(VarbindDictionary.class); - - public VarbindDictionary() { - - } - - public VarbindDictionary(String string, String userid) { - this(domain); - } - - public VarbindDictionary(String domain) { - this.varbindName = domain; - } - - @PrePersist - public void prePersist() { - Date date = new Date(); - this.createdDate = date; - this.modifiedDate = date; - } - - @PreUpdate - public void preUpdate() { - this.modifiedDate = new Date(); - try { - this.userModifiedBy =XacmlAdminAuthorization.getUserId();; - } catch (Exception e) { - LOGGER.error("Exception caused While adding Modified by Role"+e); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "VarbindDictionary", "Exception caused While adding Modified by Role"); - } - } - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - - public String getVarbindName() { - return varbindName; - } - - public void setVarbindName(String varbindName) { - this.varbindName = varbindName; - } - - public String getVarbindDescription() { - return varbindDescription; - } - - public void setVarbindDescription(String varbindDescription) { - this.varbindDescription = varbindDescription; - } - - public String getVarbindOID() { - return varbindOID; - } - - public void setVarbindOID(String varbindOID) { - this.varbindOID = varbindOID; - } - - public Date getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Date createdDate) { - this.createdDate = createdDate; - } - - public Date getModifiedDate() { - return modifiedDate; - } - - public void setModifiedDate(Date modifiedDate) { - this.modifiedDate = modifiedDate; - } - - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/WatchPolicyNotificationTable.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/WatchPolicyNotificationTable.java deleted file mode 100644 index 2acc82cce..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/WatchPolicyNotificationTable.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - * - * - * */ - -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.OrderBy; -import javax.persistence.Table; - -@Entity -@Table(name = "WatchPolicyNotificationTable") -@NamedQuery(name="WatchPolicyNotificationTable.findAll", query="SELECT e FROM WatchPolicyNotificationTable e ") -public class WatchPolicyNotificationTable implements Serializable{ - private static final long serialVersionUID = 1L; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="policyName", nullable=false, unique=true) - @OrderBy("asc") - private String policyName; - - @Column(name="loginIds", nullable=false, unique=true) - @OrderBy("asc") - private String loginIds; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getPolicyName() { - return policyName; - } - - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - - public String getLoginIds() { - return loginIds; - } - - public void setLoginIds(String loginIds) { - this.loginIds = loginIds; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Zone.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Zone.java deleted file mode 100644 index 30e02e06d..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/Zone.java +++ /dev/null @@ -1,101 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; -/* - */ -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.OrderBy; -import javax.persistence.PrePersist; -import javax.persistence.PreUpdate; -import javax.persistence.Table; - -@Entity -@Table(name="zone") -@NamedQuery(name="Zone.findAll", query="SELECT e FROM Zone e ") -public class Zone implements Serializable { - private static final long serialVersionUID = 1L; - - private static String domain; - - @Id - @GeneratedValue(strategy = GenerationType.AUTO) - @Column(name="id") - private int id; - - @Column(name="zonename", nullable=false) - @OrderBy("asc") - private String zoneName; - - @Column(name="zonevalue") - private String zoneValue; - - - public Zone() { - - } - public Zone(String string, String userid) { - this(domain); - - } - public Zone(String domain) { - - } - - @PrePersist - public void prePersist() { - - } - @PreUpdate - public void preUpdate() { - } - - - public int getId() { - return this.id; - } - - public void setId(int id) { - this.id = id; - } - public String getZoneName() { - return this.zoneName; - } - - public void setZoneName(String zoneName) { - this.zoneName = zoneName; - - } - public String getZoneValue() { - return this.zoneValue; - } - - public void setZoneValue(String zoneValue) { - this.zoneValue = zoneValue; - } - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/package-info.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/package-info.java deleted file mode 100644 index 4e77ba9e7..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/jpa/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.jpa; diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/LockdownListener.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/LockdownListener.java deleted file mode 100644 index a44ef63d8..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/LockdownListener.java +++ /dev/null @@ -1,36 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.util; - -public interface LockdownListener { - /** - * lockdown has been set in database - */ - public void lockdownSet(); - - /** - * lockdown has been unset in the database - */ - public void lockdownUnset(); -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSAttributeObject.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSAttributeObject.java deleted file mode 100644 index adf1fae8c..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSAttributeObject.java +++ /dev/null @@ -1,109 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.util; - -import java.util.HashMap; -import java.util.Map; - -public class MSAttributeObject { - - private String className; - private HashMap attribute = new HashMap<>(); - private HashMap refAttribute = new HashMap<>(); - private HashMap subClass = new HashMap<>(); - private String dependency; - private HashMap enumType = new HashMap<>(); - private HashMap matchingSet = new HashMap<>(); - private boolean policyTempalate; - - public Map getRefAttribute() { - return refAttribute; - } - public void setRefAttribute(HashMap refAttribute) { - this.refAttribute = refAttribute; - } - public String getClassName() { - return className; - } - public void setClassName(String className) { - this.className = className; - } - public Map getAttribute() { - return attribute; - } - public void setAttribute(HashMap attribute) { - this.attribute = attribute; - } - public HashMap getEnumType() { - return enumType; - } - public void setEnumType(HashMap enumType) { - this.enumType = enumType; - } - public void addAttribute(String key, String value){ - this.attribute.put(key, value); - } - public void addRefAttribute(String key, String value){ - this.refAttribute.put(key, value); - } - public void addAllAttribute(Map map){ - this.attribute.putAll(map); - } - public void addAllRefAttribute(Map map){ - this.refAttribute.putAll(map); - } - public HashMap getSubClass() { - return subClass; - } - public void setSubClass(HashMap subClass) { - this.subClass = subClass; - } - public void addAllSubClass(HashMap subClass){ - this.subClass.putAll(subClass); - } - public String getDependency() { - return dependency; - } - public void setDependency(String dependency) { - this.dependency = dependency; - } - public void addSingleEnum(String key, String value){ - this.enumType.put(key, value); - } - public HashMap getMatchingSet() { - return matchingSet; - } - public void setMatchingSet(HashMap matchingSet) { - this.matchingSet = matchingSet; - } - public void addMatchingSet(String key, String value){ - this.matchingSet.put(key, value); - } - public void addMatchingSet(HashMap matchingSet){ - this.matchingSet.putAll(matchingSet); - } - public boolean isPolicyTempalate() { - return policyTempalate; - } - public void setPolicyTempalate(boolean policyTempalate) { - this.policyTempalate = policyTempalate; - } -} \ No newline at end of file diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSAttributeValue.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSAttributeValue.java deleted file mode 100644 index cce8f7619..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSAttributeValue.java +++ /dev/null @@ -1,60 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.util; - -public class MSAttributeValue{ - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - public Boolean getRequired() { - return required; - } - public void setRequired(Boolean required) { - this.required = required; - } - public Boolean getArrayValue() { - return arrayValue; - } - public void setArrayValue(Boolean arrayValue) { - this.arrayValue = arrayValue; - } - public String getDefaultValue() { - return defaultValue; - } - public void setDefaultValue(String defaultValue) { - this.defaultValue = defaultValue; - } - private String name; - private String type; - private Boolean required; - private Boolean arrayValue; - private String defaultValue; - -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSModelUtils.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSModelUtils.java deleted file mode 100644 index 711abe59c..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/MSModelUtils.java +++ /dev/null @@ -1,701 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.util; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.commons.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.eclipse.emf.common.util.EList; -import org.eclipse.emf.common.util.EMap; -import org.eclipse.emf.common.util.Enumerator; -import org.eclipse.emf.common.util.TreeIterator; -import org.eclipse.emf.common.util.URI; -import org.eclipse.emf.ecore.EAnnotation; -import org.eclipse.emf.ecore.EClass; -import org.eclipse.emf.ecore.EClassifier; -import org.eclipse.emf.ecore.EEnum; -import org.eclipse.emf.ecore.EEnumLiteral; -import org.eclipse.emf.ecore.EObject; -import org.eclipse.emf.ecore.EPackage; -import org.eclipse.emf.ecore.EReference; -import org.eclipse.emf.ecore.EStructuralFeature; -import org.eclipse.emf.ecore.impl.EAttributeImpl; -import org.eclipse.emf.ecore.impl.EEnumImpl; -import org.eclipse.emf.ecore.resource.Resource; -import org.eclipse.emf.ecore.resource.ResourceSet; -import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; -import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; -import org.json.JSONObject; -import org.openecomp.policy.rest.XACMLRestProperties; - -import com.att.research.xacml.util.XACMLProperties; -import com.google.gson.Gson; - - -public class MSModelUtils { - - private static final Log logger = LogFactory.getLog(MSModelUtils.class); - - private HashMap classMap = new HashMap<>(); - private HashMap enumMap = new HashMap<>(); - private HashMap matchingClass = new HashMap<>(); - private String configuration = "configuration"; - private String dictionary = "dictionary"; - private String ecomp = ""; - private String policy = ""; - private String eProxyURI = "eProxyURI:"; - - public MSModelUtils(String ecomp, String policy){ - this.ecomp = ecomp; - this.policy = policy; - } - - private enum ANNOTATION_TYPE{ - MATCHING, VALIDATION, DICTIONARY - }; - - public enum MODEL_TYPE { - XMI - }; - - - public HashMap processEpackage(String file, MODEL_TYPE model){ - if (model == MODEL_TYPE.XMI ){ - processXMIEpackage(file); - } - return classMap; - - } - - private void processXMIEpackage(String xmiFile){ - EPackage root = getEpackage(xmiFile); - TreeIterator treeItr = root.eAllContents(); - String className = null; - String returnValue = null; - - // Pulling out dependency from file - while (treeItr.hasNext()) { - EObject obj = (EObject) treeItr.next(); - if (obj instanceof EClassifier) { - EClassifier eClassifier = (EClassifier) obj; - className = eClassifier.getName(); - - if (obj instanceof EEnum) { - enumMap.putAll(getEEnum(obj)); - }else if (obj instanceof EClass) { - String temp = getDependencyList(eClassifier, className).toString(); - returnValue = StringUtils.replaceEach(temp, new String[]{"[", "]"}, new String[]{"", ""}); - getAttributes(className, returnValue, root); - } - } - } - - if (!enumMap.isEmpty()){ - addEnumClassMap(); - } - if (!matchingClass.isEmpty()){ - CheckForMatchingClass(); - } - } - - private void CheckForMatchingClass() { - HashMap tempAttribute = new HashMap<>(); - - for (Entry set : matchingClass.entrySet()){ - String key = set.getKey(); - if (classMap.containsKey(key)){ - Map listAttributes = classMap.get(key).getAttribute(); - Map listRef = classMap.get(key).getRefAttribute(); - for ( Entry eSet : listAttributes.entrySet()){ - String key2 = eSet.getKey(); - tempAttribute.put(key2, "matching-true"); - } - for ( Entry eSet : listRef.entrySet()){ - String key3 = eSet.getKey(); - tempAttribute.put(key3, "matching-true"); - } - - } - UpdateMatching(tempAttribute, key); - } - - } - - - - private void UpdateMatching(HashMap tempAttribute, String key) { - Map newClass = null; - - newClass = classMap; - - for (Entry updateClass : newClass.entrySet()){ - HashMap valueMap = updateClass.getValue().getMatchingSet(); - String keymap = updateClass.getKey(); - if (valueMap.containsKey(key)){ - HashMap modifyMap = classMap.get(keymap).getMatchingSet(); - modifyMap.remove(key); - modifyMap.putAll(tempAttribute); - classMap.get(keymap).setMatchingSet(modifyMap); - } - - } - } - - private void addEnumClassMap() { - for (Entry value :classMap.entrySet()){ - value.getValue().setEnumType(enumMap); - } - } - - private EPackage getEpackage(String xmiFile) { - ResourceSet resSet = new ResourceSetImpl(); - Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE; - Map m = reg.getExtensionToFactoryMap(); - m.put("xmi", new XMIResourceFactoryImpl()); - Resource resource = resSet.getResource(URI.createFileURI(xmiFile), true); - try { - resource.load(Collections.EMPTY_MAP); - } catch (IOException e) { - logger.error("Error loading Encore Resource for new Model" + e); - } - - EPackage root = (EPackage) resource.getContents().get(0); - - return root; - } - - private HashMap getEEnum(EObject obj) { - List valueList = new ArrayList<>(); - HashMap returnMap = new HashMap<>(); - EEnum eenum = (EEnum)obj; - - String name = eenum.getName(); - for (EEnumLiteral eEnumLiteral : eenum.getELiterals()) - { - Enumerator instance = eEnumLiteral.getInstance(); - String value = instance.getLiteral(); - valueList.add(value); - } - returnMap.put(name, valueList.toString()); - return returnMap; - } - - public void getAttributes(String className, String dependency, EPackage root) { - List dpendList = new ArrayList<>(); - if (dependency!=null){ - dpendList = new ArrayList(Arrays.asList(dependency.split(","))); - } - MSAttributeObject msAttributeObject = new MSAttributeObject(); - msAttributeObject.setClassName(className); - String extendClass = getSubTypes(root, className); - HashMap returnRefList = getRefAttributeList(root, className, extendClass); - HashMap returnAttributeList = getAttributeList(root, className, extendClass); - HashMap returnSubList = getSubAttributeList(root, className, extendClass); - HashMap returnAnnotation = getAnnotation(root, className, extendClass); - msAttributeObject.setAttribute(returnAttributeList); - msAttributeObject.setRefAttribute(returnRefList); - msAttributeObject.setSubClass(returnSubList); - msAttributeObject.setDependency(dpendList.toString()); - msAttributeObject.addMatchingSet(returnAnnotation); - msAttributeObject.setPolicyTempalate(isPolicyTemplate(root, className)); - - this.classMap.put(className, msAttributeObject); - } - - private HashMap getAnnotation(EPackage root, String className, String extendClass) { - TreeIterator treeItr = root.eAllContents(); - boolean requiredAttribute = false; - boolean requiredMatchAttribute = false; - HashMap annotationSet = new HashMap<>(); - String matching = null; - String range = null; - String dictionary = null; - - // Pulling out dependency from file - while (treeItr.hasNext()) { - EObject obj = treeItr.next(); - if (obj instanceof EClassifier) { - requiredAttribute = isRequiredAttribute(obj, className ); - requiredMatchAttribute = isRequiredAttribute(obj, extendClass ); - } - - if (requiredAttribute){ - if (obj instanceof EStructuralFeature) { - EStructuralFeature eStrucClassifier = (EStructuralFeature) obj; - if (eStrucClassifier.getEAnnotations().size() != 0) { - matching = annotationValue(eStrucClassifier, ANNOTATION_TYPE.MATCHING, policy); - if (matching!=null){ - annotationSet.put(eStrucClassifier.getName(), matching); - } - range = annotationValue(eStrucClassifier, ANNOTATION_TYPE.VALIDATION, policy); - if (range!=null){ - annotationSet.put(eStrucClassifier.getName(), range); - } - dictionary = annotationValue(eStrucClassifier, ANNOTATION_TYPE.DICTIONARY, policy); - if (dictionary!=null){ - annotationSet.put(eStrucClassifier.getName(), dictionary); - } - } - } - } else if (requiredMatchAttribute){ - if (obj instanceof EStructuralFeature) { - EStructuralFeature eStrucClassifier = (EStructuralFeature) obj; - if (eStrucClassifier.getEAnnotations().size() != 0) { - matching = annotationValue(eStrucClassifier, ANNOTATION_TYPE.MATCHING, policy); - if (matching!=null){ - if (obj instanceof EReference){ - EClass refType = ((EReference) obj).getEReferenceType(); - annotationSet.put(refType.getName(), matching); - matchingClass.put(refType.getName(), matching); - }else{ - annotationSet.put(eStrucClassifier.getName(), matching); - } - } - } - } - } - } - return annotationSet; - } - - private HashMap getSubAttributeList(EPackage root, String className , String superClass) { - TreeIterator treeItr = root.eAllContents(); - boolean requiredAttribute = false; - HashMap subAttribute = new HashMap(); - int rollingCount = 0; - int processClass = 0; - boolean annotation = false; - - // Pulling out dependency from file - while (treeItr.hasNext() && rollingCount < 2) { - - EObject obj = treeItr.next(); - if (obj instanceof EClassifier) { - if (isRequiredAttribute(obj, className ) || isRequiredAttribute(obj, superClass )){ - requiredAttribute = true; - }else { - requiredAttribute = false; - } - if (requiredAttribute){ - processClass++; - } - rollingCount = rollingCount+processClass; - } - - if (requiredAttribute) { - if (obj instanceof EStructuralFeature) { - EStructuralFeature eStrucClassifier = (EStructuralFeature) obj; - if (eStrucClassifier.getEAnnotations().size() != 0) { - annotation = annotationTest(eStrucClassifier, configuration, ecomp); - if (annotation && obj instanceof EReference) { - EClass refType = ((EReference) obj).getEReferenceType(); - if(!refType.toString().contains(eProxyURI)){ - subAttribute.put(eStrucClassifier.getName(), refType.getName()); - } - } - } - } - } - } - return subAttribute; - } - - public String checkDefultValue(String defultValue) { - if (defultValue!=null){ - return ":defaultValue-"+ defultValue; - } - return ":defaultValue-NA"; - - } - - public String checkRequiredPattern(int upper, int lower) { - - String pattern = XACMLProperties.getProperty(XACMLRestProperties.PROP_XCORE_REQUIRED_PATTERN); - - if (pattern!=null){ - if (upper == Integer.parseInt(pattern.split(",")[1]) && lower==Integer.parseInt(pattern.split(",")[0])){ - return ":required-true"; - } - } - - return ":required-false"; - } - - public JSONObject buildJavaObject(HashMap map, String attributeType){ - - JSONObject returnValue = new JSONObject(map); - - return returnValue; - - } - - public HashMap getRefAttributeList(EPackage root, String className, String superClass){ - - TreeIterator treeItr = root.eAllContents(); - boolean requiredAttribute = false; - HashMap refAttribute = new HashMap<>(); - int rollingCount = 0; - int processClass = 0; - boolean annotation = false; - // Pulling out dependency from file - while (treeItr.hasNext()) { - EObject obj = treeItr.next(); - if (obj instanceof EClassifier) { - if (isRequiredAttribute(obj, className ) || isRequiredAttribute(obj, superClass )){ - requiredAttribute = true; - }else { - requiredAttribute = false; - } - if (requiredAttribute){ - processClass++; - } - rollingCount = rollingCount+processClass; - } - - if (requiredAttribute) { - if (obj instanceof EStructuralFeature) { - EStructuralFeature eStrucClassifier = (EStructuralFeature) obj; - if (eStrucClassifier.getEAnnotations().size() != 0) { - annotation = annotationTest(eStrucClassifier, configuration, ecomp); - if ( annotation && obj instanceof EReference) { - EClass refType = ((EReference) obj).getEReferenceType(); - if(refType.toString().contains(eProxyURI)){ - String one = refType.toString().split(eProxyURI)[1]; - String refValue = StringUtils.replaceEach(one.split("#")[1], new String[]{"//", ")"}, new String[]{"", ""}); - refAttribute.put(eStrucClassifier.getName(), refValue); - } else { - String array = arrayCheck(((EStructuralFeature) obj).getUpperBound()); - refAttribute.put(eStrucClassifier.getName(), refType.getName() + array); - } - } else if (annotation && obj instanceof EAttributeImpl){ - EClassifier refType = ((EAttributeImpl) obj).getEType(); - if (refType instanceof EEnumImpl){ - String array = arrayCheck(((EStructuralFeature) obj).getUpperBound()); - refAttribute.put(eStrucClassifier.getName(), refType.getName() + array); } - } - } - } - } - } - return refAttribute; - } - - private boolean annotationTest(EStructuralFeature eStrucClassifier, String annotation, String type) { - String annotationType = null; - EAnnotation eAnnotation = null; - String ecompType = null; - String ecompValue = null; - - EList value = eStrucClassifier.getEAnnotations(); - - for (int i = 0; i < value.size(); i++){ - annotationType = value.get(i).getSource(); - eAnnotation = eStrucClassifier.getEAnnotations().get(i); - ecompType = eAnnotation.getDetails().get(0).getValue(); - ecompValue = eAnnotation.getDetails().get(0).getKey(); - if (annotationType.contains(type) && ecompType.contains(annotation)){ - return true; - } else if (annotationType.contains(type) && ecompValue.contains(annotation)){ - return true; - } - } - - return false; - } - - - private String annotationValue(EStructuralFeature eStrucClassifier, ANNOTATION_TYPE annotation, String type) { - String annotationType = null; - EAnnotation eAnnotation = null; - String ecompType = null; - String ecompValue = null; - - EList value = eStrucClassifier.getEAnnotations(); - - for (int i = 0; i < value.size(); i++){ - annotationType = value.get(i).getSource(); - eAnnotation = eStrucClassifier.getEAnnotations().get(i); - ecompType = eAnnotation.getDetails().get(0).getKey(); - if (annotationType.contains(type) && ecompType.compareToIgnoreCase(annotation.toString())==0){ - ecompValue = eAnnotation.getDetails().get(0).getValue(); - if (annotation == ANNOTATION_TYPE.VALIDATION){ - return ecompValue; - } else { - return ecompType + "-" + ecompValue; - } - } - } - - return ecompValue; - } - public boolean isRequiredAttribute(EObject obj, String className){ - EClassifier eClassifier = (EClassifier) obj; - String workingClass = eClassifier.getName(); - workingClass.trim(); - if (workingClass.equalsIgnoreCase(className)){ - return true; - } - - return false; - } - - private boolean isPolicyTemplate(EPackage root, String className){ - - for (EClassifier classifier : root.getEClassifiers()){ - if (classifier instanceof EClass) { - EClass eClass = (EClass)classifier; - if (eClass.getName().contentEquals(className)){ - EList value = eClass.getEAnnotations(); - for (EAnnotation workingValue : value){ - EMap keyMap = workingValue.getDetails(); - if (keyMap.containsKey("policyTemplate")){ - return true; - } - } - } - } - } - return false; - } - private String getSubTypes(EPackage root, String className) { - String returnSubTypes = null; - for (EClassifier classifier : root.getEClassifiers()){ - if (classifier instanceof EClass) { - EClass eClass = (EClass)classifier; - - for (EClass eSuperType : eClass.getEAllSuperTypes()) - { - if (eClass.getName().contentEquals(className)){ - returnSubTypes = eSuperType.getName(); - } - } - } - } - return returnSubTypes; - } - - public HashMap getAttributeList(EPackage root, String className, String superClass){ - - TreeIterator treeItr = root.eAllContents(); - boolean requiredAttribute = false; - HashMap refAttribute = new HashMap<>(); - boolean annotation = false; - boolean dictionaryTest = false; - String defaultValue = null; - String eType = null; - - // Pulling out dependency from file - while (treeItr.hasNext()) { - EObject obj = treeItr.next(); - if (obj instanceof EClassifier) { - if (isRequiredAttribute(obj, className ) || isRequiredAttribute(obj, superClass )){ - requiredAttribute = true; - }else { - requiredAttribute = false; - } - - } - - if (requiredAttribute){ - if (obj instanceof EStructuralFeature) { - EStructuralFeature eStrucClassifier = (EStructuralFeature) obj; - if (eStrucClassifier.getEAnnotations().size() != 0) { - annotation = annotationTest(eStrucClassifier, configuration, ecomp); - dictionaryTest = annotationTest(eStrucClassifier, dictionary, policy); - EClassifier refType = ((EStructuralFeature) obj).getEType(); - if (annotation && !(obj instanceof EReference) && !(refType instanceof EEnumImpl)) { - String name = eStrucClassifier.getName(); - if (dictionaryTest){ - eType = annotationValue(eStrucClassifier, ANNOTATION_TYPE.DICTIONARY, policy); - }else { - eType = eStrucClassifier.getEType().getInstanceClassName(); - } - defaultValue = checkDefultValue(((EStructuralFeature) obj).getDefaultValueLiteral()); - - String array = arrayCheck(((EStructuralFeature) obj).getUpperBound()); - String required = checkRequiredPattern(((EStructuralFeature) obj).getUpperBound(), ((EStructuralFeature) obj).getLowerBound()); - String attributeValue = eType + defaultValue + required + array; - refAttribute.put(name, attributeValue); - } - } - } - } - } - return refAttribute; - - } - - public String arrayCheck(int upperBound) { - - if (upperBound == -1){ - return ":MANY-true"; - } - - return ":MANY-false"; - } - - public List getDependencyList(EClassifier eClassifier, String className){ - List returnValue = new ArrayList<>();; - EList somelist = ((EClass) eClassifier).getEAllSuperTypes(); - if (somelist.isEmpty()){ - return returnValue; - } - for(EClass depend: somelist){ - if (depend.toString().contains(eProxyURI)){ - String one = depend.toString().split(eProxyURI)[1]; - String value = StringUtils.replaceEach(one.split("#")[1], new String[]{"//", ")"}, new String[]{"", ""}); - returnValue.add(value); - } - } - - return returnValue; - } - - public Map buildSubList(HashMap subClassAttributes, HashMap classMap, String className){ - Map missingValues = new HashMap<>(); - Map workingMap = new HashMap<>(); - boolean enumType; - - for ( Entry map : classMap.get(className).getRefAttribute().entrySet()){ - String value = map.getValue().split(":")[0]; - if (value!=null){ - classMap.get(className).getEnumType(); - enumType = classMap.get(className).getEnumType().containsKey(value); - if (!enumType){ - workingMap = classMap.get(value).getRefAttribute(); - for ( Entry subMab : workingMap.entrySet()){ - String value2 = subMab.getValue().split(":")[0]; - if (!subClassAttributes.containsValue(value2)){ - missingValues.put(subMab.getKey(), subMab.getValue()); - } - } - - } - } - } - - return missingValues; - } - - public Map> recursiveReference(HashMap classMap, String className){ - - Map> returnObject = new HashMap<>(); - HashMap returnClass = getRefclass(classMap, className); - returnObject.put(className, returnClass); - for (Entry reAttribute :returnClass.entrySet()){ - if (reAttribute.getValue().split(":")[1].contains("MANY")){ - if (classMap.get(reAttribute.getValue().split(":")[0]) != null){ - returnObject.putAll(recursiveReference(classMap, reAttribute.getValue().split(":")[0])); - } - } - - } - - return returnObject; - - } - - public String createJson(HashMap subClassAttributes, HashMap classMap, String className) { - boolean enumType; - Map> myObject = new HashMap<>(); - for ( Entry map : classMap.get(className).getRefAttribute().entrySet()){ - String value = map.getValue().split(":")[0]; - if (value!=null){ - enumType = classMap.get(className).getEnumType().containsKey(value); - if (!enumType){ - if (map.getValue().split(":")[1].contains("MANY")){ - Map> testRecursive = recursiveReference(classMap, map.getValue().split(":")[0] ); - myObject.putAll(testRecursive); - } - } - } - } - - Gson gson = new Gson(); - String json = gson.toJson(myObject); - - return json; - } - - public HashMap getRefclass(HashMap classMap, String className){ - HashMap missingValues = new HashMap<>(); - - if (classMap.get(className).getAttribute()!=null || !classMap.get(className).getAttribute().isEmpty()){ - missingValues.putAll(classMap.get(className).getAttribute()); - } - - if (classMap.get(className).getRefAttribute()!=null || !classMap.get(className).getRefAttribute().isEmpty()){ - missingValues.putAll(classMap.get(className).getRefAttribute()); - } - - return missingValues; - } - - public String createSubAttributes(ArrayList dependency, HashMap classMap, String modelName) { - - HashMap workingMap = new HashMap<>(); - MSAttributeObject tempObject = new MSAttributeObject(); - if (dependency!=null){ - if (dependency.size()==0){ - return "{}"; - } - dependency.add(modelName); - for (String element: dependency){ - tempObject = classMap.get(element); - if (tempObject!=null){ - workingMap.putAll(classMap.get(element).getSubClass()); - } - } - } - - String returnValue = createJson(workingMap, classMap, modelName); - return returnValue; - } - - public ArrayList getFullDependencyList(ArrayList dependency, HashMap classMap) { - ArrayList returnList = new ArrayList<>(); - ArrayList workingList = new ArrayList<>(); - returnList.addAll(dependency); - for (String element : dependency ){ - if (classMap.containsKey(element)){ - MSAttributeObject value = classMap.get(element); - String rawValue = StringUtils.replaceEach(value.getDependency(), new String[]{"[", "]"}, new String[]{"", ""}); - workingList = new ArrayList(Arrays.asList(rawValue.split(","))); - for(String depend : workingList){ - if (!returnList.contains(depend) && !depend.isEmpty()){ - returnList.add(depend.trim()); - } - } - } - } - - return returnList; - } -} diff --git a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/Webapps.java b/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/Webapps.java deleted file mode 100644 index 5cffb998a..000000000 --- a/ECOMP-REST/src/main/java/org/openecomp/policy/rest/util/Webapps.java +++ /dev/null @@ -1,115 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest.util; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.rest.XACMLRestProperties; - -import org.openecomp.policy.xacml.api.XACMLErrorConstants; -import com.att.research.xacml.util.XACMLProperties; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - -public class Webapps { - private static String actionHome = null; - private static String configHome = null; - private static Log logger = LogFactory.getLog(Webapps.class); - - private Webapps() { - } - - public static String getConfigHome(){ - try { - loadWebapps(); - } catch (Exception e) { - logger.error("Exception Occured while loading webapps"+e); - return null; - } - return configHome; - } - - public static String getActionHome(){ - try { - loadWebapps(); - } catch (Exception e) { - logger.error("Exception Occured while loading webapps"+e); - return null; - } - return actionHome; - } - - private static void loadWebapps() throws Exception{ - String errorMessageName = "Invalid Webapps Path Location property :"; - if(actionHome == null || configHome == null){ - Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); - //Sanity Check - if (webappsPath == null) { - logger.error(errorMessageName + XACMLRestProperties.PROP_PAP_WEBAPPS); - PolicyLogger.error(errorMessageName + XACMLRestProperties.PROP_PAP_WEBAPPS); - throw new Exception(errorMessageName + XACMLRestProperties.PROP_PAP_WEBAPPS); - } - Path webappsPathConfig; - Path webappsPathAction; - if(webappsPath.toString().contains("\\")){ - webappsPathConfig = Paths.get(webappsPath.toString()+"\\Config"); - webappsPathAction = Paths.get(webappsPath.toString()+"\\Action"); - }else{ - webappsPathConfig = Paths.get(webappsPath.toString()+"/Config"); - webappsPathAction = Paths.get(webappsPath.toString()+"/Action"); - } - - checkConfigActionHomeExists(webappsPathConfig, webappsPathAction); - - actionHome = webappsPathAction.toString(); - configHome = webappsPathConfig.toString(); - } - } - - private static void checkConfigActionHomeExists(Path webappsPathConfig, Path webappsPathAction){ - if (!webappsPathConfig.toFile().exists()){ - try { - Files.createDirectories(webappsPathConfig); - } catch (IOException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: " - + webappsPathConfig.toAbsolutePath().toString(), e); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Webapps", "Failed to create config directory"); - } - } - - if (!webappsPathAction.toFile().exists()){ - try { - Files.createDirectories(webappsPathAction); - } catch (IOException e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: " - + webappsPathAction.toAbsolutePath().toString(), e); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Webapps", "Failed to create config directory"); - } - } - } - -} diff --git a/ECOMP-REST/src/test/java/org/openecomp/policy/rest/XACMLRestTest.java b/ECOMP-REST/src/test/java/org/openecomp/policy/rest/XACMLRestTest.java deleted file mode 100644 index c49231b6a..000000000 --- a/ECOMP-REST/src/test/java/org/openecomp/policy/rest/XACMLRestTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-REST - * ================================================================================ - * 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.rest; - -/*import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import java.util.Random; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletInputStream; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import junit.framework.TestCase; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.springframework.mock.web.MockHttpServletResponse; -import org.springframework.mock.web.MockServletConfig; - -import com.att.research.xacml.util.XACMLProperties; -import com.mockrunner.mock.web.MockServletInputStream; - -public class XACMLRestTest extends TestCase{ - private static Log logger = LogFactory.getLog(XACMLRestTest.class); - - private List headers = new ArrayList(); - - private HttpServletRequest httpServletRequest; - private HttpServletResponse httpServletResponse; - private ServletOutputStream mockOutput; - private ServletInputStream mockInput; - private ServletConfig servletConfig; - - - @Before - public void setUp(){ - httpServletRequest = Mockito.mock(HttpServletRequest.class); - Mockito.when(httpServletRequest.getMethod()).thenReturn("POST"); - Mockito.when(httpServletRequest.getHeaderNames()).thenReturn(Collections.enumeration(headers)); - Mockito.when(httpServletRequest.getAttributeNames()).thenReturn(Collections.enumeration(headers)); - - mockOutput = Mockito.mock(ServletOutputStream.class); - - httpServletResponse = Mockito.mock(MockHttpServletResponse.class); - - try { - Mockito.when(httpServletResponse.getOutputStream()).thenReturn(mockOutput); - } catch (IOException e) { - fail(); - } - - servletConfig = Mockito.mock(MockServletConfig.class); - Mockito.when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers)); - //pdpServlet = new XACMLPdpServlet(); - - Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.pdp.properties"); - - System.setProperty("xacml.properties", "xacml.pdp.properties"); - System.setProperty("xacml.rest.pdp.config", "config_testing"); - System.setProperty("xacml.rest.pep.idfile", "testclient.properties"); - System.setProperty("xacml.rest.pdp.webapps", "/webapps"); - System.setProperty("xacml.rootPolicies", "test_PolicyEngine.xml"); - System.setProperty("xacml.referencedPolicies", "test_PolicyEngine.xml"); - System.setProperty("test_PolicyEngine.xml.file", "config_testing\\test_PolicyEngine.xml"); - System.setProperty("xacml.rest.pdp.register", "false"); - } - - @Test - public void testDummy(){ - logger.info("XACMLRestTest - testInit"); - try { - assertTrue(true); - } catch (Exception e) { - fail(); - - } - - } -} -*/ \ No newline at end of file diff --git a/ECOMP-SDK-APP/README.md b/ECOMP-SDK-APP/README.md deleted file mode 100644 index 4595f162c..000000000 --- a/ECOMP-SDK-APP/README.md +++ /dev/null @@ -1,68 +0,0 @@ -Ecomp SDK Web App -================= - -This is a Maven project with the ECOMP SDK web application for public release, containing files specific to requirements of the open-source version. This project uses the Maven war plugin to copy in ("overlay") the contents of the ECOMP SDK web application overlay files distribution at package time. - -Use Apache Maven to build, package and deploy this webapp to a web container like Apache Tomcat. Eclipse users must install the M2E-WTP connector, see https://www.eclipse.org/m2e-wtp/ -Release Notes - -All of the release notes in the epsdk-app-common and epsdk-app-overlay areas apply here! - -Build 1.2.8, ?? ??? 2017 - - put new entries here * - -Build 1.2.7, 10 Apr 2017 - - Drop shared context property - -Build 1.2.6, 23 Mar 2017 - - DE270905 Removed total page/current page text boxes from bottom of Profile Search page - DE272154 SDK-App: self profile page, changes on drop downs not saved (120272) - DE273128 Revise left menu to have unique IDs - DE271378 fixed Camunda Page link in fn_menu; additional links were updated: Notebook - US847688 Abstraction of support page content for AT&T vs Open Source in SQL Scripts - Add sample defs/definitions.xml file for partner applications to configure jsp pages - Downgrade angularJS from 1.5.0 to 1.4.8 - -Build 1.2.5, 16 Mar 2017 - - DE272709 Update icon names from DS1 to DS2 in database load script - Upgrade to EPSDK libraries version 1.2.5 - -Build 1.2.4, 10 Mar 2017 - - DE272042 Add missing includes so left menu appears on collaborate and notebook pages - DE272193 Fix class/icon name to restore role icon on Self Profile page - Restore spinners by changing class name from icon-spinner to icon-primary-spinner - DE272202 updated ionicon.css for open source version of report search page - Removed unused js files from samplePage.html in epsdk-app-os - Upgrade to EPSDK libraries version 1.2.4 - -Build 1.2.3, 8 Mar 2017 - - DE271038 Remove references to famous telecommunications company from system.properties - Upgrade to EPSDK libraries version 1.2.3 - -Build 1.2.2, 6 Mar 2017 - - DE270658 EPSDK-app-os header is covering part of left menu. - DE271510 Pages not loading in IE and FF properly. Drop page-resource-ds2.js; load scripts in HTML directly - Remove references to famous telecommunications company hosts from fusion.properties, portal.properties - Upgrade to EPSDK libraries version 1.2.2 - -Build 1.2.1, 2 Mar 2017 - - DE269231 Separated footer files on OS module displaying black footer with no content - US847688 Split database scripts; include full set in distributions - US847706 Refactored AdminAuthExtension to implement interface expected in OnboardingApiServiceImpl - Added class conf/HibernateMappingLocations - moved out of common to apps - Added file logback.xml to src/main/resources with appropriate logger names - Extend HibernateMappingLocations with method that returns list of package names to scan - Remove references to famous telecommunications company hosts from system.properties file - Upgrade to EPSDK libraries version 1.2.1 - -Build 1.2.0, 9 Feb 2017 - - Initial release diff --git a/ECOMP-SDK-APP/policyLogger.properties b/ECOMP-SDK-APP/policyLogger.properties deleted file mode 100644 index 0deb1b3d6..000000000 --- a/ECOMP-SDK-APP/policyLogger.properties +++ /dev/null @@ -1,44 +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========================================================= -### - -################################### Set concurrentHashMap and timer info ####################### -#Timer initial delay and the delay between in milliseconds before task is to be execute. -timer.delay.time=1000 -#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. -check.interval= 30000 -#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. -event.expired.time=86400 -#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed -#to remove all expired records from this concurrentHashMap. -concurrentHashMap.limit=5000 -#Size of the concurrentHashMap - when its size drops to this point, stop the Timer -stop.check.point=2500 -################################### Set logging format ############################################# -# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println -logger.type=EELF -#################################### Set level for EELF or SYSTEMOUT logging ################################## -# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all -debugLogger.level=INFO -# Set level for metrics file. Set OFF to disable; set ON to enable -metricsLogger.level=ON -# Set level for error file. Set OFF to disable; set ON to enable -error.level=ON -# Set level for audit file. Set OFF to disable; set ON to enable -audit.level=ON diff --git a/ECOMP-SDK-APP/pom.xml b/ECOMP-SDK-APP/pom.xml deleted file mode 100644 index 9603b6475..000000000 --- a/ECOMP-SDK-APP/pom.xml +++ /dev/null @@ -1,267 +0,0 @@ - - - - 4.0.0 - - org.openecomp.policy.engine - PolicyEngineSuite - 1.1.0-SNAPSHOT - - ECOMP-SDK-APP - war - - - UTF-8 - 1.1.0 - 4.2.0.RELEASE - 4.3.11.Final - - true - - 2.6.0 - - - - - doclint-java8-disable - - [1.8,) - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.10.4 - - -Xdoclint:none - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.2 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.19.1 - - ${skiptests} - - **/Test*.java - **/*Test.java - **/*TestCase.java - - - ${basedir}/war - - - classpath: - - - - - - org.apache.maven.plugins - maven-war-plugin - 2.1 - - true - - - true - - - ${project.version} - ${maven.build.timestamp} - - - - - org.openecomp.ecompsdkos - epsdk-app-overlay - - - org.openecomp.policy.engine - POLICY-SDK-APP - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 3.0.0 - - ${skipassembly} - - ${basedir}/distribution.xml - - - - - make-assembly - package - - single - - - - - - - - - - org.openecomp.policy.engine - POLICY-SDK-APP - ${project.version} - war - - - org.openecomp.ecompsdkos - epsdk-core - - - - - org.openecomp.policy.engine - POLICY-SDK-APP - ${project.version} - jar - classes - - - org.openecomp.ecompsdkos - epsdk-core - - - - - org.openecomp.policy.engine - PolicyEngineUtils - ${project.version} - - - com.att.aft - dme2 - - - - - - org.openecomp.ecompsdkos - epsdk-app-overlay - ${epsdk.version} - war - - - org.openecomp.ecompsdkos - epsdk-app-common - ${epsdk.version} - jar - - - - org.openecomp.ecompsdkos - epsdk-core - ${epsdk.version} - - - org.openecomp.ecompsdkos - epsdk-analytics - ${epsdk.version} - - - com.oracle - ojdbc6 - - - - - org.openecomp.ecompsdkos - epsdk-workflow - ${epsdk.version} - - - com.att.eelf - eelf-core - 0.0.1 - - - - org.slf4j - jcl-over-slf4j - 1.7.12 - - - com.mchange - c3p0 - 0.9.5.2 - - - - org.mariadb.jdbc - mariadb-java-client - 1.2.3 - - - commons-dbcp - commons-dbcp - 1.4 - - - - org.quartz-scheduler - quartz - 2.2.1 - - - - c3p0 - c3p0 - - - - - javax.servlet - javax.servlet-api - 3.1.0 - - - junit - junit - 4.12 - - - diff --git a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java b/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java deleted file mode 100644 index e0a11cbc8..000000000 --- a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/ExternalAppConfig.java +++ /dev/null @@ -1,161 +0,0 @@ -/*- - * ================================================================================ - * ECOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.portalapp.conf; - -import java.util.ArrayList; -import java.util.List; - -import org.openecomp.portalapp.login.LoginStrategyImpl; -import org.openecomp.portalapp.scheduler.RegistryAdapter; -import org.openecomp.portalsdk.core.auth.LoginStrategy; -import org.openecomp.portalsdk.core.conf.AppConfig; -import org.openecomp.portalsdk.core.conf.Configurable; -import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; -import org.openecomp.portalsdk.core.service.DataAccessService; -import org.openecomp.portalsdk.core.util.CacheManager; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.context.annotation.Profile; -import org.springframework.context.annotation.PropertySource; -import org.springframework.scheduling.annotation.EnableAsync; -import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.scheduling.quartz.SchedulerFactoryBean; -import org.springframework.web.servlet.ViewResolver; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; - -/** - * ECOMP Portal SDK sample application. ECOMP Portal SDK core AppConfig class to - * reuse interceptors, view resolvers and other features defined there. - */ -@Configuration -@EnableWebMvc -@ComponentScan(basePackages = "org.openecomp") -@PropertySource(value = { "${container.classpath:}/WEB-INF/conf/app/test.properties" }, ignoreResourceNotFound = true) -@Profile("src") -@EnableAsync -@EnableScheduling -public class ExternalAppConfig extends AppConfig implements Configurable { - - private RegistryAdapter schedulerRegistryAdapter; - - @Configuration - @Import(SystemProperties.class) - static class InnerConfiguration { - } - - /** - * @see org.openecomp.portalsdk.core.conf.AppConfig#viewResolver() - */ - public ViewResolver viewResolver() { - return super.viewResolver(); - } - - /** - * @see org.openecomp.portalsdk.core.conf.AppConfig#addResourceHandlers(ResourceHandlerRegistry) - * - * @param registry - */ - public void addResourceHandlers(ResourceHandlerRegistry registry) { - super.addResourceHandlers(registry); - } - - /** - * @see org.openecomp.portalsdk.core.conf.AppConfig#dataAccessService() - */ - public DataAccessService dataAccessService() { - // Echo the JDBC URL to assist developers when starting the app. - System.out.println("ExternalAppConfig: " + SystemProperties.DB_CONNECTIONURL + " is " - + SystemProperties.getProperty(SystemProperties.DB_CONNECTIONURL)); - return super.dataAccessService(); - } - - /** - * Creates a new list with a single entry that is the external app - * definitions.xml path. - * - * @return List of String, size 1 - */ - public List addTileDefinitions() { - List definitions = new ArrayList<>(); - definitions.add("/WEB-INF/defs/definitions.xml"); - return definitions; - } - - /** - * Adds request interceptors to the specified registry by calling - * {@link AppConfig#addInterceptors(InterceptorRegistry)}, but excludes - * certain paths from the session timeout interceptor. - */ - @Override - public void addInterceptors(InterceptorRegistry registry) { - super.setExcludeUrlPathsForSessionTimeout("/login_external", "*/login_external.htm", "login", "/login.htm", - "/api*", "/single_signon.htm", "/single_signon"); - super.addInterceptors(registry); - } - - /** - * Creates and returns a new instance of a {@link CacheManager} class. - * - * @return New instance of {@link CacheManager} - */ - @Bean - public AbstractCacheManager cacheManager() { - return new CacheManager(); - } - - /** - * Creates and returns a new instance of a {@link SchedulerFactoryBean} and - * populates it with triggers. - * - * @return New instance of {@link SchedulerFactoryBean} - * @throws Exception - */ - // @Bean // ANNOTATION COMMENTED OUT - // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION - public SchedulerFactoryBean schedulerFactoryBean() throws Exception { - SchedulerFactoryBean scheduler = new SchedulerFactoryBean(); - scheduler.setTriggers(schedulerRegistryAdapter.getTriggers()); - scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties")); - scheduler.setDataSource(dataSource()); - return scheduler; - } - - /** - * Sets the scheduler registry adapter. - * - * @param schedulerRegistryAdapter - */ - @Autowired - public void setSchedulerRegistryAdapter(final RegistryAdapter schedulerRegistryAdapter) { - this.schedulerRegistryAdapter = schedulerRegistryAdapter; - } - - @Bean - public LoginStrategy loginStrategy() { - - return new LoginStrategyImpl(); - } -} diff --git a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java b/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java deleted file mode 100644 index 6d7c72d1a..000000000 --- a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/ExternalAppInitializer.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ================================================================================ - * ECOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.portalapp.conf; - -import org.openecomp.portalsdk.core.conf.AppInitializer; - -public class ExternalAppInitializer extends AppInitializer { - - @Override - protected Class[] getRootConfigClasses() { - return super.getRootConfigClasses(); - } - - @Override - protected Class[] getServletConfigClasses() { - Class appConfigClass = ExternalAppConfig.class; - // Show something on stdout to indicate the app is starting. - System.out.println("ExternalAppInitializer: servlet configuration class is " + appConfigClass.getName()); - return new Class[] { appConfigClass }; - } - - /* - * URL request will direct to the Spring dispatcher for processing - */ - @Override - protected String[] getServletMappings() { - return super.getServletMappings(); - } - -} diff --git a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java b/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java deleted file mode 100644 index cf6ee2f07..000000000 --- a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/conf/HibernateMappingLocations.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ================================================================================ - * ECOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.portalapp.conf; - -import org.springframework.context.annotation.Profile; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.stereotype.Component; - -import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable; - -@Component -@Profile("src") -public class HibernateMappingLocations implements HibernateMappingLocatable { - - /* - * (non-Javadoc) - * - * @see org.openecomp.portalsdk.core.conf.HibernateMappingLocatable# - * getMappingLocations() - */ - @Override - public Resource[] getMappingLocations() { - return new Resource[] { new ClassPathResource("../fusion/orm/Fusion.hbm.xml"), - new ClassPathResource("../fusion/orm/Workflow.hbm.xml"), - new ClassPathResource("../fusion/orm/RNoteBookIntegration.hbm.xml") }; - } - - /* - * (non-Javadoc) - * - * @see org.openecomp.portalsdk.core.conf.HibernateMappingLocatable# - * getPackagesToScan() - */ - @Override - public String[] getPackagesToScan() { - return new String[] { "org.openecomp" }; - } - -} diff --git a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/lm/FusionLicenseManagerImpl.java b/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/lm/FusionLicenseManagerImpl.java deleted file mode 100644 index 4993a005d..000000000 --- a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/lm/FusionLicenseManagerImpl.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.openecomp.portalapp.lm; - -import java.util.Date; -import java.util.List; -import java.util.Map; - -import javax.servlet.ServletContext; - -import org.openecomp.portalsdk.core.lm.FusionLicenseManager; -import org.springframework.stereotype.Component; - -/* - * Please note that this class is not being used; its a dummy stub to have a qualifying bean for the interface. - */ - -@Component -public class FusionLicenseManagerImpl implements FusionLicenseManager { - - @Override - public void initKeyStoreParam() { - - } - - @Override - public void initCipherParam() { - - } - - @Override - public void initLicenseParam() { - - } - - @Override - public void doInitWork() { - - } - - @Override - public int installLicense() { - return 0; - } - - @Override - public synchronized int verifyLicense(ServletContext context) { - return 0; - } - - @Override - public void generateLicense(Map clientInfoMap, List ipAddressList) throws Exception { - - } - - @Override - public String nvl(String s) { - return null; - } - - @Override - public Date getExpiredDate() { - return null; - } - - @Override - public void setExpiredDate(Date expiredDate) { - - } - -} diff --git a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/lm/LicenseableClassImpl.java b/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/lm/LicenseableClassImpl.java deleted file mode 100644 index 91fe78706..000000000 --- a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/lm/LicenseableClassImpl.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ================================================================================ - * eCOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.portalapp.lm; - -import java.io.FileNotFoundException; -import java.io.InputStream; - -import org.openecomp.portalsdk.core.lm.LicenseableClass; - -/* - * Please note that this class is not being used; its a dummy stub to have a qualifying bean for the interface. - */ - -public class LicenseableClassImpl implements LicenseableClass { - - public String getApplicationName() { - return ""; - } - - public InputStream getPublicKeystoreAsInputStream() throws FileNotFoundException { - return null; - } - - public String getAlias() { - return ""; - } - - public String getKeyPasswd() { - return ""; - } - - public String getPublicKeystorePassword() { - return ""; - } - - public String getCipherParamPassword() { - return ""; - } - - @SuppressWarnings("rawtypes") - public Class getClassToLicense() { - return this.getClass(); - } -} - diff --git a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/login/LoginStrategyImpl.java b/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/login/LoginStrategyImpl.java deleted file mode 100644 index d0aca5d32..000000000 --- a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/login/LoginStrategyImpl.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.openecomp.portalapp.login; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.portalsdk.core.auth.LoginStrategy; -import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; -import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; -import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; -import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; -import org.springframework.web.servlet.ModelAndView; - -public class LoginStrategyImpl extends LoginStrategy { - - private static final Logger LOGGER = FlexLogger.getLogger(LoginStrategyImpl.class); - - @Override - public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { - //'login' for opensource is same as 'external' login. - return doExternalLogin(request, response); - } - - @Override - public String getUserId(HttpServletRequest request) throws PortalAPIException { - // Check ECOMP Portal cookie - if (!isLoginCookieExist(request)) - return null; - - String userid = null; - try { - userid = getUserIdFromCookie(request); - } catch (Exception e) { - LOGGER.error("Exception Occured"+e); - } - return userid; - } - - private static String getUserIdFromCookie(HttpServletRequest request) throws Exception { - String userId = ""; - Cookie[] cookies = request.getCookies(); - Cookie userIdcookie = null; - if (cookies != null) - for (Cookie cookie : cookies) - if (cookie.getName().equals(USER_ID)) - userIdcookie = cookie; - if(userIdcookie!=null){ - userId = CipherUtil.decrypt(userIdcookie.getValue(), - PortalApiProperties.getProperty(PortalApiConstants.Decryption_Key)); - } - return userId; - - } - - private static boolean isLoginCookieExist(HttpServletRequest request) { - Cookie ep = getCookie(request, EP_SERVICE); - return (ep != null); - } - - private static Cookie getCookie(HttpServletRequest request, String cookieName) { - Cookie[] cookies = request.getCookies(); - if (cookies != null) - for (Cookie cookie : cookies) - if (cookie.getName().equals(cookieName)) - return cookie; - - return null; - } - - -} diff --git a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/scheduler/Register.java b/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/scheduler/Register.java deleted file mode 100644 index 5793fac5a..000000000 --- a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/scheduler/Register.java +++ /dev/null @@ -1,71 +0,0 @@ -/*- - * ================================================================================ - * ECOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.portalapp.scheduler; - -import java.util.ArrayList; -import java.util.List; - -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.openecomp.portalsdk.core.scheduler.Registerable; -import org.openecomp.portalsdk.core.util.SystemProperties; -import org.quartz.Trigger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.DependsOn; -import org.springframework.stereotype.Component; - -@Component -@DependsOn({ "logRegistry", "systemProperties" }) -public class Register implements Registerable { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(Register.class); - - private List scheduleTriggers = new ArrayList<>(); - Trigger trigger[] = new Trigger[1]; - - @Autowired - private LogRegistry logRegistry; - - @Override - public Trigger[] getTriggers() { - return getScheduleTriggers().toArray(trigger); - } - - @Override - public void registerTriggers() { - // if the property value is not available; the cron will not be added - // and can be ignored. its safe to ignore the exceptions - try { - if (SystemProperties.getProperty(SystemProperties.LOG_CRON) != null) - getScheduleTriggers().add(logRegistry.getTrigger()); - } catch (IllegalStateException ies) { - logger.info(EELFLoggerDelegate.debugLogger, ("Log Cron not available") + ies); - } - - } - - public List getScheduleTriggers() { - return scheduleTriggers; - } - - public void setScheduleTriggers(List scheduleTriggers) { - this.scheduleTriggers = scheduleTriggers; - } - -} diff --git a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java b/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java deleted file mode 100644 index af2bca592..000000000 --- a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/scheduler/RegistryAdapter.java +++ /dev/null @@ -1,92 +0,0 @@ -/*- - * ================================================================================ - * ECOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.portalapp.scheduler; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import org.openecomp.portalsdk.core.scheduler.Registerable; -import org.openecomp.portalsdk.workflow.services.WorkflowScheduleService; -import org.quartz.Trigger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.scheduling.quartz.SchedulerFactoryBean; -import org.springframework.stereotype.Component; - -@Component -public class RegistryAdapter { - - @Autowired - private Registerable registry; - - @Autowired - private WorkflowScheduleService workflowScheduleService; - - private SchedulerFactoryBean schedulerBean; - - Trigger trigger[] = new Trigger[1]; - - public Trigger[] getTriggers() { - - registry.registerTriggers(); - - List allTriggers = new ArrayList<>(); - - List coreTriggers = addCoreTriggers(); - final Trigger[] extTriggerArray = registry.getTriggers(); - - allTriggers.addAll(Arrays.asList(extTriggerArray)); - allTriggers.addAll(coreTriggers); - - return allTriggers.toArray(trigger); - } - - public List addCoreTriggers() { - // On startup of the application after crash recovery, invoke workflow - // schedule trigger - List triggers = getWorkflowScheduleService().triggerWorkflowScheduling(); - return triggers; - } - - public void setSchedulerBean(SchedulerFactoryBean _schedulerBean) { - schedulerBean = _schedulerBean; - } - - public SchedulerFactoryBean getSchedulerBean() { - return schedulerBean; - } - - public Registerable getRegistry() { - return registry; - } - - public void setRegistry(Registerable registry) { - this.registry = registry; - } - - public WorkflowScheduleService getWorkflowScheduleService() { - return workflowScheduleService; - } - - public void setWorkflowScheduleService(WorkflowScheduleService workflowScheduleService) { - this.workflowScheduleService = workflowScheduleService; - } - -} diff --git a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java b/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java deleted file mode 100644 index 20de89874..000000000 --- a/ECOMP-SDK-APP/src/main/java/org/openecomp/portalapp/service/AdminAuthExtension.java +++ /dev/null @@ -1,113 +0,0 @@ -/*- - * ================================================================================ - * ECOMP Portal SDK - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property - * ================================================================================ - * 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. - * ================================================================================ - */ -package org.openecomp.portalapp.service; - -import java.util.Set; - -import org.openecomp.policy.model.Roles; -import org.openecomp.policy.rest.dao.CommonClassDao; -import org.openecomp.policy.rest.jpa.UserInfo; -import org.openecomp.portalsdk.core.domain.Role; -import org.openecomp.portalsdk.core.domain.User; -import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - - -@Service("adminAuthExtension") -@Transactional -/** - * Provides empty implementations of the methods in IAdminAuthExtension. - */ -public class AdminAuthExtension implements IAdminAuthExtension { - - EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminAuthExtension.class); - - @Autowired - CommonClassDao commonClassDao; - - - /* - * (non-Javadoc) - * @see org.openecomp.portalapp.service.IAdminAuthExtension#saveUserExtension(org.openecomp.portalsdk.core.domain.User) - */ - public void saveUserExtension(User user) { - logger.debug("saveUserExtension"); - savePolicyRole(null, user); - } - - /* - * (non-Javadoc) - * @see org.openecomp.portalapp.service.IAdminAuthExtension#editUserExtension(org.openecomp.portalsdk.core.domain.User) - */ - public void editUserExtension(User user) { - logger.debug("editUserExtension"); - } - - /* - * (non-Javadoc) - * @see org.openecomp.portalapp.service.IAdminAuthExtension#saveUserRoleExtension(java.util.Set, org.openecomp.portalsdk.core.domain.User) - */ - public void saveUserRoleExtension(Set roles, User user) { - logger.debug("saveUserRoleExtension"); - savePolicyRole(roles, user); - } - - private void savePolicyRole(Set roles, User user){ - System.out.println("User Object Recieved"); - try{ - Roles roles1 = new Roles(); - roles1.setName(user.getFullName()); - roles1.setLoginId(user.getLoginId()); - if(user.getRoles() != null){ - String query = "delete from Roles where loginid='"+user.getLoginId()+"'"; - commonClassDao.updateQuery(query); - for(Role role : user.getRoles()){ - System.out.println("User Role"+role); - if(role.getName().trim().equalsIgnoreCase("Policy Super Admin") || role.getName().trim().equalsIgnoreCase("System Administrator") || role.getName().trim().equalsIgnoreCase("Standard User") ){ - roles1.setRole("super-admin"); - }else if(role.getName().trim().equalsIgnoreCase("Policy Super Editor")){ - roles1.setRole("super-editor"); - }else if(role.getName().trim().equalsIgnoreCase("Policy Super Guest")){ - roles1.setRole("super-guest"); - }else if(role.getName().trim().equalsIgnoreCase("Policy Admin")){ - roles1.setRole("admin"); - }else if(role.getName().trim().equalsIgnoreCase("Policy Editor")){ - roles1.setRole("editor"); - }else if(role.getName().trim().equalsIgnoreCase("Policy Guest")){ - roles1.setRole("guest"); - } - commonClassDao.save(roles1); - } - } - - UserInfo userInfo = new UserInfo(); - userInfo.setUserLoginId(user.getLoginId()); - userInfo.setUserName(user.getFullName()); - commonClassDao.save(userInfo); - System.out.println("User Object Updated Successfully"); - } - catch(Exception e){ - logger.error("Exception caused while Setting role to Policy DB"+e); - } - } - -} diff --git a/ECOMP-SDK-APP/src/main/resources/logback.xml b/ECOMP-SDK-APP/src/main/resources/logback.xml deleted file mode 100644 index c944721f5..000000000 --- a/ECOMP-SDK-APP/src/main/resources/logback.xml +++ /dev/null @@ -1,370 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ${defaultLoggerPattern} - - - - - - - - - - - - ${logDirectory}/${generalLogName}.log - - - ${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.log.zip - - - 30 - 3GB - - - - ${applicationLoggerPattern} - - - - - - 256 - - true - - - - - - - - - - - - - - - - - - - ${logDirectory}/${auditLogName}.log - - - ${logDirectory}/${auditLogName}.%d{yyyy-MM-dd}.log.zip - - - 30 - 3GB - - - - ${auditLoggerPattern} - - - - 256 - - - - - ${logDirectory}/${metricsLogName}.log - - - ${logDirectory}/${metricsLogName}.%d{yyyy-MM-dd}.log.zip - - - 30 - 3GB - - - - ${metricsLoggerPattern} - - - - - - 256 - - - - - ${logDirectory}/${errorLogName}.log - - - ${logDirectory}/${errorLogName}.%d{yyyy-MM-dd}.log.zip - - - 30 - 3GB - - - - ${errorLoggerPattern} - - - - - 256 - - - - - ${debugLogDirectory}/${debugLogName}.log - - - ${logDirectory}/${debugLogName}.%d{yyyy-MM-dd}.log.zip - - - 30 - 3GB - - - - ${defaultLoggerPattern} - - - - - 256 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/ECOMP-SDK-APP/src/main/resources/portal.properties b/ECOMP-SDK-APP/src/main/resources/portal.properties deleted file mode 100644 index 0da2d5b5c..000000000 --- a/ECOMP-SDK-APP/src/main/resources/portal.properties +++ /dev/null @@ -1,69 +0,0 @@ -### -# ================================================================================ -# eCOMP Portal SDK -# ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property -# ================================================================================ -# 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. -# ================================================================================ -### -# Properties read by ECOMP Framework library, ecompFW.jar - -########################################################################## -# The following properties should NOT be changed by partner applications. -########################################################################## - -portal.api.prefix = /api -max.idle.time = 5 -user.attribute.name = user_attribute - -# CSP settings -csp_cookie_name = attESSec -csp_gate_keeper_prod_key = PROD -testing=testing - -#Use REST API instead of UEB to fetch the functional menu data -use_rest_for_functional_menu=true - -########################################################################## -# The following properties MUST be changed by partner applications. -########################################################################## - -# Name of java class that implements the OnBoardingApiService interface. -portal.api.impl.class = org.openecomp.portalapp.service.OnBoardingApiServiceImpl - -# CSP Global Log On for single sign on -ecomp_redirect_url = todo_csp_global_logon - -# URL of the ECOMP Portal REST API -ecomp_rest_url = todo_Ecomp_rest_url - -# Applications do not need to run a UEB listener in 1610. -ueb_listeners_enable = false - -# UEB Configuration -# In release 1607, all 6 entries below were required. -# In release 1610, if key ueb_listeners_enable is set to false, -# then only the ueb_app_key is required. -# UEB servers -ueb_url_list = todo_ueb_list -# ECOMP Portal listens on this UEB topic -ecomp_portal_inbox_name = ECOMP-PORTAL-INBOX-TEST-DEMETER -# Replace these 3 default values with the ones for your specific App, -# as shown on the on-boarding page on the ECOMP Portal web application. -ueb_app_key = ZOicEniw7BWDL1pM -ueb_app_secret = PJIsBErHfo2RGKzuu03CZKgV -ueb_app_mailbox_name = ECOMP-PORTAL-OUTBOX-TEST-32756 -# Consumer group name for UEB topic. -# Use the special tag '{UUID}' to generate a unique one for each sdk-app server. -ueb_app_consumer_group_name = {UUID} diff --git a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties b/ECOMP-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties deleted file mode 100644 index 6c65eaf52..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties +++ /dev/null @@ -1,72 +0,0 @@ -# Properties read by ECOMP Core library, ecompSDK-core.jar - -########################################################################## -# The following properties should NOT be changed by partner applications. -########################################################################## - -application_user_id = 30000 -post_default_role_id = 16 -clustered = true - -#Enable Fusion Mobile capabilities for the application -mobile_enable = false - -# Cache config file is needed on the classpath -cache_config_file_path = /WEB-INF/classes/cache.ccf -cache_switch = 199 -cache_load_on_startup = false - -user_name = fullName -decryption_key = AGLDdG4D04BKm2IxIWEr8o== - -########################################################################## -# The following properties MAY require changes by partner applications. -########################################################################## -#Mysql -db.driver = com.mysql.jdbc.Driver -db.connectionURL = jdbc:mysql://localhost:3306/ecomp_sdk -db.userName = policy_user -db.password = policy_user -db.hib.dialect = org.hibernate.dialect.MySQLDialect -db.min_pool_size = 5 -db.max_pool_size = 10 -hb.dialect = org.hibernate.dialect.MySQLDialect -# SQL statements are logged to stdout -hb.show_sql = true -hb.idle_connection_test_period = 3600 - -app_display_name = EP SDK App -files_path = /tmp - -#element map files -element_map_file_path = /tmp -element_map_icon_path = app/fusionapp/icons/ - -#Cron Schedules have 6 required fields and 1 optional field: -# Seconds Minutes Hours Day-of-Month Month Day-of-Week Year -log_cron = 0 0/1 * * * ?; -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_shared_context_url - -# Link shown in Help menu -contact_us_link = todo_Contact_link - -# Camunda cockpit link -camunda_cockpit_link = todo_camunda_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. -# Online Unique UUID generator - https://www.uuidgenerator.net/ -instance_uuid=8da691c9-987d-43ed-a358-00ac2f35685d - -# R Cloud feature -guard_notebook_url=todo_guard_url - -# Application base URL has the host and app context only; a proper prefix of the on-boarded URL. -# Only required for applications using WebJunction or FE/BE separation. For example: -# app_base_url = todo_App_base_url diff --git a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/left-menu.jsp b/ECOMP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/left-menu.jsp deleted file mode 100644 index cbf7f8ad5..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/left-menu.jsp +++ /dev/null @@ -1,778 +0,0 @@ -<%-- - ================================================================================ - eCOMP Portal SDK - ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property - ================================================================================ - 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. - ================================================================================ - --%> -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> -<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> -<%@ page isELIgnored="false"%> -<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties"%> -<%@ page import="org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties"%> -<%@ page import="org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants"%> -<%@ page import="org.openecomp.portalsdk.core.domain.MenuData"%> - - - - - - - - - - - -" /> -" /> - -<% - String contactUsLink = SystemProperties.getProperty(SystemProperties.CONTACT_US_LINK); - String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ECOMP_REDIRECT_URL); - String portalUrl = redirectUrl.substring(0, redirectUrl.lastIndexOf('/')) + "/process_csp"; - String getAccessLink = redirectUrl.substring(0, redirectUrl.lastIndexOf('/')) + "/get_access"; -%> - - - - - - -<%@include file="/WEB-INF/fusion/jsp/ebz/loginSnippet.html" %> - -
-
- -
-
-
- - -
-
-
-
-
  • - - ECOMP Portal -
  • -
    -
    - -
    -
    - - -
    - - -
    -
    -
    -
  • - Unable to load menus -
  • -
    - -
    -
  • -
    - - -
    -
  • -
  •  
  • -
    - -
    -
    -
    -
    -
    -
    -
    - -
    -
    - - - -     {{app_name}} - -
    -
    -
    -
    - - - - - -
    -
    -
    -
    -
    -
    -
    -
    - - \ No newline at end of file diff --git a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/fusion/orm/RNoteBookIntegration.hbm.xml b/ECOMP-SDK-APP/src/main/webapp/WEB-INF/fusion/orm/RNoteBookIntegration.hbm.xml deleted file mode 100644 index 6638b4bc7..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/fusion/orm/RNoteBookIntegration.hbm.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/index.jsp b/ECOMP-SDK-APP/src/main/webapp/WEB-INF/index.jsp deleted file mode 100644 index f6030c979..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/index.jsp +++ /dev/null @@ -1,24 +0,0 @@ -<%-- - ================================================================================ - eCOMP Portal SDK - ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property - ================================================================================ - 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. - ================================================================================ - --%> -<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> - -<%-- Redirected because we can't set the welcome page to a virtual URL. --%> -<%-- Forward to the intended start page to reduce frustration for new users. --%> - diff --git a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/jsp/login.jsp b/ECOMP-SDK-APP/src/main/webapp/WEB-INF/jsp/login.jsp deleted file mode 100644 index 09320356c..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/jsp/login.jsp +++ /dev/null @@ -1,113 +0,0 @@ -<%-- - ================================================================================ - ECOMP Portal SDK - ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property - ================================================================================ - 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. - ================================================================================ ---%> -<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties"%> - -<% - // Name is defined by app; do not throw if missing - final String appDisplayName = SystemProperties.containsProperty(SystemProperties.APP_DISPLAY_NAME) - ? SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) - : SystemProperties.APP_DISPLAY_NAME; -%> - - - - - - - Login - - - - -
    -
    -
    ${model.error}
    -
    -
    -
    -
    -
    -
    - - - diff --git a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/jsp/login_external.jsp b/ECOMP-SDK-APP/src/main/webapp/WEB-INF/jsp/login_external.jsp deleted file mode 100644 index 9d099bf0e..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/jsp/login_external.jsp +++ /dev/null @@ -1,117 +0,0 @@ -<%-- - ================================================================================ - ECOMP Portal SDK - ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property - ================================================================================ - 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. - ================================================================================ ---%> -<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties"%> - -<% - // Name is defined by app; do not throw if missing - final String appDisplayName = SystemProperties.containsProperty(SystemProperties.APP_DISPLAY_NAME) - ? SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) - : SystemProperties.APP_DISPLAY_NAME; -%> - - - - - - - - - - - -
    -
    -
    ${model.error}
    -
    -
    -
    -
    -
    -
    - - - diff --git a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/web.xml b/ECOMP-SDK-APP/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 0290f1fc8..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - ecomp-sdk-app-os - - - - - - 7 - COOKIE - - - \ No newline at end of file diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-samplePages/samplePage.html b/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-samplePages/samplePage.html deleted file mode 100644 index 06d62f676..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-samplePages/samplePage.html +++ /dev/null @@ -1,62 +0,0 @@ - - - - - - - Sample Page - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -
    - - - diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/footer.html b/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/footer.html deleted file mode 100644 index f4d8d7edb..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/footer.html +++ /dev/null @@ -1,13 +0,0 @@ -
    -
    - -
    -
    \ No newline at end of file diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/utils/page-resource-ds2.js b/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/utils/page-resource-ds2.js deleted file mode 100644 index d0af6cbc3..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/utils/page-resource-ds2.js +++ /dev/null @@ -1,97 +0,0 @@ -function loadjscssfile(filename, filetype){ - if (filetype=="js"){ //if filename is a external JavaScript file - var done = false; - var script = document.createElement('script'); - script.src = filename; - script.async = false; - document.head.appendChild(script); - }else if (filetype=="css"){ //if filename is an external CSS file - var fileref=document.createElement("link") - fileref.setAttribute("rel", "stylesheet") - fileref.setAttribute("type", "text/css") - fileref.setAttribute("async", false) - fileref.setAttribute("href", filename) - document.head.appendChild(fileref); - } -} - -function loadResource(){ - /*********************AngularJs***************************/ - loadjscssfile("./app/fusion/external/angular-1.5/angular.min.js", "js"); - loadjscssfile("./app/fusion/external/angular-1.5/angular-messages.js", "js"); - loadjscssfile("./app/fusion/external/angular-1.5/angular-touch.js", "js"); - loadjscssfile("./app/fusion/external/angular-1.5/angular-sanitize.min.js", "js"); - loadjscssfile("./app/fusion/external/angular-1.5/angular-route.min.js", "js"); - loadjscssfile("./app/fusion/external/angular-1.5/angular-cookies.min.js", "js"); - - loadjscssfile("./app/fusion/external/ds2/js/b2b-angular/b2b-library.min.js", "js"); -/* loadjscssfile("./app/fusion/external/ds2/js/digital-ng-library/digital.ng.library.min.js", "js"); -*/ - loadjscssfile("./app/fusion/external/jquery/dist/jquery.min.js", "js"); - - /*********************Angular Gridster***************************/ - loadjscssfile("./app/fusion/external/angular-gridster/dist/angular-gridster.min.css", "css"); - loadjscssfile("./app/fusion/external/angular-bootstrap/ui-bootstrap-csp.css", "css"); - loadjscssfile("./app/fusion/external/javascript-detect-element-resize/jquery.resize.js", "js"); - loadjscssfile("./app/fusion/external/angular-bootstrap/ui-bootstrap-tpls.min.js", "js"); - loadjscssfile("./app/fusion/external/angular-gridster/dist/angular-gridster.min.js", "js"); - - /*********************Angular UI grid***************************/ - loadjscssfile("./app/fusion/external/angular-ui-grid/ui-grid.js", "js"); - loadjscssfile("./app/fusion/external/angular-ui-grid/ui-grid.css", "css"); - - loadjscssfile("./app/fusion/external/ds2/js/appDS2.js", "js"); - - loadjscssfile("./app/fusion/scripts/DS2-services/headerServiceDS2.js", "js"); - loadjscssfile("./app/fusion/scripts/DS2-services/leftMenuServiceDS2.js", "js"); - loadjscssfile("./app/fusion/scripts/DS2-services/manifestService.js", "js"); - loadjscssfile("./app/fusion/scripts/DS2-directives/footer.js", "js"); - loadjscssfile("./app/fusion/scripts/DS2-directives/ds2Header.js", "js"); - loadjscssfile("./app/fusion/scripts/DS2-directives/ds2LeftMenu.js", "js"); - loadjscssfile("./app/fusion/external/ds2/js/digital-ng-library/digital-design-library.js", "js"); - - /*******DS2 styles*******/ - loadjscssfile("./app/fusion/external/ds2/css/b2b-angular/b2b-angular.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/extras/ds2-accordion.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/extras/ds2-bootstrap-datepicker.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/extras/ds2-cc-input-field.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/extras/ds2-tooltip.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/extras/x-tabs-pills.css", "css"); - - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-accordion.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-bootstrap-datepicker.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-c2c.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-cc-input-field.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-filmstrip.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-filters.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-legacynav-fix.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-marquee.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-pagination.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-popover.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-progressbar.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-tooltip.css", "css"); - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/global.css", "css"); - - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/digital-design-library.css", "css"); - /*******DS2 ICONS*******/ - - loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ionicons.css", "css"); - loadjscssfile("./app/fusion/styles/ecomp.css", "css"); - loadjscssfile("./app/fusion/external/angular-gridster/dist/angular-gridster.min.css", "css"); - -} - -window.onload = loadResource(); -/*window.onload = function(){ - var appLoadingInterval = setInterval(function(){ loadApp() }, 10000); - var count=0; - function loadApp(){ - count++ - if(typeof angular !== 'undefined') { - angular.bootstrap(document, ['abs']); - clearInterval(appLoadingInterval); - }else if(count>10){ - clearInterval(appLoadingInterval); - } - } -}*/ \ No newline at end of file diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/view-models/footer.html b/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/view-models/footer.html deleted file mode 100644 index 7cbff474b..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/view-models/footer.html +++ /dev/null @@ -1,17 +0,0 @@ - - - -
    -
    -
    -
    -
    - -
    -
    -
    -
    -
    - \ No newline at end of file diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/css/att_angular_gridster/ui-gridster.css b/ECOMP-SDK-APP/src/main/webapp/static/fusion/css/att_angular_gridster/ui-gridster.css deleted file mode 100644 index 4bf19bfaf..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/static/fusion/css/att_angular_gridster/ui-gridster.css +++ /dev/null @@ -1,116 +0,0 @@ -/* ui-gridster.css */ -.gridster-container { - background-color: #EFEFEF; - color: #fff; - border: 1px dashed; - overflow-y: auto; - overflow-x: hidden; } - -/* app css for attGridtser */ -.gridster-item-container { - background-color: #FFFFFF; - position: relative; - margin-left: auto; - margin-right: auto; - min-height: 79px; - height: 100%; } - .gridster-item-container .gridster-item-header { - /* gridster-item Header */ - position: relative; - height: 50px !important; - border: 1px solid #d3d3d3; - border-bottom: 0; - background-color: #E5E5E5; - white-space: nowrap; - text-overflow: ellipsis; - z-index: 1; - -webkit-border-radius: 2px 2px 0 0; - -moz-border-radius: 2px 2px 0 0; - -ms-border-radius: 2px 2px 0 0; - -o-border-radius: 2px 2px 0 0; - border-radius: 2px 2px 0 0; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - overflow: hidden; - /* IE6-8 */ } - .gridster-item-container .gridster-item-header .gridster-item-handle { - cursor: move; - margin: 12px; - position: absolute; - top: 0; - left: 0; - border: 0; - vertical-align: middle; - -ms-interpolation-mode: bicubic; - display: block; } - .gridster-item-container .gridster-item-header .gridster-item-header-content { - line-height: 44px; - margin-left: 26px; - font-family: "Omnes-ECOMP-W02", Arial; - font-size: 18px; - color: #444444; - float: left; } - .gridster-item-container .gridster-item-header .gridster-item-sub-header-content { - position: absolute; - top: 29.5px; - left: 26px; - font-family: "Omnes-ECOMP-W02", Arial; - font-size: 12px; - color: #444444; } - .gridster-item-container .gridster-item-header .gridster-item-header-buttons-container { - position: absolute; - right: 10px; - top: 10px; - overflow: hidden; - text-align: right; - height: 30px; - color: #444444; } - .gridster-item-container .gridster-item-body { - /* gridster-item Body */ - position: absolute; - width: 100%; - top: 50px; - left: 0; - right: 0; - bottom: 29px; - border: 1px solid #d3d3d3; - box-sizing: border-box; - overflow: auto; - color: #444444; - /* text-align: center; */ } - .gridster-item-container .gridster-item-footer { - /* gridster-item Footer */ - position: absolute; - bottom: 0; - width: 100%; - height: 29px !important; - text-align: left; - cursor: pointer; - border: 1px solid #d3d3d3; - border-top: 0; - background-color: #F2F2F2; - -webkit-border-radius: 0 0 2px 2px; - -moz-border-radius: 0 0 2px 2px; - -ms-border-radius: 0 0 2px 2px; - -o-border-radius: 0 0 2px 2px; - border-radius: 0 0 2px 2px; - -webkit-box-sizing: border-box; - -moz-box-sizing: border-box; - box-sizing: border-box; - text-decoration: none; - /* IE6-8 */ } - .gridster-item-container .gridster-item-footer:hover { - background-color: #E5E5E5; - color: #565656; - text-decoration: underline; } - .gridster-item-container .gridster-item-footer .gridster-item-footer-content { - line-height: 30px; - font-family: "Omnes-ECOMP-W02", Arial; - font-size: 12px; - color: #565656; - margin: 20px; - text-decoration: none; } - .gridster-item-container .gridster-item-footer .gridster-item-footer-content:hover { - color: #199ddf; - text-decoration: underline; } diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/worddata.csv b/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/worddata.csv deleted file mode 100644 index 762cb4237..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/worddata.csv +++ /dev/null @@ -1 +0,0 @@ -text,frequency service,98 portal,70 management,70 virtual,56 design,56 VNF,56 studio,42 operations,42 inventory,42 POLO,42 D2.0,42 ASDC,42 router,28 restart,28 process,28 platform,28 manage,28 loop,28 licensing,28 license,28 integrated,28 flow-through,28 enable,28 data,28 controller,28 control,28 configure,28 component,28 common,28 asset,28 application,28 ECOMP,28 workflow,14 waterfall,14 visual,14 view,14 vCTS,14 utilization,14 user,14 usage,14 troubleshoot,14 transformation,14 track,14 topolgies,14 topics,14 time,14 tickets,14 thresholds,14 templates,14 structures,14 standards-based,14 software,14 reuse,14 repository,14 reports,14 release,14 recipes,14 real-time,14 provisioning,14 properties,14 project-based,14 processes,14 physical,14 oversight,14 openl-loop,14 network,14 monitor,14 modeling,14 model-driven,14 model,14 message,14 maximize,14 manually,14 machine,14 layer,14 interact,14 instances,14 initiate,14 increase,14 imported,14 impacts,14 host,14 function,14 feeds,14 features,14 faults,14 extended,14 engines,14 engine,14 dynamic,14 document-driven,14 determine,14 dashboard,14 current,14 creation,14 created,14 create,14 configuration,14 composer,14 components,14 collective,14 certification,14 bus,14 basis,14 available,14 automation,14 automated,14 associated,14 assignment,14 appropriate,14 against,14 aervice,14 adminstrators,14 activation,14 action,14 VMs,14 VM,14 VLAN,14 SDN,14 SDK,14 SBG,14 SAM,14 RUBY,14 Policy,14 PODS,14 Ops,14 GFP,14 F5FW,14 DMaaP,14 DCAE,14 DBC,14 CPADS,14 AT&T,14 APP-C,14 AOTS-TM,14 ALTS,14 A&AI,14 diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/wordcloud.html b/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/wordcloud.html deleted file mode 100644 index 6cf000795..000000000 --- a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/wordcloud.html +++ /dev/null @@ -1,36 +0,0 @@ - - - Word Cloud Example - - - - - - - - - -
    - - -
    -
    - -
    - - - -
    - - \ No newline at end of file diff --git a/ECOMP-SDK-APP/xacml.admin.properties b/ECOMP-SDK-APP/xacml.admin.properties deleted file mode 100644 index e6774a6cd..000000000 --- a/ECOMP-SDK-APP/xacml.admin.properties +++ /dev/null @@ -1,203 +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========================================================= -### - -# -# This file is set to the defaults one can use to run the XACML-PAP-ADMIN for testing and development. -# -# It is not recommended to modify this file directly, but rather copy it to another location and make any modifications -# necessary to run the application in a development or a production environment. You can set the Java VM System -# property to change where the application can find the file. For example: -# -#-Dxacml.properties=/opt/app/xacml/etc/xacml.admin.properties -# -# -# Standard API Factories -# -xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory -xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory -xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory -xacml.pipFinderFactory=com.att.research.xacml.std.pip.StdPIPFinderFactory -# -# AT&T PDP Implementation Factories -# -xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory -xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory -xacml.att.functionDefinitionFactory=org.openecomp.policy.xacml.custom.EcompFunctionDefinitionFactory -xacml.att.policyFinderFactory=com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory - -# -# This is an extremely simple policy to demonstrate authorization -# within the Admin Console. -# -xacml.rootPolicies=admin -# -# PAP Servlet properties -# -xacml.PAP.papEngineFactory=org.openecomp.policy.xacml.std.pap.StdEngineFactory - -# -# Admin Console properties -# -xacml.AC.papEngineFactory=org.openecomp.policy.xacml.admin.util.RESTfulPAPFactory - -# Set your domain here: -xacml.rest.admin.domain=com -# -# -# Property to declare the max time frame for logs. -# -xacml.log.timeframe=30 -# -# -# -xacml.rest.admin.closedLoopJSON =JSONConfig.json -xacml.rest.admin.microServiceModel=model.properties -xacm.restful.interface.file=RESTful.interface.properties -# -#If the Audit is set false, then Audit function will not work at the Server Run time. -#This will Syncronize the data between Roles and Userinfo Table -xacml.audit.userInfo = true -# -#The Test Environment User Login LoginIU Should provide below on seperating with Comma -# -xacml.testEnvironment.loginId = - -#Log DB properties -xacml.log.db.driver=org.mariadb.jdbc.Driver -xacml.log.db.url=jdbc:mariadb://localhost:3306/log?failOverReadOnly=false&autoReconnect=true -xacml.log.db.user=policy_user -xacml.log.db.password=policy_user - -xacml.att.log.timeframe=150 - -javax.persistence.jdbc.driver=com.mysql.jdbc.Driver -javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/ecomp_sdk -javax.persistence.jdbc.user=policy_user -javax.persistence.jdbc.password=policy_user - -# Dashboard refresh rate in miliseconds -xacml.refresh.rate=40000 -xacml.user.column.count=3 -xacml.sqlcontainer.page.length=75 -xacm.xcor.required.pattern=1,1 -xacm.cache.live.time=2 -xacml.max.priority.count=10 - -# -# These can be set so the Admin Console knows who is logged on. Ideally, you can run the console in a J2EE -# container and setup authentication as you please. Setting HttpSession attribute values will override these -# values set in the properties files. -# -# ((HttpServletRequest) request).getSession().setAttribute("xacml.rest.admin.user.name", "Homer"); -# -# The default policy: Policy-Admin.xml is extremely simple. -# -# You can test authorization within the Admin Console by changing the user id. -# There are 3 supported user ids: -# guest - Read only access -# editor - Read/Write access -# admin - Read/Write/Admin access -# -# An empty or null value for xacml.rest.admin.user.id results in no access to the application at all. -# -# This is for development/demonstration purposes only. A production environment should provide authentication which is -# outside the scope of this application. This application can be used to develop a XACML policy for user authorization -# within this application. -# -#xacml.rest.admin.user.name=Guest -#xacml.rest.admin.user.id=guest -#xacml.rest.admin.user.name=Editor -#xacml.rest.admin.user.id=editor -xacml.rest.admin.user.name=Administrator -xacml.rest.admin.user.id=super-admin -xacml.rest.admin.user.email= - -# -# URL location for the PAP servlet. -# -xacml.rest.pap.url=http://localhost:8070/pap/ - -# id PAP -xacml.rest.pap.userid=testpap -# pass PAP -xacml.rest.pap.password=alpha123 - -# new Property Please mention your PAP-REST webapps Location here. - -xacml.rest.config.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ - -# pdps file - Needs to have the location of the PDPs File of the PAP-REST -xacml.rest.pdp.idfile=test.properties - -#Template Versions -xacml.rest.closedLoopFault=OpenSource.version.1 -xacml.rest.closedLoopPM=OpenSource.version.1 -xacml.rest.microServices=OpenSource.version.1 -xacml.rest.gocPolicy=OpenSource.version.1 -xacml.rest.firewallPolicy=OpenSource.version.1 - -#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java*** - -#The name of the Admin. Must be unique across the system -xacml.rest.admin.resource.name=site_1.admin_1 - -#The site name for the Admin -site_name=site_1 - -#Has to be one of pdp_xacml, pdp_drools, pap, pap_admin, logparser, brms_gateway, astra_gateway, elk_server -node_type=pap_admin - -# The (optional) period of time in seconds between executions of the integrity audit. -# Value < 0 : Audit does not run (default value if property is not present = -1) -# Value = 0 : Audit runs continuously -# Value > 0 : The period of time in seconds between execution of the audit on a particular node -integrity_audit_period_seconds=-1 - -#Automatic Policy Distribution -xacml.att.automatic.push = false - - -#Dashboard Tab Limit -xacml.ecomp.dashboard.logTableLimit = 5000 -xacml.ecomp.dashboard.systemAlertTableLimit = 2000 - - -#Diff of policies for Firewall feature -FW_GETURL=https://todo_enter_the_firewallurl -FW_AUTHOURL=https://todo_enter_the_firewallAuthurl -FW_PROXY=todo_enter_the_proxy -FW_PORT=8080 - -#SMTP Server Details for Java Mail -ecomp.smtp.host = smtp_host -ecomp.smtp.port = smtp_port -ecomp.smtp.userName = smtp_username -ecomp.smtp.password = smtp_password -ecomp.smtp.emailExtension=smtp_emailExtension -ecomp.application.name = smtp_AppName - -#Dialect for Database -ecomp.dialect = org.hibernate.dialect.MySQLDialect - -policyAdapter.impl.className = org.openecomp.policy.admin.PolicyAdapter - -#Micro Service Model Properties -xacml.policy.msEcompName=http://org.openecomp -xacml.policy.msPolicyName=http://org.openecomp/policy \ No newline at end of file diff --git a/ECOMP-XACML/config_testing/test_PolicyEngine.xml b/ECOMP-XACML/config_testing/test_PolicyEngine.xml deleted file mode 100644 index e111dfbf6..000000000 --- a/ECOMP-XACML/config_testing/test_PolicyEngine.xml +++ /dev/null @@ -1,595 +0,0 @@ - - - - - Test Policies for the ProtoType PolicyEngineAPI - - - - Check if the CPU Utilization or Memory reach the threshold values. - - CPU - - - - 95 - - - Memory - - - - 95 - - - - - - Spinoff if the VM if CPU or memory value reaches the threshold - - CPU - - - - 90 - - - Memory - - - - 90 - - - - - Json Test - - - - - JSON - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_json.json - - - - - - Json + Config test - - - - - JSON - - - - JSONconfig - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_json.json - - - - - - XML test - - - - - XML - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_xml.xml - - - - - - XML + Config test - - - - - XML - - - - XMLConfig - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_xml.xml - - - - - - Properties Test - - - - - Properties - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_prop.properties - - - - - - Properties + Config Test - - - - - Properties - - - - PropConfig - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_prop.properties - - - - - - Other Test - - - - - Other - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_other.txt - - - - - - Other + Config Test - - - - - Other - - - - OtherConfig - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - http://localhost:5443/config/test_other.txt - - - - - - JSON + Attributes - - - - - JSON - - - - JSONconfig - - - - TestSubject - - - - ACCESS - - - - TestJSON - - - - Config - - - - Test - - - - - - - - - Configuration - - - http://localhost:5443/config/test_json.json - - - - - - XML + Attributes - - - - - XML - - - - XMLConfig - - - - TestSubject - - - - ACCESS - - - - TestJSON - - - - Config - - - - Test - - - - - - - - - Configuration - - - http://localhost:5443/config/test_xml.xml - - - - - - Prop + Attributes - - - - - Properties - - - - PropConfig - - - - TestSubject - - - - ACCESS - - - - TestJSON - - - - Config - - - - Test - - - - - - - - - Configuration - - - http://localhost:5443/config/test_prop.properties - - - - - - Other + Attributes - - - - - Other - - - - Otherconfig - - - - TestSubject - - - - ACCESS - - - - TestJSON - - - - Config - - - - Test - - - - - - - - - Configuration - - - http://localhost:5443/config/test_other.txt - - - - - - - Permit to RESET VM if the values reach the threshold settings. - - - - - Restart - - - - - - - - Restart VM if this condition is met - - true - - - - - - Restart - - - - - - - - - Permit to SpinOff VM if the values reach the threshold settings. - - - - - SpinOff - - - - - - - - SpinOff VM if this condition is met - - true - - - - - - SpinOff - - - PDPAction - - - REST - - - - - - GET - - - http://localhost:8635/RESTjson/PDP/VM/$com.att.labs.ecomp.obligation.spinoff/$com.att.labs.ecomp.obligation.server - - - - - - Deny all the other requests. - - - diff --git a/ECOMP-XACML/config_testing/xacml.pip.properties b/ECOMP-XACML/config_testing/xacml.pip.properties deleted file mode 100644 index 16a66ed56..000000000 --- a/ECOMP-XACML/config_testing/xacml.pip.properties +++ /dev/null @@ -1,19 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-XACML -# ================================================================================ -# 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========================================================= -### diff --git a/ECOMP-XACML/config_testing/xacml.policy.properties b/ECOMP-XACML/config_testing/xacml.policy.properties deleted file mode 100644 index 17d6b455e..000000000 --- a/ECOMP-XACML/config_testing/xacml.policy.properties +++ /dev/null @@ -1,23 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-XACML -# ================================================================================ -# 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========================================================= -### - -xacml.referencedPolicies=test_PolicyEngine.xml -xacml.rootPolicies=test_PolicyEngine.xml -test_PolicyEngine.xml.file=config_testing\\test_PolicyEngine.xml diff --git a/ECOMP-XACML/policyLogger.properties b/ECOMP-XACML/policyLogger.properties deleted file mode 100644 index 7fa1b2099..000000000 --- a/ECOMP-XACML/policyLogger.properties +++ /dev/null @@ -1,44 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-XACML -# ================================================================================ -# 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========================================================= -### - -################################### Set concurrentHashMap and timer info ####################### -#Timer initial delay and the delay between in milliseconds before task is to be execute. -timer.delay.time=1000 -#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. -check.interval= 30000 -#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. -event.expired.time=86400 -#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed -#to remove all expired records from this concurrentHashMap. -concurrentHashMap.limit=5000 -#Size of the concurrentHashMap - when its size drops to this point, stop the Timer -stop.check.point=2500 -################################### Set logging format ############################################# -# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println -logger.type=EELF -#################################### Set level for EELF or SYSTEMOUT logging ################################## -# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all -debugLogger.level=INFO -# Set level for metrics file. Set OFF to disable; set ON to enable -metricsLogger.level=ON -# Set level for error file. Set OFF to disable; set ON to enable -error.level=ON -# Set level for audit file. Set OFF to disable; set ON to enable -audit.level=ON diff --git a/ECOMP-XACML/pom.xml b/ECOMP-XACML/pom.xml deleted file mode 100644 index 30720e9fc..000000000 --- a/ECOMP-XACML/pom.xml +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - - 4.0.0 - - org.openecomp.policy.engine - PolicyEngineSuite - 1.1.0-SNAPSHOT - - ECOMP-XACML - jar - - - org.openecomp.policy.engine - ${project.version} - PolicyEngineUtils - - - commons-cli - commons-cli - 1.2 - - - commons-io - commons-io - 2.4 - - - org.apache.httpcomponents - httpcore - 4.4.4 - - - junit - junit - 4.11 - test - - - org.mockito - mockito-core - 2.7.22 - - - org.springframework - spring-mock - 2.0.8 - - - commons-logging - commons-logging - - - - - com.mockrunner - mockrunner - 0.3.1 - - - com.att.research.xacml - xacml - 1.0.0 - - - diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/XACMLErrorConstants.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/XACMLErrorConstants.java deleted file mode 100644 index 5a2eac109..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/XACMLErrorConstants.java +++ /dev/null @@ -1,56 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.api; - -/** - * List of Error Classifications - * PE100 - Permissions - * PE200 - System Error (such as availability, timeout, configuration, etc...) - * PE300 - Data Issue( such as request for REST/JSON ) - * PE400 - Schema validation - * PE500 - Process Flow issues - * PE900 - Default/Unknown Errors - * - * - */ -public class XACMLErrorConstants { - //Captures all the errors related to Authentication, Authorizations and Permissions in the PolicyEngine Process - public static final String ERROR_PERMISSIONS = "PE100 - Permissions Error: "; - - //Captures all the errors related to availability, timeout configuration variables, etc... in the PolicyEngine - public static final String ERROR_SYSTEM_ERROR = "PE200 - System Error: "; - - /* - * Captures all the errors related to configuration values from properties files and data from the interfacing System - * like REST/JSON values - */ - public static final String ERROR_DATA_ISSUE = "PE300 - Data Issue: "; - - //Captures all the errors related to the XML schemas and/or REST/JSON structures - public static final String ERROR_SCHEMA_INVALID = "PE400 - Schema validation Error: "; - - //Captures all the errors related to the Process, when data from one Process to another Process does not flow - public static final String ERROR_PROCESS_FLOW = "PE500 - Process Flow Issue: "; - - //Captures all the errors that not related to the list of above error codes - public static final String ERROR_UNKNOWN = "PE900 - Unknown Error: "; - - -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/ECOMPPapEngineFactory.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/ECOMPPapEngineFactory.java deleted file mode 100644 index d34d03348..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/ECOMPPapEngineFactory.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.openecomp.policy.xacml.api.pap; - -import java.util.Properties; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.util.FactoryException; -import com.att.research.xacml.util.FactoryFinder; - -public abstract class ECOMPPapEngineFactory{ - - /** - * Creates a new PAPEngineFactory instance using the given class name and the default thread class loader. - * - * @param factoryClassName the String name of the factory class to instantiate - * @return an instance of an object that extends ECOMPPapEngineFactory to use in creating PAPPolicyEngine objects. - */ - public static ECOMPPapEngineFactory newInstance(String factoryClassName) throws FactoryException { - return FactoryFinder.newInstance(factoryClassName, ECOMPPapEngineFactory.class, null, true); - } - - /** - * Creates a new PAPPolicyEngine based on the configured ECOMPPapEngineFactory. - * - * @return a new PAPPolicyEngine - * @throws PAPException - */ - public abstract PAPPolicyEngine newEngine() throws FactoryException, PAPException; - - /** - * Creates a new PAPPolicyEngine based on the configured ECOMPPapEngineFactory. - * - * @return a new PAPPolicyEngine - * @throws PAPException - */ - public abstract PAPPolicyEngine newEngine(Properties properties) throws FactoryException, PAPException; - - -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/EcompPAPPolicy.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/EcompPAPPolicy.java deleted file mode 100644 index 79ee08e2e..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/EcompPAPPolicy.java +++ /dev/null @@ -1,89 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.api.pap; - -import java.net.URI; -import java.util.List; -import java.util.Map; - -import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; - -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonTypeInfo; -import com.fasterxml.jackson.annotation.JsonSubTypes.Type; - -/* - * The following allows us to use Jackson to convert sub-types of this type into JSON and back to objects. - */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - include = JsonTypeInfo.As.PROPERTY, - property = "PAPPolicyType") -@JsonSubTypes({ - @Type(value = StdPAPPolicy.class, name = "StdPAPPolicy") }) -public interface EcompPAPPolicy { - - public String getPolicyName(); - public String getOldPolicyFileName(); - public String getPolicyDescription(); - public String getEcompName(); - public String getConfigName(); - public Map getDynamicFieldConfigAttributes(); - public Map getDynamicSettingsMap(); - public List getDynamicRuleAlgorithmLabels(); - public List getDynamicRuleAlgorithmCombo(); - public List getDynamicRuleAlgorithmField1(); - public List getDynamicRuleAlgorithmField2(); - public List getDynamicVariableList(); - public List getDataTypeList(); - public String getConfigBodyData(); - public String getPolicyID(); - public String getRuleID(); - public String getConfigType(); - public Boolean isEditPolicy(); - public Boolean isDraft(); - public String getVersion(); - public String getDomainDir(); - public String getConfigPolicyType(); - public String getJsonBody(); - public Integer getHighestVersion(); - public URI getLocation(); - public String getActionPerformer(); - public String getActionAttribute(); - public String getActionBody(); - public Map getDropDownMap(); - public String getActionDictHeader(); - public String getActionDictType(); - public String getActionDictUrl(); - public String getActionDictMethod(); - public String getServiceType(); - public String getUuid(); - public String getMsLocation(); - public String getPriority(); - public String getDeleteCondition(); - public String getDictionaryType(); - public String getDictionary(); - public String getDictionaryFields(); - - public String getRiskLevel(); - public String getGuard(); - public String getRiskType(); - public String getTTLDate(); -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/EcompPDP.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/EcompPDP.java deleted file mode 100644 index ecb21aa09..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/EcompPDP.java +++ /dev/null @@ -1,44 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.api.pap; - -import org.openecomp.policy.xacml.std.pap.StdPDP; - -import com.att.research.xacml.api.pap.PDP; -import com.fasterxml.jackson.annotation.JsonSubTypes; -import com.fasterxml.jackson.annotation.JsonSubTypes.Type; -import com.fasterxml.jackson.annotation.JsonTypeInfo; - -/* - * The following allows us to use Jackson to convert sub-types of this type into JSON and back to objects. - */ -@JsonTypeInfo( - use = JsonTypeInfo.Id.NAME, - include = JsonTypeInfo.As.PROPERTY, - property = "PDPType") -@JsonSubTypes({ - @Type(value = StdPDP.class, name = "StdPDP") }) -public interface EcompPDP extends PDP { - - public Integer getJmxPort(); - - public void setJmxPort(Integer jmxport); - -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/EcompPDPGroup.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/EcompPDPGroup.java deleted file mode 100644 index 4aa7cbf64..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/EcompPDPGroup.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.openecomp.policy.xacml.api.pap; - -import java.util.Set; - -import com.att.research.xacml.api.pap.PDPGroup; -import com.att.research.xacml.api.pap.PDPPolicy; - -public interface EcompPDPGroup extends PDPGroup { - - public Set getEcompPdps(); - - public Set getSelectedPolicies(); - - public String getOperation(); -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/PAPPolicyEngine.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/PAPPolicyEngine.java deleted file mode 100644 index 0c5c334da..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/api/pap/PAPPolicyEngine.java +++ /dev/null @@ -1,66 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.api.pap; - -import java.io.InputStream; -import java.util.Set; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.att.research.xacml.api.pap.PDPStatus; - -public interface PAPPolicyEngine{ - - public EcompPDPGroup getDefaultGroup() throws PAPException; - - public void SetDefaultGroup(EcompPDPGroup group) throws PAPException; - - public void newPDP(String id, EcompPDPGroup group, String name, String description, int jmxport) throws PAPException, NullPointerException; - - public void newGroup(String name, String description) throws PAPException, NullPointerException; - - public EcompPDPGroup getGroup(String id) throws PAPException; - - public Set getEcompPDPGroups() throws PAPException; - - public EcompPDPGroup getPDPGroup(EcompPDP pdp) throws PAPException; - - public PDPStatus getStatus(EcompPDP pdp) throws PAPException; - - public void movePDP(EcompPDP pdp, EcompPDPGroup newGroup) throws PAPException; - - public void updatePDP(EcompPDP pdp) throws PAPException; - - public void removePDP(EcompPDP pdp) throws PAPException; - - public EcompPDP getPDP(String pdpId) throws PAPException; - - public void updateGroup(EcompPDPGroup group) throws PAPException; - - public void removeGroup(EcompPDPGroup group, EcompPDPGroup newGroup) throws PAPException, NullPointerException; - -public void publishPolicy(String id, String name, boolean isRoot, InputStream policy, EcompPDPGroup group) throws PAPException; - - // copy the given policy file into the group's directory, but do not include the policy in the group's policy set - public void copyPolicy(PDPPolicy policy, EcompPDPGroup group) throws PAPException; - - public void removePolicy(PDPPolicy policy, EcompPDPGroup group) throws PAPException; - -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdEngine.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdEngine.java deleted file mode 100644 index 83ff56ebf..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdEngine.java +++ /dev/null @@ -1,1034 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.std.pap; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.TreeSet; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -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.PDPGroup; -import com.att.research.xacml.api.pap.PDPPIPConfig; -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.google.common.base.Joiner; -import com.google.common.base.Splitter; -import com.google.common.collect.Sets; - -/** - * This is a simple PAP engine that uses some property files and a simple directory - * structure in the file system to manage a policy repository and set of PDP nodes. - * - * - */ -public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine { - public static final String pipPropertyFile = "pip.properties"; - - private static Log logger = LogFactory.getLog(StdEngine.class); - - public static String PROP_PAP_REPO = "xacml.pap.pdps"; - public static String PROP_PAP_GROUPS = "xacml.pap.groups"; - public static String PROP_PAP_GROUPS_DEFAULT = "xacml.pap.groups.default"; - public static String PROP_PAP_GROUPS_DEFAULT_NAME = "default"; - //this value will be accessed from XacmlPapServlet so that we know if a default group did not exist - //and was just added. This way, we can add the new group to the database. - public boolean wasDefaultGroupJustAdded = false; - - protected final Path repository; - protected Set groups; - - public StdEngine() throws PAPException, IOException { - // - // Get the location in the file system of our repository - // - this.repository = Paths.get(XACMLProperties.getProperty(PROP_PAP_REPO)); - // - // Initialize - // - this.intialize(); - } - - public StdEngine(Properties properties) throws PAPException, IOException { - // - // Get the location in the file system of our repository - // - this.repository = Paths.get(properties.getProperty(PROP_PAP_REPO)); - // - // Initialize - // - this.intialize(); - } - - public StdEngine(Path repository) throws PAPException, IOException { - // - // Save our location - // - this.repository = repository; - // - // Initialize - // - this.intialize(); - } - - private void intialize() throws PAPException, IOException { - // - // Sanity check the repository path - // - if (this.repository == null) { - throw new PAPException ("No repository specified."); - } - if (Files.notExists(this.repository)) { - Files.createDirectory(repository); - } - if (Files.isDirectory(this.repository) == false) { - throw new PAPException ("Repository is NOT a directory: " + this.repository.toAbsolutePath()); - } - if (Files.isWritable(this.repository) == false) { - throw new PAPException ("Repository is NOT writable: " + this.repository.toAbsolutePath()); - } - // - // Load our groups - // - this.loadGroups(); - } - - private void loadGroups() throws PAPException { - // - // Create a properties object - // - Properties properties = new Properties(); - Path file = Paths.get(this.repository.toString(), XACMLProperties.XACML_PROPERTIES_NAME); - try { - // - // Load the properties - // - try (InputStream is = new FileInputStream(file.toFile())) { - properties.load(is); - } - - // - // Parse it - // - this.groups = this.readProperties(this.repository, properties); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to load properties file"); - this.groups = new HashSet<>(); - } - // - // Initialize the default group - // - PDPGroup defaultGroup = this.initializeDefaultGroup(file, properties); - logger.info("Default group is: " + defaultGroup.getId() + "=" + defaultGroup.getName()); - } - - private PDPGroup initializeDefaultGroup(Path file, Properties properties) throws PAPException { - wasDefaultGroupJustAdded = false; - // - // Make sure we have the default group - // - PDPGroup group = this.getDefaultGroup(); - if (group != null) { - return group; - } - // - // We don't have the default group, create it - // - String defaultId = properties.getProperty(PROP_PAP_GROUPS_DEFAULT, PROP_PAP_GROUPS_DEFAULT_NAME); - if(defaultId == null){ - defaultId = PROP_PAP_GROUPS_DEFAULT_NAME; - } - if(defaultId.equals("")){ - defaultId = PROP_PAP_GROUPS_DEFAULT_NAME; - } - //we're going to check one more time in case the PROP_PAP_GROUPS_DEFAULT_NAME doesn't exist - if(defaultId == null){ - defaultId = "default"; - } - if(defaultId.equals("")){ - defaultId = "default"; - } - logger.warn("Default group does NOT exist, creating " + defaultId); - Path defaultPath = Paths.get(this.repository.toString(), defaultId); - try { - // - // Does it exist? - // - if (Files.notExists(defaultPath)) { - // - // Create its directory - // - Files.createDirectory(defaultPath); - // - // Create property files - // - { - Properties props = new Properties(); - props.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, ""); - props.setProperty(XACMLProperties.PROP_ROOTPOLICIES, ""); - Path policyPath = Paths.get(defaultPath.toAbsolutePath().toString(), "xacml.policy.properties"); - Files.createFile(policyPath); - try (OutputStream os = Files.newOutputStream(policyPath)) { - props.store(os, ""); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to write default policy properties"); - } - } - { - Properties props = new Properties(); - props = setPIPProperties(props); - Path pipPath = Paths.get(defaultPath.toAbsolutePath().toString(), "xacml.pip.properties"); - Files.createFile(pipPath); - try (OutputStream os = Files.newOutputStream(pipPath)) { - props.store(os, ""); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to write default pip properties"); - } - } - } - // - // Create the default group - // - StdPDPGroup newDefault = new StdPDPGroup(defaultId, true, "default", "The default group where new PDP's are put.", defaultPath); - // - // Add it to our list - // - this.groups.add(newDefault); - // - // Save our properties out since we have - // a new default group. - // - StdEngine.setGroupProperties(newDefault, properties); - // - // Save it to disk - // - try { - try (OutputStream os = Files.newOutputStream(file)) { - properties.store(os, ""); - } - } catch (IOException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdEngine", "Failed to save properties with new default group information."); - } - // - // Return it - // - wasDefaultGroupJustAdded = true; - return newDefault; - } catch (IOException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdEngine", "Failed to create default group"); - throw new PAPException("Failed to create default group"); - } - } - - @Override - public EcompPDPGroup getDefaultGroup() throws PAPException{ - for (EcompPDPGroup group : this.groups) { - if (group.isDefaultGroup()) { - return group; - } - } - // - // Default group doesn't exist - // - return null; - } - - @Override - public EcompPDPGroup getGroup(String id) throws PAPException { - for (EcompPDPGroup g: this.groups) { - if (g.getId().equals(id)) { - return g; - } - } - return null; - } - - @Override - public void newGroup(String name, String description) throws PAPException, NullPointerException{ - // - // Null check - // - if (name == null) { - throw new NullPointerException(); - } - // - // Do we already have this group? - // - for (PDPGroup group : this.groups) { - if (group.getName().equals(name)) { - throw new PAPException("Group with this name=" + name + " already exists."); - } - } - - - // create an Id that can be used as a file name and a properties file key. - // Ids must not contain \/:*?"<>|=,; - // The ID must also be unique within the current set of PDPGroups. - String id = createNewPDPGroupId(name); - - - // - // Construct the directory path - // - Path groupPath = Paths.get(this.repository.toString(), id); - // - // If it exists already - // - if (Files.exists(groupPath)) { - logger.warn("addGroup " + id + " directory exists" + groupPath.toString()); - } else { - try { - // - // Create the directory - // - Files.createDirectory(groupPath); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to create " + groupPath); - throw new PAPException("Failed to create " + id); - } - } - // - // Create the Policies - // - - Path policyProperties = Paths.get(groupPath.toString(), "xacml.policy.properties"); - if (Files.exists(policyProperties)) { - logger.warn("addGroup " + id + " file exists: " + policyProperties.toString()); - } else { - Properties props = new Properties(); - props.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, ""); - props.setProperty(XACMLProperties.PROP_ROOTPOLICIES, ""); - try { - Files.createFile(policyProperties); - try (OutputStream os = Files.newOutputStream(policyProperties)) { - props.store(os, ""); - } - } catch (IOException e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdEngine", "Failed to create " + policyProperties); - throw new PAPException("Failed to create " + id); - } - } - // - // Create the PIP config - // - Path pipProperties = Paths.get(groupPath.toString(), "xacml.pip.properties"); - Properties props = new Properties(); - if (Files.exists(pipProperties)) { - logger.warn("addGroup " + id + " file exists: " + pipProperties.toString()); - } else { - try { - props = setPIPProperties(props); - Files.createFile(pipProperties); - try (OutputStream os = Files.newOutputStream(pipProperties)) { - props.store(os, ""); - } - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to create " + pipProperties); - throw new PAPException("Failed to create " + id); - } - - } - // - // Ok now add it - // - StdPDPGroup newGroup = new StdPDPGroup(id, name, description, groupPath); - // Add the default PIP configuration. - String list = props.getProperty(XACMLProperties.PROP_PIP_ENGINES); - if (list != null && list.length() > 0) { - Set pipConfigs = new HashSet<>(); - for (String pipID : list.split("[,]")) { - StdPDPPIPConfig config = new StdPDPPIPConfig(pipID, props); - if (config.isConfigured()) { - pipConfigs.add(config); - } - } - newGroup.setPipConfigs(pipConfigs); - } - if (this.groups.add(newGroup)) { - // save the new group in our properties and notify any listeners of the change - groupChanged(newGroup); - } - - } - - - - - /** - * Helper to create a new Group ID. - * Use the Name field to create the Id. - * The Name is expected to not be null; if it is then this method throws an exception. - * The name is supposed to be unique within the current set of groups, - * so creating the ID based on the name will create a unique string. - * - * @param name - * @return - */ - private String createNewPDPGroupId(String name) { - String id = name; - // replace "bad" characters with sequences that will be ok for file names and properties keys. - id = id.replace(" ", "_sp_"); - id = id.replace("\t", "_tab_"); - id = id.replace("\\", "_bksl_"); - id = id.replace("/", "_sl_"); - id = id.replace(":", "_col_"); - id = id.replace("*", "_ast_"); - id = id.replace("?", "_q_"); - id = id.replace("\"", "_quo_"); - id = id.replace("<", "_lt_"); - id = id.replace(">", "_gt_"); - id = id.replace("|", "_bar_"); - id = id.replace("=", "_eq_"); - id = id.replace(",", "_com_"); - id = id.replace(";", "_scom_"); - - return id; - } - - - @Override - public EcompPDP getPDP(String pdpId) throws PAPException { - for (EcompPDPGroup group : this.groups) { - for (EcompPDP pdp : group.getEcompPdps()) { - if (pdp.getId().equals(pdpId)) { - return pdp; - } - } - } - return null; - } - - - @Override - public void movePDP(EcompPDP pdp, EcompPDPGroup newGroup) throws PAPException { - if (newGroup == null) { - throw new NullPointerException("You must specify which group the PDP will belong to."); - } - PDPGroup currentGroup = this.getPDPGroup(pdp); - if (currentGroup == null) { - throw new PAPException("PDP must already belong to a group."); - } - if (currentGroup.equals(newGroup)) { - logger.warn("Already in that group."); - return; - } - if (currentGroup instanceof StdPDPGroup && newGroup instanceof StdPDPGroup) { - if (((StdPDPGroup) currentGroup).removePDP(pdp)) { - boolean result = ((StdPDPGroup) newGroup).addPDP(pdp); - if (result) { - // - // Save the configuration - // - this.doSave(); - } else { - PolicyLogger.error("Failed to add to new group, putting back into original group."); - if (((StdPDPGroup) currentGroup).removePDP(pdp) == false) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Failed to put PDP back into original group."); - } - } - } - } else { - String message = "Unknown PDP group class: " + newGroup.getClass().getCanonicalName() + " and " + currentGroup.getClass().getCanonicalName(); - logger.warn(message); - throw new PAPException(message); - } - } - - - @Override - public void updatePDP(EcompPDP pdp) throws PAPException { - PDP currentPDP = this.getPDP(pdp.getId()); - if (currentPDP == null) { - String message = "Unknown PDP id '" + pdp.getId() + "'"; - logger.warn(message); - throw new PAPException(message); - } - - // the only things that the user can change are name and description - currentPDP.setDescription(pdp.getDescription()); - currentPDP.setName(pdp.getName()); - if (currentPDP instanceof EcompPDP && pdp instanceof EcompPDP) { - ((EcompPDP)currentPDP).setJmxPort(((EcompPDP)pdp).getJmxPort()); - } - this.doSave(); - } - - @Override - public void removePDP(EcompPDP pdp) throws PAPException { - PDPGroup group = this.getPDPGroup(pdp); - if (group == null) { - throw new NullPointerException(); - } - if (group instanceof StdPDPGroup) { - boolean result = ((StdPDPGroup) group).removePDP(pdp); - if (result) { - this.doSave(); - } - return; - } - String message = "Unknown PDP group class: " + group.getClass().getCanonicalName(); - logger.warn(message); - throw new PAPException(message); - } - - - @Override - /** - * Should never be called - Detailed status is held on the PDP, not the PAP - */ - public PDPStatus getStatus(EcompPDP pdp) throws PAPException { - return getPDP(pdp.getId()).getStatus(); - } - - @Override - public void publishPolicy(String id, String name, boolean isRoot, InputStream policy, EcompPDPGroup group) throws PAPException { - if (group == null) { - throw new NullPointerException(); - } - if (group instanceof StdPDPGroup && this.groups.contains(group)) { - ((StdPDPGroup) group).publishPolicy(id, name, isRoot, policy); - return; - } - logger.warn("unknown PDP Group: " + group); - throw new PAPException("Unknown PDP Group: " + group.getId()); - } - - // Currently not used on the PAP side. This is done by ((StdPDPGroup) group).copyPolicyToFile - @Override - public void copyPolicy(PDPPolicy policy, EcompPDPGroup group) - throws PAPException { - } - - - @Override - public void removePolicy(PDPPolicy policy, EcompPDPGroup group) throws PAPException { - if (group == null) { - throw new NullPointerException(); - } - if (group instanceof StdPDPGroup && this.groups.contains(group)) { - ((StdPDPGroup) group).removePolicy(policy); - return; - } - logger.warn("unknown PDP Group: " + group); - throw new PAPException("Unknown PDP Group: " + group.getId()); - } - - - // - // HELPER methods - // - - private Set readProperties(Path repository, Properties properties) throws PAPException { - Set groups = new HashSet<>(); - // - // See if there is a groups property - // - String groupList = properties.getProperty(PROP_PAP_GROUPS, ""); - if (groupList == null) { - logger.warn("null group list " + PROP_PAP_GROUPS); - groupList = ""; - } - if (logger.isDebugEnabled()) { - logger.debug("group list: " + groupList); - } - // - // Iterate the groups, converting to a set ensures we have unique groups. - // - for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(groupList)) { - // - // Add our Group Object - // - StdPDPGroup g = new StdPDPGroup(id.trim(), - id.equals(properties.getProperty(PROP_PAP_GROUPS_DEFAULT, PROP_PAP_GROUPS_DEFAULT_NAME)), - properties, - Paths.get(repository.toString(), id)); - - // - // Add it in - // - groups.add(g); - } - // - // Dump what we got - // - if (logger.isDebugEnabled()) { - logger.debug("PDP Group List: " + groups.toString()); - } - return groups; - } - - private void saveConfiguration() throws PAPException, IOException { - // - // Create our properties object - // - Properties properties = new Properties() { - private static final long serialVersionUID = 1L; - // For Debugging it is helpful for the file to be in a sorted order, - // any by returning the keys in the natural Alpha order for strings we get close enough. - // TreeSet is sorted, and this just overrides the normal Properties method to get the keys. - @Override - public synchronized Enumeration keys() { - return Collections.enumeration(new TreeSet(super.keySet())); - } - }; - // - // Iterate our groups - // - List ids = new ArrayList<>(); - for (PDPGroup group : this.groups) { - ids.add(group.getId()); - properties.setProperty(group.getId() + ".name", (group.getName() == null ? "" : group.getName())); - properties.setProperty(group.getId() + ".description", (group.getDescription() == null ? "" : group.getDescription())); - // - // Iterate its PDPs - // - List pdps = new ArrayList<>(); - for (PDP pdp : group.getPdps()) { - pdps.add(pdp.getId()); - properties.setProperty(pdp.getId() + ".name", (pdp.getName() == null ? "" : pdp.getName())); - properties.setProperty(pdp.getId() + ".description", (pdp.getDescription() == null ? "" : pdp.getDescription())); - if (pdp instanceof EcompPDP) { - properties.setProperty(pdp.getId() + ".jmxport", (((EcompPDP)pdp).getJmxPort()==0 ? "" : ((EcompPDP)pdp).getJmxPort()).toString()); - } - } - String pdpList = ""; - if (pdps.size() == 1) { - pdpList = pdps.get(0); - } else if (pdps.size() > 1) { - pdpList = Joiner.on(',').skipNulls().join(pdps); - } - if (logger.isDebugEnabled()) { - logger.debug("Group " + group.getId() + " PDPS: " + pdpList); - } - properties.setProperty(group.getId() + ".pdps", pdpList); - } - if (ids.isEmpty()) { - throw new PAPException("Inconsistency - we have NO groups. We should have at least one."); - } - String groupList = ""; - if (ids.size() == 1) { - groupList = ids.get(0); - } else if (ids.size() > 1){ - groupList = Joiner.on(',').skipNulls().join(ids); - } - logger.info("New Group List: " + groupList); - - properties.setProperty(PROP_PAP_GROUPS, groupList); - // - // Get the default group - // - PDPGroup defaultGroup = this.getDefaultGroup(); - if (defaultGroup == null) { - throw new PAPException("Invalid state - no default group."); - } - properties.setProperty(PROP_PAP_GROUPS_DEFAULT, defaultGroup.getId()); - // - // Now we can save the file - // - Path file = Paths.get(this.repository.toString(), "xacml.properties"); - try (OutputStream os = Files.newOutputStream(file)) { - properties.store(os, ""); - } - } - - public static void removeGroupProperties(String id, Properties properties) { - for (Object key : properties.keySet()) { - if (key.toString().startsWith(id + ".")) { - properties.remove(key); - } - } - } - - public static void setGroupProperties(PDPGroup group, Properties properties) { - // - // make sure its in the list of groups - // - Iterable groups = Splitter.on(',').trimResults().omitEmptyStrings().split( properties.getProperty(PROP_PAP_GROUPS, "")); - boolean inList = false; - for (String g : groups) { - if (g.equals(group.getId())) { - inList = true; - } - } - if (inList == false) { - Set grps = Sets.newHashSet(groups); - grps.add(group.getId()); - String newGroupList = "";; - if (grps.size() == 1) { - newGroupList = grps.iterator().next(); - } else if (grps.size() > 1) { - newGroupList = Joiner.on(',').skipNulls().join(grps); - } - logger.info("New Group List: " + newGroupList); - properties.setProperty(PROP_PAP_GROUPS, newGroupList); - } - // - // Set its properties - // - properties.setProperty(group.getId() + ".name", group.getName()); - properties.setProperty(group.getId() + ".description", group.getDescription()); - // - // Set its PDP list - // - if (group.getPdps().size() > 0) { - String pdpList = ""; - if (group.getPdps().size() == 1) { - pdpList = group.getPdps().iterator().next().getId(); - } else if (group.getPdps().size() > 1) { - Set ids = new HashSet<>(); - for (PDP pdp : group.getPdps()) { - ids.add(pdp.getId()); - } - pdpList = Joiner.on(',').skipNulls().join(ids); - } - properties.setProperty(group.getId() + ".pdps", pdpList); - } else { - properties.setProperty(group.getId() + ".pdps", ""); - } - } - - - public void changed() { - if (logger.isDebugEnabled()) { - logger.debug("changed"); - } - this.doSave(); - this.fireChanged(); - } - - public void groupChanged(EcompPDPGroup group) { - if (logger.isDebugEnabled()) { - logger.debug("groupChanged: " + group); - } - this.doSave(); - this.firePDPGroupChanged(group); - } - - - public void pdpChanged(EcompPDP pdp) { - if (logger.isDebugEnabled()) { - logger.debug("pdpChanged: " + pdp); - } - this.doSave(); - this.firePDPChanged(pdp); - } - - private void doSave() { - try { - // - // Save the configuration - // - this.saveConfiguration(); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdEngine", "Failed to save configuration"); - } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdEngine", "Failed to save configuration"); - } - } - - private Properties setPIPProperties(Properties props){ - props.setProperty(XACMLProperties.PROP_PIP_ENGINES, "AAF"); - props.setProperty("AAF.name", "AAFEngine"); - props.setProperty("AAF.description", "AAFEngine to communicate with AAF to take decisions"); - props.setProperty("AAF.classname","org.openecomp.policy.xacml.std.pip.engines.aaf.AAFEngine"); - // read from PIP properties file. - Path file = Paths.get(pipPropertyFile); - if (!Files.notExists(file)) { - InputStream in; - Properties prop = new Properties(); - try { - in = new FileInputStream(file.toFile()); - prop.load(in); - } catch (IOException e) { - PolicyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "can not load the pip properties from file" +e); - } - props = prop; - } - return props; - } - - - @Override - public Set getEcompPDPGroups() throws PAPException { - final Set grps = new HashSet<>(); - for (EcompPDPGroup g : this.groups) { - grps.add(g); - } - return Collections.unmodifiableSet(grps); - } - - @Override - public EcompPDPGroup getPDPGroup(EcompPDP pdp) throws PAPException { - for (EcompPDPGroup group : this.groups) { - if (group.getPdps().contains(pdp)) { - return group; - } - } - return null; - } - - @Override - public void SetDefaultGroup(EcompPDPGroup group) throws PAPException { - boolean changesMade = false; - for (EcompPDPGroup aGroup : groups) { - if (aGroup.getId().equals(group.getId())) { - if ( ! aGroup.isDefaultGroup()) { - if (aGroup instanceof StdPDPGroup) { - ((StdPDPGroup) aGroup).setDefault(true); - changesMade = true; - } else { - throw new IllegalArgumentException("Group in groups of unknown type '" + aGroup.getClass().getName() + "'"); - } - } - } else { - // not the new default group - if (aGroup.isDefaultGroup()) { - if (aGroup instanceof StdPDPGroup) { - ((StdPDPGroup) aGroup).setDefault(false); - changesMade = true; - } else { - throw new IllegalArgumentException("Group in groups of unknown type '" + aGroup.getClass().getName() + "'"); - } - } - } - } - if (changesMade) { - this.doSave(); - } - - return; - - } - - @Override - public void newPDP(String id, EcompPDPGroup group, String name, String description, int jmxport) - throws PAPException, NullPointerException { - if (group == null) { - throw new PAPException("You must specify which group the PDP will belong to."); - } - if (this.groups.contains(group) == false) { - throw new PAPException("Unknown group, not in our list."); - } - for (EcompPDP p : group.getEcompPdps()) { - if (p.getId().equals(id)) { - throw new PAPException("A PDP with this ID exists."); - } - } - if (group instanceof StdPDPGroup) { - StdPDP pdp = new StdPDP(id, name, description, jmxport); - if (((StdPDPGroup) group).addPDP(pdp)) { - // - // Save the properties and notify any listeners - // - pdpChanged(pdp); - return; - } - } - return; - - } - - @Override - public void updateGroup(EcompPDPGroup group) throws PAPException { - if (group == null || group.getId() == null) { - throw new PAPException("Group or id is null"); - } - if (group.getName() == null || group.getName().trim().length() == 0) { - throw new PAPException("New name for group cannot be null or blank"); - } - StdPDPGroup existingGroup = (StdPDPGroup)getGroup(group.getId()); - if (existingGroup == null) { - throw new PAPException("Update found no existing group with id '" + group.getId() + "'"); - } - - - // We do dramatically different things when the Name changes - // because the Name is essentially the identity of the group (as the User knows it) so when the Identity changes we have to change the group ID. - if (group.getName().equals(existingGroup.getName())) { - - // update the disk - try { - ((StdPDPGroup)group).saveGroupConfiguration(); - } catch (IOException e) { - throw new PAPException("Unable to save new configuration for '" + group.getName() + "': " + e.getMessage()); - } - // update the group in the set by simply replacing the old instance with the new one - this.groups.remove(existingGroup); - this.groups.add((StdPDPGroup)group); - - } else { - // the name/identity of the group has changed - // generate the new id - String newId = createNewPDPGroupId(group.getName()); - - // make sure no other group uses the new id - for (EcompPDPGroup g : groups) { - if (g.getId().equals(newId)) { - throw new PAPException("Replacement name maps to ID '" + newId + "' which is already in use"); - } - } - ((StdPDPGroup)group).setId(newId); - - // rename the existing directory to the new id - Path oldPath = existingGroup.getDirectory(); - Path newPath = Paths.get(oldPath.getParent().toString(), newId); - ((StdPDPGroup)group).setDirectory(newPath); - - try { - boolean success = oldPath.toFile().renameTo(newPath.toFile()); - if ( ! success) { - throw new PAPException("Unable to rename directory; reason unknown"); - } - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdEngine", "Unable to rename directory"); - throw new PAPException("Unable to move directory from '" + oldPath + "' to '" + newPath + "': " + e.getMessage()); - } - // update the disk - try { - ((StdPDPGroup)group).saveGroupConfiguration(); - } catch (IOException e) { - throw new PAPException("Unable to save new configuration for '" + group.getName() + "': " + e.getMessage()); - } - - // save the new group into the Set - groups.remove(existingGroup); - groups.add((StdPDPGroup)group); - - } - - // perhaps only the group changed, but if the name/id changed it may look to a listener like more than one group - changed(); - - - } - - @Override - public void removeGroup(EcompPDPGroup group, EcompPDPGroup newGroup) throws PAPException, NullPointerException { - if (group == null) { - throw new NullPointerException(); - } - // - // Does this group exist? - // - if (this.groups.contains(group) == false) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "This group doesn't exist."); - throw new PAPException("The group '" + group.getId() + "' does not exist"); - } - // - // Is it the default group? - // - if (group.isDefaultGroup()) { - throw new PAPException("You cannot delete the default group."); - } - Set pdps = group.getEcompPdps(); - // - // Are there PDPs? If so, then we need a target group - // - if (pdps.isEmpty() == false && newGroup == null) { - throw new NullPointerException("Group targeted for deletion has PDPs, you must provide a new group for them."); - } - // - // Move the PDPs - // - if (pdps.isEmpty() == false) { - if (! (newGroup instanceof StdPDPGroup)) { - throw new PAPException("Unexpected class for newGroup: " + newGroup.getClass().getCanonicalName()); - } - // The movePDP function will modify the set of PDPs in the group. - // To avoid concurrent modification exceptions we need to duplicate the list before calling that function. - List pdpList = new ArrayList<>(); - for (EcompPDP pdp : pdps) { - pdpList.add(pdp); - } - // now we can use the PDPs from the list without having ConcurrentAccessExceptions - for (EcompPDP pdp : pdpList) { - this.movePDP(pdp, newGroup); - } - } - // - // remove the directory for the group - // - String id = group.getId(); - Path groupPath = Paths.get(this.repository.toString(), id); - // - // If it exists already - // - if ( ! Files.exists(groupPath)) { - logger.warn("removeGroup " + id + " directory does not exist" + groupPath.toString()); - } else { - try { - Files.walkFileTree(groupPath, new SimpleFileVisitor() { - - @Override - public FileVisitResult visitFile(Path file, - BasicFileAttributes attrs) throws IOException { - Files.delete(file); - return super.visitFile(file, attrs); - } - - }); - // - // delete the directory - // - Files.delete(groupPath); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to delete " + groupPath); - throw new PAPException("Failed to delete " + id); - } - } - - // remove the group from the set of all groups - groups.remove(group); - - // - // Save changes - // - changed(); - this.doSave(); - return; - - } - -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdEngineFactory.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdEngineFactory.java deleted file mode 100644 index b8ca1f2e9..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdEngineFactory.java +++ /dev/null @@ -1,57 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.std.pap; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - -import java.io.IOException; -import java.util.Properties; - -import org.openecomp.policy.xacml.api.pap.ECOMPPapEngineFactory; -import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.util.FactoryException; - -public class StdEngineFactory extends ECOMPPapEngineFactory { - - @Override - public PAPPolicyEngine newEngine() throws FactoryException, PAPException { - try { - return (PAPPolicyEngine) new StdEngine(); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "StdEngineFactory", "Failed to create engine"); - return null; - } - } - - @Override - public PAPPolicyEngine newEngine(Properties properties) throws FactoryException, - PAPException { - try { - return (PAPPolicyEngine) new StdEngine(properties); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "StdEngineFactory", "Failed to create engine"); - return null; - } - } - -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPAPPolicy.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPAPPolicy.java deleted file mode 100644 index 61ba86b8a..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPAPPolicy.java +++ /dev/null @@ -1,910 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.std.pap; - -import java.io.Serializable; -import java.net.URI; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.openecomp.policy.xacml.api.pap.EcompPAPPolicy; - -public class StdPAPPolicy implements EcompPAPPolicy, Serializable{ - private static final long serialVersionUID = 5260230629397322000L; - - private String policyName = null; - private String oldPolicyFileName = null; - private String policyDescription = null; - private String ecompName = null; - private String configName = null; - private Map dyanamicFieldConfigAttributes = new HashMap<>(); - private Map dropDownMap = new HashMap<>(); - private Map dynamicSettingsMap = new HashMap<>(); - private List dynamicRuleAlgorithmLabels; - private List dynamicRuleAlgorithmCombo; - private List dynamicRuleAlgorithmField1; - private List dynamicRuleAlgorithmField2; - private List dynamicVariableList; - private List dataTypeList; - private String configBodyData = null; - private String policyID = null; - private String ruleID = null; - private String brmsController; - private ArrayList brmsDependency; - private String configType = null; - private Boolean editPolicy = false; - private Boolean draft = false; - private String version = null; - private String domain = null; - private String configPolicyType = null; - private String jsonBody = null; - private String serviceType = null; - private Integer highestVersion = null; - private URI location = null; - private String actionPerformer = null; - private String actionAttribute = null; - private String actionBody = null; - private String actionDictHeader = null; - private String actionDictType = null; - private String actionDictUrl = null; - private String actionDictMethod = null; - private String uuid = null; - private String msLocation = null; - private String priority = null; - private Map drlRuleAndUIParams=null; - private String deleteCondition = null; - private String dictionaryType = null; - private String dictionary = null; - private String dictionaryFields = null; - private String providerComboBox = null; - private String riskType = null; - private String guard = null; - private String riskLevel; - private String ttlDate = null; - - - public StdPAPPolicy() { - - } - - //Constructor for sending location when pushing policies - public StdPAPPolicy(URI location) { - this.location = location; - } - - //Constructor for Validating Config Policies - public StdPAPPolicy(String policyName, String body, String configType, String configPolicyType) { - this.policyName = policyName; - this.configBodyData = body; - this.configType = configType; - this.configPolicyType = configPolicyType; - } - - //convenience constructor - public StdPAPPolicy(String configPolicyType, String policyName, String description, String ecompName, String configName, Map attributes, String configType, - String body, Boolean editPolicy, String domain, String riskLevel, String riskType, String guard, String ttlDate){ - this(configPolicyType, policyName, description, ecompName, configName, attributes, configType, - body, editPolicy, domain, 1, riskLevel, riskType, guard, ttlDate); - } - - //Constructor for Create/Update Action Policies from API - public StdPAPPolicy(String policyName, String description, Map attributes, List dynamicRuleAlgorithmLabels, List dynamicRuleAlgorithmCombo, - List dynamicRuleAlgorithmField1, List dynamicRuleAlgorithmField2, String actionPerformer,String actionAttribute, Boolean editPolicy, - String domain, int highestVersion) { - - this.policyName = policyName; - this.policyDescription = description; - this.dyanamicFieldConfigAttributes = attributes; - this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; - this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; - this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; - this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; - this.actionPerformer = actionPerformer; - this.actionAttribute = actionAttribute; - this.editPolicy = editPolicy; - this.domain = domain; - this.highestVersion = highestVersion; - - } - - //Constructor for Create/Update Decision Policies from Admin Console - public StdPAPPolicy(String policyName, String description, String ecompName, String providerComboBox, Map attributes, Map settings, - List dynamicRuleAlgorithmLabels, List dynamicRuleAlgorithmCombo, List dynamicRuleAlgorithmField1, - List dynamicRuleAlgorithmField2, Map dropDownMap, List dynamicVariableList, - List dataTypeList, Boolean editPolicy, String domain, int highestVersion) { - - this.policyName = policyName; - this.policyDescription = description; - this.ecompName = ecompName; - this.setProviderComboBox(providerComboBox); - this.dyanamicFieldConfigAttributes = attributes; - this.dynamicSettingsMap = settings; - this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; - this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; - this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; - this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; - this.dynamicVariableList = dynamicVariableList; - this.dataTypeList = dataTypeList; - this.dropDownMap = dropDownMap; - this.editPolicy = editPolicy; - this.domain = domain; - this.highestVersion = highestVersion; - - } - - - //Constructor for Create Config Policies from API and Admin Console - //Constructor for Updating Config Policies from the API - public StdPAPPolicy(String configPolicyType, String policyName, String description, String ecompName, String configName, Map attributes, String configType, - String body, Boolean editPolicy, String domain, int highestVersion, String riskLevel, String riskType, String guard, String ttlDate) { - - this.configPolicyType = configPolicyType; - this.policyName = policyName; - this.policyDescription = description; - this.ecompName = ecompName; - this.configName = configName; - this.dyanamicFieldConfigAttributes = attributes; - this.configType = configType; - this.configBodyData = body; - this.editPolicy = editPolicy; - this.domain = domain; - this.highestVersion = highestVersion; - this.riskLevel = riskLevel; - this.riskType = riskType; - this.guard = guard; - this.ttlDate = ttlDate; - } - - //convenience constructor - public StdPAPPolicy (String configPolicyType, String policyName, String description, String ecompName, String configName, Map attributes, String body, String policyID, - String ruleID, String configType, Boolean editPolicy, String version, String domain, String riskLevel, String riskType, String guard, String ttlDate) { - this (configPolicyType, policyName, description, ecompName, configName, attributes, body, policyID, - ruleID, configType, editPolicy, version, domain, 1, riskLevel, riskType, guard, ttlDate); - } - - //Constructor for Updating Config Policies from Admin Console - public StdPAPPolicy (String configPolicyType, String policyName, String description, String ecompName, String configName, Map attributes, String body, String policyID, - String ruleID, String configType, Boolean editPolicy, String version, String domain, int highestVersion, String riskLevel, String riskType, String guard, String ttlDate) { - - this.configPolicyType = configPolicyType; - this.policyName = policyName; - this.policyDescription = description; - this.ecompName = ecompName; - this.configName = configName; - this.dyanamicFieldConfigAttributes = attributes; - this.configBodyData = body; - this.policyID = policyID; - this.ruleID = ruleID; - this.configType = configType; - this.editPolicy = editPolicy; - this.version = version; - this.domain = domain; - this.highestVersion = highestVersion; - this.riskLevel = riskLevel; - this.riskType = riskType; - this.guard = guard; - this.ttlDate = ttlDate; - } - - - //Constructor for Creating Config Firewall Policies - public StdPAPPolicy (String configPolicyType, String policyName, String description, String configName, - Boolean editPolicy, String domain, String jsonBody, Integer highestVersion, String riskLevel, String riskType, String guard, String ttlDate) { - - this.configPolicyType = configPolicyType; - this.policyName = policyName; - this.policyDescription = description; - this.configName = configName; - this.editPolicy = editPolicy; - this.domain = domain; - this.jsonBody = jsonBody; - this.highestVersion = highestVersion; - this.riskLevel = riskLevel; - this.riskType = riskType; - this.guard = guard; - this.ttlDate = ttlDate; - - } - - //Constructor for Creating Goc Policies - public StdPAPPolicy (String configPolicyType, String policyName, String description, String configName, - Boolean editPolicy, String domain, String jsonBody, Integer highestVersion, String eCompName, String riskLevel, String riskType, String guard, String ttlDate) { - - this.configPolicyType = configPolicyType; - this.policyName = policyName; - this.policyDescription = description; - this.configName = configName; - this.editPolicy = editPolicy; - this.domain = domain; - this.jsonBody = jsonBody; - this.highestVersion = highestVersion; - this.ecompName=eCompName; - this.riskLevel = riskLevel; - this.riskType = riskType; - this.guard = guard; - this.ttlDate = ttlDate; - } - - //Constructor for Creating BRMS Policies from the Admin Console - public StdPAPPolicy (String configPolicyType, String policyName, String description, - String configName, Boolean editPolicy, String domain, - Map dyanamicFieldConfigAttributes, Integer highestVersion, String eCompName, - String configBodyData, String riskLevel, String riskType, String guard, String ttlDate, String brmsController, ArrayList brmsDependency) { - - this.configPolicyType = configPolicyType; - this.policyName = policyName; - this.policyDescription = description; - this.configName = configName; - this.editPolicy = editPolicy; - this.domain = domain; - this.dyanamicFieldConfigAttributes = dyanamicFieldConfigAttributes; - this.highestVersion = highestVersion; - this.ecompName=eCompName; - this.configBodyData=configBodyData; - this.riskLevel = riskLevel; - this.riskType = riskType; - this.guard = guard; - this.ttlDate = ttlDate; - this.brmsController = brmsController; - this.brmsDependency = brmsDependency; - } - - //Constructor for Creating BRMS Param Policies from the Admin Console - public StdPAPPolicy (String configPolicyType, String policyName, String description, - String configName, Boolean editPolicy, String domain, - Map dyanamicFieldConfigAttributes, Integer highestVersion, String eCompName, - String configBodyData,Map drlRuleAndUIParams, String riskLevel, String riskType, String guard, String ttlDate, String brmsController, ArrayList brmsDependency) { - - this.configPolicyType = configPolicyType; - this.policyName = policyName; - this.policyDescription = description; - this.configName = configName; - this.editPolicy = editPolicy; - this.domain = domain; - this.dyanamicFieldConfigAttributes = dyanamicFieldConfigAttributes; - this.highestVersion = highestVersion; - this.ecompName=eCompName; - this.configBodyData=configBodyData; - this.drlRuleAndUIParams=drlRuleAndUIParams; - this.riskLevel = riskLevel; - this.riskType = riskType; - this.guard = guard; - this.ttlDate = ttlDate; - this.brmsController = brmsController; - this.brmsDependency = brmsDependency; - } - - //Constructor for Creating CloseLoop_Fault and Performance Metric Policies - public StdPAPPolicy (String configPolicyType, String policyName, String description, String ecompName, - String jsonBody, Boolean draft, String oldPolicyFileName, String serviceType, Boolean editPolicy, - String domain, Integer highestVersion, String riskLevel, String riskType, String guard, String ttlDate) { - - this.configPolicyType = configPolicyType; - this.policyName = policyName; - this.policyDescription = description; - this.ecompName = ecompName; - this.jsonBody = jsonBody; - this.draft = draft; - this.oldPolicyFileName = oldPolicyFileName; - this.serviceType = serviceType; - this.editPolicy = editPolicy; - this.domain = domain; - this.highestVersion = highestVersion; - this.riskLevel = riskLevel; - this.riskType = riskType; - this.guard = guard; - this.ttlDate = ttlDate; - } - - //Constructor for Updating Config Firewall Policies from the Admin Console - public StdPAPPolicy (String configPolicyType, String policyName, String description, String configName, Boolean editPolicy, String domain, String policyID, - String ruleID, String version, String jsonBody, Integer highestVersion, String riskLevel, String riskType, String guard, String ttlDate) { - - this.configPolicyType = configPolicyType; - this.policyName = policyName; - this.policyDescription = description; - this.configName = configName; - this.editPolicy = editPolicy; - this.domain = domain; - this.policyID = policyID; - this.ruleID = ruleID; - this.version = version; - this.jsonBody = jsonBody; - this.highestVersion = highestVersion; - this.riskLevel = riskLevel; - this.riskType = riskType; - this.guard = guard; - this.ttlDate = ttlDate; - } - - //Constructor for Micro Service Creating/Updating Policies from the Admin Console - public StdPAPPolicy(String configPolicyType, String policyName, String description, String ecompName, String configName, String serviceType, String uuid, - String msLocation, String jsonBody, String priority, String version, Boolean editPolicy, String domain, int highestVersion, String riskLevel, - String riskType, String guard, String ttlDate) { - - this.configPolicyType = configPolicyType; - this.policyName = policyName; - this.policyDescription = description; - this.ecompName = ecompName; - this.configName = configName; - this.serviceType = serviceType; - this.uuid = uuid; - this.msLocation = msLocation; - this.priority = priority; - this.version = version; - this.jsonBody = jsonBody; - this.editPolicy = editPolicy; - this.domain = domain; - this.highestVersion = highestVersion; - this.riskLevel = riskLevel; - this.riskType = riskType; - this.guard = guard; - this.ttlDate = ttlDate; - } - - //Constructor for Updating Goc Policies from the Admin Console - public StdPAPPolicy (String configPolicyType, String policyName, String description, - String configName, Boolean editPolicy, String domain, - String policyID, String ruleID, String version, - String jsonBody, Integer highestVersion, String eCompName,String riskLevel, String riskType, String guard, String ttlDate) { - - this.configPolicyType = configPolicyType; - this.policyName = policyName; - this.policyDescription = description; - this.configName = configName; - this.editPolicy = editPolicy; - this.domain = domain; - this.policyID = policyID; - this.ruleID = ruleID; - this.version = version; - this.jsonBody = jsonBody; - this.highestVersion = highestVersion; - this.ecompName=eCompName; - this.riskLevel = riskLevel; - this.riskType = riskType; - this.guard = guard; - this.ttlDate = ttlDate; - } - - //Constructor for Updating Brms Policies from the Admin Console - public StdPAPPolicy (String configPolicyType, String policyName, String description, - String configName, Boolean editPolicy, String domain, - String policyID, String ruleID, String version, - Map dyanamicFieldConfigAttributes, Integer highestVersion, String eCompName, - String configBodyData , String riskLevel, String riskType, String guard, String ttlDate - ) { - this.configPolicyType = configPolicyType; - this.policyName = policyName; - this.policyDescription = description; - this.configName = configName; - this.editPolicy = editPolicy; - this.domain = domain; - this.policyID = policyID; - this.ruleID = ruleID; - this.version = version; - this.dyanamicFieldConfigAttributes = dyanamicFieldConfigAttributes; - this.highestVersion = highestVersion; - this.ecompName=eCompName; - this.configBodyData=configBodyData; - this.riskLevel = riskLevel; - this.riskType = riskType; - this.guard = guard; - this.ttlDate = ttlDate; - } - - //Constructor for Updating Brms Param Policies from the Admin Console - public StdPAPPolicy (String configPolicyType, String policyName, String description, - String configName, Boolean editPolicy, String domain, - String policyID, String ruleID, String version, - Map dyanamicFieldConfigAttributes, Integer highestVersion, String eCompName, - Map drlRuleAndUIParams, String riskLevel, String riskType, String guard, String ttlDate - ) { - this.configPolicyType = configPolicyType; - this.policyName = policyName; - this.policyDescription = description; - this.configName = configName; - this.editPolicy = editPolicy; - this.domain = domain; - this.policyID = policyID; - this.ruleID = ruleID; - this.version = version; - this.dyanamicFieldConfigAttributes = dyanamicFieldConfigAttributes; - this.highestVersion = highestVersion; - this.ecompName=eCompName; - this.drlRuleAndUIParams=drlRuleAndUIParams; - this.riskLevel = riskLevel; - this.riskType = riskType; - this.guard = guard; - this.ttlDate = ttlDate; - } - - // Constructor for deleting policies from the API - public StdPAPPolicy(String policyName, String deleteCondition) { - this.policyName = policyName; - this.deleteCondition = deleteCondition; - } - - // Constructor for creating dictionary items from the API> - public StdPAPPolicy(String dictionaryType, String dictionary, String dictionaryFields) { - this.dictionaryType = dictionaryType; - this.dictionary = dictionary; - this.dictionaryFields = dictionaryFields; - } - - @Override - public String getPolicyName() { - return policyName; - } - - @Override - public String getPolicyDescription() { - return policyDescription; - } - - @Override - public String getEcompName() { - return ecompName; - } - - @Override - public String getConfigName() { - return configName; - } - - @Override - public Map getDynamicFieldConfigAttributes() { - return dyanamicFieldConfigAttributes; - } - - @Override - public String getConfigBodyData() { - return configBodyData; - } - - @Override - public String getPolicyID() { - return policyID; - } - - @Override - public String getRuleID() { - return ruleID; - } - - @Override - public String getConfigType() { - return configType; - } - - @Override - public Boolean isEditPolicy() { - return editPolicy; - } - - @Override - public Boolean isDraft() { - return draft; - } - - @Override - public String getVersion() { - return version; - } - - @Override - public String getDomainDir() { - return domain; - } - - @Override - public String getConfigPolicyType() { - return configPolicyType; - } - - @Override - public String getJsonBody() { - return jsonBody; - } - - @Override - public Integer getHighestVersion() { - return highestVersion; - } - - @Override - public URI getLocation() { - return location; - } - - @Override - public List getDynamicRuleAlgorithmLabels() { - return dynamicRuleAlgorithmLabels; - } - - @Override - public List getDynamicRuleAlgorithmCombo() { - return dynamicRuleAlgorithmCombo; - } - - @Override - public List getDynamicRuleAlgorithmField1() { - return dynamicRuleAlgorithmField1; - } - - @Override - public List getDynamicRuleAlgorithmField2() { - return dynamicRuleAlgorithmField2; - } - - @Override - public String getActionPerformer() { - return actionPerformer; - } - - @Override - public String getActionAttribute() { - return actionAttribute; - } - - @Override - public String getActionBody() { - return actionBody; - } - - @Override - public Map getDropDownMap() { - return dropDownMap; - } - - @Override - public String getActionDictHeader() { - return actionDictHeader; - } - - @Override - public String getActionDictType() { - return actionDictType; - } - - @Override - public String getActionDictUrl() { - return actionDictUrl; - } - - @Override - public String getActionDictMethod() { - return actionDictMethod; - } - - @Override - public Map getDynamicSettingsMap() { - return dynamicSettingsMap; - } - - @Override - public List getDynamicVariableList() { - return dynamicVariableList; - } - - @Override - public List getDataTypeList() { - return dataTypeList; - } - - @Override - public String getOldPolicyFileName() { - return oldPolicyFileName; - } - - @Override - public String getServiceType() { - return serviceType; - } - - @Override - public String getUuid() { - return uuid; - } - - @Override - public String getMsLocation() { - return msLocation; - } - - @Override - public String getPriority() { - return priority; - } - - @Override - public String getDeleteCondition() { - return deleteCondition; - } - - @Override - public String getDictionaryType() { - return dictionaryType; - } - - @Override - public String getDictionary() { - return dictionary; - } - - @Override - public String getTTLDate(){ - return ttlDate; - } - - @Override - public String getDictionaryFields() { - return dictionaryFields; - } - - @Override - public String getRiskType() { - return riskType; - } - - @Override - public String getRiskLevel() { - return riskLevel; - } - - @Override - public String getGuard() { - return guard; - } - - @Override - public String toString() { - return "StdPAPPolicy [policyName=" + policyName + ", policyDescription=" + policyDescription + ", ecompName=" - + ecompName + ", configName=" + configName + ", dyanamicFieldConfigAttributes=" + dyanamicFieldConfigAttributes + ", configBodyData=" + configBodyData - + ", policyID=" + policyID + ", ruleID=" + ruleID + ", configType=" + configType + ", editPolicy=" + ", version=" + ", domain=" + domain - + ", configPolicyType=" + configPolicyType + ", jsonBody=" + jsonBody + ", highestVersion=" + highestVersion + ", location=" + location - + ",dynamicRuleAlgorithmLabels=" + dynamicRuleAlgorithmLabels + ",dynamicRuleAlgorithmCombo=" + dynamicRuleAlgorithmCombo - + ",dynamicRuleAlgorithmField1=" + dynamicRuleAlgorithmField1 + ",dynamicRuleAlgorithmField2=" + dynamicRuleAlgorithmField2 - + ",actionPerformer=" + actionPerformer + ",actionAttribute=" + actionAttribute + ",actionBody=" + actionBody + ",dropDownMap=" + dropDownMap - + ",actionDictHeader=" + actionDictHeader + ",actionDictType=" + actionDictType + ",actionDictUrl=" + actionDictUrl - + ",actionDictMethod=" + actionDictMethod + ",dynamicSettingsMap=" + dynamicSettingsMap + ",dynamicVariableList=" + dynamicVariableList + ",providerComboBox=" + providerComboBox - + ",dataTypeList=" + dataTypeList + ",draft=" + ",oldPolicyFileName=" + oldPolicyFileName + ",serviceType=" + serviceType - + ",uuid=" + uuid + ",msLocation=" + msLocation + ",priority=" + priority + ",deleteCondition=" + deleteCondition + ",dictionaryType=" + dictionaryType - + ",dictionary=" + dictionary + ",dictionaryFields=" + dictionaryFields + ",uuid=" + uuid + ",msLocation=" + msLocation + ",priority=" - + priority + ",deleteCondition=" + deleteCondition + ",riskType="+riskType + ",riskLevel="+riskLevel + ",guard="+ guard + ",ttlDate="+ ttlDate + "]"; - } - - // Methods needed for JSON Deserialization - public void setPolicyName(String policyName) { - this.policyName = policyName; - } - - public void setPolicyDescription(String policyDescription) { - this.policyDescription = policyDescription; - } - - public void setEcompName(String ecompName) { - this.ecompName = ecompName; - } - - public void setConfigName(String configName) { - this.configName = configName; - } - - public void setDyanamicFieldConfigAttributes( - Map dyanamicFieldConfigAttributes) { - this.dyanamicFieldConfigAttributes = dyanamicFieldConfigAttributes; - } - - public void setConfigBodyData(String configBodyData) { - this.configBodyData = configBodyData; - } - - public void setPolicyID(String policyID) { - this.policyID = policyID; - } - - public void setRuleID(String ruleID) { - this.ruleID = ruleID; - } - - public void setConfigType(String configType) { - this.configType = configType; - } - - public void setEditPolicy(Boolean editPolicy) { - this.editPolicy = editPolicy; - } - - public void setVersion(String version) { - this.version = version; - } - - public void setDomainDir(String domain) { - this.domain = domain; - } - - public void setConfigPolicyType(String configPolicyType) { - this.configPolicyType = configPolicyType; - } - - public void setJsonBody(String jsonBody) { - this.jsonBody = jsonBody; - } - - public void setHighestVersion(Integer highestVersion) { - this.highestVersion = highestVersion; - } - - public void setLocation (URI location) { - this.location = location; - } - - public void setDynamicRuleAlgorithmLabels( - List dynamicRuleAlgorithmLabels) { - this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; - } - - public void setDynamicRuleAlgorithmCombo(List dynamicRuleAlgorithmCombo) { - this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; - } - - public void setDynamicRuleAlgorithmField1( - List dynamicRuleAlgorithmField1) { - this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; - } - - public void setDynamicRuleAlgorithmField2( - List dynamicRuleAlgorithmField2) { - this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; - } - - public void setActionPerformer(String actionPerformer) { - this.actionPerformer = actionPerformer; - } - - public void setActionAttribute(String actionAttribute) { - this.actionAttribute = actionAttribute; - } - - public void setActionBody(String actionBody) { - this.actionBody = actionBody; - } - - public void setDropDownMap(Map dropDownMap) { - this.dropDownMap = dropDownMap; - } - - public void setActionDictHeader(String actionDictHeader) { - this.actionDictHeader = actionDictHeader; - } - - public void setActionDictType(String actionDictType) { - this.actionDictType = actionDictType; - } - - public void setActionDictUrl(String actionDictUrl) { - this.actionDictUrl = actionDictUrl; - } - - public void setActionDictMethod(String actionDictMethod) { - this.actionDictMethod = actionDictMethod; - } - - public void setDynamicSettingsMap(Map dynamicSettingsMap) { - this.dynamicSettingsMap = dynamicSettingsMap; - } - - public void setDynamicVariableList(List dynamicVariableList) { - this.dynamicVariableList = dynamicVariableList; - } - - public void setDataTypeList(List dataTypeList) { - this.dataTypeList = dataTypeList; - } - - public void setDraft(Boolean draft) { - this.draft = draft; - } - - public void setOldPolicyFileName(String oldPolicyFileName) { - this.oldPolicyFileName = oldPolicyFileName; - } - - public void setServiceType(String serviceType) { - this.serviceType = serviceType; - } - - public Map getDrlRuleAndUIParams() { - return drlRuleAndUIParams; - } - - public void setDrlRuleAndUIParams(Map drlRuleAndUIParams) { - this.drlRuleAndUIParams = drlRuleAndUIParams; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public void setMsLocation(String msLocation) { - this.msLocation = msLocation; - } - - public void setPriority(String priority) { - this.priority = priority; - } - - public void setDeleteCondition(String deleteCondition) { - this.deleteCondition = deleteCondition; - } - - public void setDictionaryType(String dictionaryType) { - this.dictionaryType = dictionaryType; - } - - public void setDictionary(String dictionary) { - this.dictionary = dictionary; - } - - public void setDictionaryFields(String dictionaryFields) { - this.dictionaryFields = dictionaryFields; - } - - public String getProviderComboBox() { - return providerComboBox; - } - - public void setProviderComboBox(String providerComboBox) { - this.providerComboBox = providerComboBox; - } - - public void setRiskType(String riskType){ - this.riskType = riskType; - } - - public void setRiskLevel(String riskLevel){ - this.riskLevel = riskLevel; - } - - public void setGuard(String guard){ - this.guard = guard; - } - - public void setTTLDate(String ttlDate){ - this.ttlDate = ttlDate; - } - - public String getBrmsController() { - return brmsController; - } - - public void setBrmsController(String brmsController) { - this.brmsController = brmsController; - } - - public ArrayList getBrmsDependency() { - return brmsDependency; - } - - public void setBrmsDependency(ArrayList brmsDependency) { - this.brmsDependency = brmsDependency; - } -} \ No newline at end of file diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDP.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDP.java deleted file mode 100644 index 7e3c1e61a..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDP.java +++ /dev/null @@ -1,222 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.std.pap; - -import java.io.Serializable; -import java.util.Collections; -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -import org.openecomp.policy.xacml.api.pap.EcompPDP; - -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import com.att.research.xacml.api.pap.PDPPIPConfig; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.att.research.xacml.api.pap.PDPStatus; - -public class StdPDP extends StdPDPItemSetChangeNotifier implements EcompPDP, Comparable, Serializable { - private static final long serialVersionUID = 1L; - private static Logger logger = FlexLogger.getLogger(StdPDP.class); - - private String id; - - private String name; - - private String description; - - private Integer jmxport = 0; - - private PDPStatus status = new StdPDPStatus(); - - private Set policies = new HashSet<>(); - - private Set pipConfigs = new HashSet<>(); - - public StdPDP() { - - } - - public StdPDP(String id, Integer jmxport) { - this(id, null, null, jmxport); - } - - public StdPDP(String id, String name, Integer jmxport) { - this(id, name, null, jmxport); - } - - public StdPDP(String id, String name, String description, Integer jmxport) { - this.id = id; - this.name = name; - this.description = description; - if(jmxport != null){ - this.jmxport = jmxport; - } - } - - public StdPDP(String id, Properties properties) { - this(id, 0); - - this.initialize(properties); - } - - public void initialize(Properties properties) { - for (Object key : properties.keySet()) { - if (key.toString().startsWith(this.id + ".")) { - if (logger.isDebugEnabled()) { - logger.debug("Found: " + key); - } - if (key.toString().endsWith(".name")) { - this.name = properties.getProperty(key.toString()); - } else if (key.toString().endsWith(".description")) { - this.description = properties.getProperty(key.toString()); - }else if (key.toString().endsWith(".jmxport")) { - //todo fix this hackjob - if (properties.getProperty(key.toString()) != null && properties.getProperty(key.toString()).trim().length() > 0){ - logger.debug("initialize before: " + this.jmxport); - this.jmxport = Integer.valueOf( properties.getProperty(key.toString())); - logger.debug("initialize after: " + this.jmxport); - }else{ - this.jmxport = 0; - } - } - } - } - } - - @Override - public String getId() { - return this.id; - } - - public void setId(String id) { - this.id=id; - } - - @Override - public String getName() { - return this.name; - } - - @Override - public void setName(String name) { - this.name = name; - this.firePDPChanged(this); - } - - @Override - public String getDescription() { - return this.description; - } - - @Override - public void setDescription(String description) { - this.description = description; - this.firePDPChanged(this); - } - - @Override - public PDPStatus getStatus() { - return this.status; - } - - public void setStatus(PDPStatus status) { - this.status = status; - } - - @Override - public Set getPolicies() { - return Collections.unmodifiableSet(this.policies); - } - - public void setPolicies(Set policies) { - this.policies = policies; - } - - @Override - public Set getPipConfigs() { - return Collections.unmodifiableSet(this.pipConfigs); - } - - public void setPipConfigs(Set pipConfigs) { - this.pipConfigs = pipConfigs; - } - public void setJmxPort(Integer jmxport) { - this.jmxport = jmxport; - } - @Override - public Integer getJmxPort() { - return this.jmxport; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StdPDP other = (StdPDP) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; - } - - @Override - public String toString() { - return "StdPDP [id=" + id + ", name=" + name + ", description=" - + description + ", jmxport=" + jmxport + ", status=" + status + ", policies=" + policies - + ", pipConfigs=" + pipConfigs + "]"; - } - - // - // Comparable interface - // - @Override - public int compareTo(StdPDP o) { - if (o == null) { - return -1; - } - if ( ! (o instanceof StdPDP)) { - return -1; - } - if (((StdPDP)o).name == null) { - return -1; - } - if (name == null) { - return 1; - } - return name.compareTo(((StdPDP)o).name); - } - -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPGroup.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPGroup.java deleted file mode 100644 index b28c04e29..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPGroup.java +++ /dev/null @@ -1,1058 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.std.pap; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Serializable; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Properties; -import java.util.Set; -import java.util.TreeSet; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; -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.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener; - -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.PDPGroupStatus; -import com.att.research.xacml.api.pap.PDPGroupStatus.Status; -import com.att.research.xacml.api.pap.PDPPIPConfig; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.google.common.base.Joiner; -import com.google.common.base.Splitter; -import com.google.common.io.ByteStreams; - -public class StdPDPGroup extends StdPDPItemSetChangeNotifier implements EcompPDPGroup, StdItemSetChangeListener, Comparable, Serializable { - private static final long serialVersionUID = 1L; - private static Log logger = LogFactory.getLog(StdPDPGroup.class); - - private String id; - - private boolean isDefault = false; - - private String name; - - private String description; - - private StdPDPGroupStatus status = new StdPDPGroupStatus(Status.UNKNOWN); - - private Set pdps = new HashSet<>(); - - private Set policies = new HashSet<>(); - - private Set selectedPolicies = new HashSet<>(); - - private Set pipConfigs = new HashSet<>(); - - private String operation; - - @JsonIgnore - private Path directory; - - @JsonIgnore - private Integer jmxport; - - - public StdPDPGroup(String id, Path directory) { - this.id = id; - this.directory = directory; - } - - public StdPDPGroup(String id, boolean isDefault, Path directory) { - this(id, directory); - this.isDefault = isDefault; - } - - public StdPDPGroup(String id, boolean isDefault, String name, String description, Path directory) { - this(id, isDefault, directory); - this.name = name; - // force all policies to have a name - if (name == null) { - this.name = id; - } - this.description = description; - } - - public StdPDPGroup(String id, String name, String description, Path directory) { - this(id, false, name, description, directory); - this.resetStatus(); - } - - public StdPDPGroup(String id, boolean isDefault, Properties properties, Path directory) throws PAPException { - this(id, isDefault, directory); - this.initialize(properties, directory); - this.resetStatus(); - } - - private void initialize(Properties properties, Path directory) throws PAPException { - if (this.id == null || this.id.length() == 0) { - logger.warn("Cannot initialize with a null or zero length id"); - return; - } - // - // Pull the group's properties - // - for (Object key : properties.keySet()) { - if (key.toString().startsWith(this.id + ".")) { - if (key.toString().endsWith(".name")) { - this.name = properties.getProperty(key.toString()); - } else if (key.toString().endsWith(".description")) { - this.description = properties.getProperty(key.toString()); - } else if (key.toString().endsWith(".pdps")) { - String pdpList = properties.getProperty(key.toString()); - if (pdpList != null && pdpList.length() > 0) { - for (String id : Splitter.on(',').omitEmptyStrings().trimResults().split(pdpList)) { - StdPDP pdp = new StdPDP(id, properties); - pdp.addItemSetChangeListener(this); - this.pdps.add(pdp); - } - } - } - } - // force all policies to have a name - if (this.name == null) { - this.name = this.id; - } - } - // - // Validate our directory - // - if (Files.notExists(directory)) { - logger.warn("Group directory does NOT exist: " + directory.toString()); - try { - Files.createDirectory(directory); - this.status.addLoadWarning("Group directory does NOT exist"); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Group directory does NOT exist"); - this.status.addLoadError("Group directory does NOT exist"); - this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); - } - } - // - // Parse policies - // - this.loadPolicies(Paths.get(directory.toString(), "xacml.policy.properties")); - // - // Parse pip config - // - this.loadPIPConfig(Paths.get(directory.toString(), "xacml.pip.properties")); - } - - public void loadPolicies(Path file) throws PAPException { - // - // Read the Groups Policies - // - Properties policyProperties = new Properties(); - if ( ! file.toFile().exists()) { - // need to create the properties file with default values - policyProperties.setProperty(XACMLProperties.PROP_ROOTPOLICIES, ""); - policyProperties.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, ""); - // save properties to file - try (OutputStream os = Files.newOutputStream(file)) { - policyProperties.store(os, ""); - } catch (Exception e) { - throw new PAPException("Failed to create new default policy properties file '" + file +"'"); - } - } else { - // load previously existing file - try { - // - // Load the properties - // - try (InputStream is = Files.newInputStream(file)) { - policyProperties.load(is); - } - // - // Parse the policies - // - this.readPolicyProperties(directory, policyProperties); - } catch (IOException e) { - logger.warn("Failed to load group policy properties file: " + file, e); - this.status.addLoadError("Not policy properties defined"); - this.status.setStatus(Status.LOAD_ERRORS); - throw new PAPException("Failed to load group policy properties file: " + file); - } - } - } - - public void loadPIPConfig(Path file) throws PAPException { - // - // Read the Groups' PIP configuration - // - Properties pipProperties = new Properties(); - if ( ! file.toFile().exists()) { - // need to create the properties file with no values - pipProperties = setPIPProperties(pipProperties); - // save properties to file - try { - try (OutputStream os = Files.newOutputStream(file)) { - pipProperties.store(os, ""); - } - } catch (Exception e) { - throw new PAPException("Failed to create new default pip properties file '" + file +"'"); - } - //Even if we create a new pip file, we still need to parse and load the properties - try{ - this.readPIPProperties(directory, pipProperties); - }catch(Exception e){ - throw new PAPException("Failed to load the new pip properties file"); - } - } else { - try { - // - // Load the properties - // - try (InputStream is = Files.newInputStream(file)) { - pipProperties.load(is); - } - // For all old PIP config's modify to the new PIP Configuration. - // If PIP is empty add the new values and save it. - if(pipProperties.get(XACMLProperties.PROP_PIP_ENGINES).toString().trim().equals("")){ - pipProperties = setPIPProperties(pipProperties); - try (OutputStream os = Files.newOutputStream(file)) { - pipProperties.store(os, ""); - } - } - // - // Parse the pips - // - this.readPIPProperties(directory, pipProperties); - } catch (IOException e) { - logger.warn("Failed to open group PIP Config properties file: " + file, e); - this.status.addLoadError("Not PIP config properties defined"); - this.status.setStatus(Status.LOAD_ERRORS); - throw new PAPException("Failed to load group policy properties file: " + file); - - } - } - } - - public void resetStatus() { -// // -// // If we are updating, don't allow reset -// // -// if (this.status.getStatus() == Status.UPDATING_CONFIGURATION) { -// logger.warn("We are updating, chill."); -// return; -// } -// // -// // Load errors take precedence -// // -// if (this.status.getStatus() == Status.LOAD_ERRORS) { -// logger.warn("We had load errors."); -// return; -// } - // - // Reset our status object - // - this.status.reset(); - // - // Determine our status - // - for (PDP pdp : this.pdps) { - switch (pdp.getStatus().getStatus()) { - case OUT_OF_SYNCH: - this.status.addOutOfSynchPDP(pdp); - break; - case LAST_UPDATE_FAILED: - this.status.addLastUpdateFailedPDP(pdp); - break; - case LOAD_ERRORS: - this.status.addFailedPDP(pdp); - break; - case UPDATING_CONFIGURATION: - this.status.addUpdatingPDP(pdp); - break; - case UP_TO_DATE: - this.status.addInSynchPDP(pdp); - break; - case UNKNOWN: - case CANNOT_CONNECT: - case NO_SUCH_HOST: - default: - this.status.addUnknownPDP(pdp); - break; - } - } - - // priority is worst-cast to best case - if (this.status.getUnknownPDPs().size() > 0) { - this.status.setStatus(Status.UNKNOWN); - } else if (this.status.getFailedPDPs().size() > 0 || this.status.getLastUpdateFailedPDPs().size() > 0) { - this.status.setStatus(Status.LOAD_ERRORS); - } else if (this.status.getOutOfSynchPDPs().size() > 0) { - this.status.setStatus(Status.OUT_OF_SYNCH); - } else if (this.status.getUpdatingPDPs().size() > 0) { - this.status.setStatus(Status.UPDATING_CONFIGURATION); - } else { - this.status.setStatus(Status.OK); - } - } - - @Override - public String getId() { - return this.id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public boolean isDefaultGroup() { - return this.isDefault; - } - - public void setDefaultGroup(boolean isDefault) { - this.isDefault = isDefault; - // - // Cannot fire this because 2 operations have - // to occur: 1) old default=false (don't want to fire) and - // then 2) new default=true (yes fire - but we'll have to do that - // elsewhere. - //this.firePDPGroupChanged(this); - } - - @Override - public String getName() { - return name; - } - - @Override - public void setName(String groupName) { - this.name = groupName; - this.firePDPGroupChanged(this); - } - - @Override - public String getDescription() { - return this.description; - } - - @Override - public void setDescription(String groupDescription) { - this.description = groupDescription; - this.firePDPGroupChanged(this); - } - - public Path getDirectory() { - return this.directory; - } - - public void setDirectory(Path groupDirectory) { - this.directory = groupDirectory; - // this is used only for transmission on the RESTful interface, so no need to fire group changed? - } - - @Override - public PDPGroupStatus getStatus(){ - return this.status; - } - - @Override - public Set getSelectedPolicies() { - return this.selectedPolicies; - } - - @Override - public String getOperation() { - return this.operation; - } - - @Override - public Set getPdps() { - return Collections.unmodifiableSet(pdps); - } - - public void setEcompPdps(Set pdps) { - this.pdps = pdps; - } - - public Set getEcompPdps(){ - return Collections.unmodifiableSet(pdps); - } - - public boolean addPDP(EcompPDP pdp) { - return this.pdps.add(pdp); - } - - public boolean removePDP(PDP pdp) { - return this.pdps.remove(pdp); - } - - @Override - public Set getPolicies() { - return Collections.unmodifiableSet(this.policies); - } - - @Override - public PDPPolicy getPolicy(String id) { - for (PDPPolicy policy : this.policies) { - if (policy.getId().equals(id)) { - return policy; - } - } - return null; - } - - public Properties getPolicyProperties() - { - Properties properties = new Properties(){ - private static final long serialVersionUID = 1L; - // For Debugging it is helpful for the file to be in a sorted order, - // any by returning the keys in the natural Alpha order for strings we get close enough. - // TreeSet is sorted, and this just overrides the normal Properties method to get the keys. - @Override - public synchronized Enumeration keys() { - return Collections.enumeration(new TreeSet(super.keySet())); - } - };; - List roots = new ArrayList(); - List refs = new ArrayList(); - - for (PDPPolicy policy : this.policies) { - // for all policies need to tell PDP the "name", which is the base name for the file id - if (policy.getName() != null) { - properties.setProperty(policy.getId() + ".name", policy.getName()); - } - // put the policy on the correct list - if (policy.isRoot()) { - roots.add(policy.getId()); - } else { - refs.add(policy.getId()); - } - } - - properties.setProperty(XACMLProperties.PROP_ROOTPOLICIES, Joiner.on(',').join(roots)); - properties.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, Joiner.on(',').join(refs)); - - return properties; - } - - public PDPPolicy publishPolicy(String id, String name, boolean isRoot, InputStream policy) throws PAPException { - // - // Does it exist already? - // - if (this.getPolicy(id) != null) { - throw new PAPException("Policy with id " + id + " already exists - unpublish it first."); - } - Path tempFile = null; - try { - // - // Copy the policy over - // - tempFile = Files.createFile(Paths.get(this.directory.toAbsolutePath().toString(), id)); - long num; - try (OutputStream os = Files.newOutputStream(tempFile)) { - num = ByteStreams.copy(policy, os); - } - logger.info("Copied " + num + " bytes for policy " + name); - - StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, isRoot, name, tempFile.toUri()); - if (tempRootPolicy.isValid() == false) { - try { - Files.delete(tempFile); - } catch(Exception ee) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, "StdPDPGroup", "Policy was invalid, could NOT delete it."); - } - throw new PAPException("Policy is invalid"); - } - // - // Add it in - // - this.policies.add(tempRootPolicy); - // - // We are changed - // - this.firePDPGroupChanged(this); - // - // Return our new object. - // - return tempRootPolicy; - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdPDPGroup", "Failed to publishPolicy"); - } - return null; - } - - /** - * Copy one policy file into the Group's directory but do not change the configuration. - * This is one part of a multi-step process of publishing policies. - * There may be multiple changes in the group (adding multiple policies, deleting policies, changine root<->referenced) - * that must be done all at once, so we just copy the file in preparation for a later "update whole group" operation. - * - * @param id - * @param name - * @param isRoot - * @param policy - * @return - * @throws PAPException - */ - public void copyPolicyToFile(String id, InputStream policy) throws PAPException { - try { - // - // Copy the policy over - // - long num; - Path policyFilePath = Paths.get(this.directory.toAbsolutePath().toString(), id); - - Path policyFile; - if (Files.exists(policyFilePath)) { - policyFile = policyFilePath; - } else { - policyFile = Files.createFile(policyFilePath); - } - - try (OutputStream os = Files.newOutputStream(policyFile)) { - num = ByteStreams.copy(policy, os); - } - - logger.info("Copied " + num + " bytes for policy " + name); - - for (PDPPolicy p : policies) { - if (p.getId().equals(id)) { - // we just re-copied/refreshed/updated the policy file for a policy that already exists in this group - logger.info("Policy '" + id + "' already exists in group '" + getId() + "'"); - return; - } - } - - // policy is new to this group - StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, true, name, policyFile.toUri()); - if (tempRootPolicy.isValid() == false) { - try { - Files.delete(policyFile); - } catch(Exception ee) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, "StdPDPGroup", "Policy was invalid, could NOT delete it."); - } - throw new PAPException("Policy is invalid"); - } - // - // Add it in - // - this.policies.add(tempRootPolicy); - // - // We are changed - // - this.firePDPGroupChanged(this); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to copyPolicyToFile"); - throw new PAPException("Failed to copy policy to file: " + e); - } - return; - } - - /** - * Policy Engine API Copy one policy file into the Group's directory but do not change the configuration. - * - * @param id - * @param name - * @param policy - * @return - * @throws PAPException - */ - public void copyPolicyToFile(String id, String name, InputStream policy) throws PAPException { - try { - // - // Copy the policy over - // - long num; - Path policyFilePath = Paths.get(this.directory.toAbsolutePath().toString(), id); - - Path policyFile; - if (Files.exists(policyFilePath)) { - policyFile = policyFilePath; - } else { - policyFile = Files.createFile(policyFilePath); - } - - try (OutputStream os = Files.newOutputStream(policyFile)) { - num = ByteStreams.copy(policy, os); - } - - logger.info("Copied " + num + " bytes for policy " + name); - for (PDPPolicy p : policies) { - if (p.getId().equals(id)) { - // we just re-copied/refreshed/updated the policy file for a policy that already exists in this group - logger.info("Policy '" + id + "' already exists in group '" + getId() + "'"); - return; - } - } - - // policy is new to this group - StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, true, name, policyFile.toUri()); - if (tempRootPolicy.isValid() == false) { - try { - Files.delete(policyFile); - } catch(Exception ee) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, "StdPDPGroup", "Policy was invalid, could NOT delete it."); - } - throw new PAPException("Policy is invalid"); - } - // - // Add it in - // - this.policies.add(tempRootPolicy); - // - // We are changed - // - this.firePDPGroupChanged(this); - - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to copyPolicyToFile"); - throw new PAPException("Failed to copy policy to file: " + e); - } - return; - } - - public boolean removePolicyFromGroup(PDPPolicy policy) { - PolicyLogger.info("policy: " + policy.getId()); - PolicyLogger.info("Policy ID:" + policy.getPolicyId()); - PolicyLogger.info("Policy Version: " + policy.getVersion()); - PolicyLogger.info("StdPDPPolicy Class cast: " + this.getPolicy(policy.getId()).toString()); - StdPDPPolicy currentPolicy = (StdPDPPolicy) this.getPolicy(policy.getId()); - if (currentPolicy == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Policy " + policy.getId() + " does not exist."); - return false; - } - try { - // - // Remove it from our list - // - this.policies.remove(currentPolicy); - // - // We are changed - // - this.firePDPGroupChanged(this); - return true; - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to delete policy"); - } - return false; - } - - public boolean removePolicy(PDPPolicy policy) { - StdPDPPolicy currentPolicy = (StdPDPPolicy) this.getPolicy(policy.getId()); - if (currentPolicy == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Policy " + policy.getId() + " does not exist."); - return false; - } - try { - // - // Delete it on disk - // - Files.delete(Paths.get(currentPolicy.getLocation())); - // - // Remove it from our list - // - this.policies.remove(currentPolicy); - // - // We are changed - // - this.firePDPGroupChanged(this); - return true; - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to delete policy " + policy); - } - return false; - } - - @Override - public Set getPipConfigs() { - return Collections.unmodifiableSet(this.pipConfigs); - } - - @Override - public PDPPIPConfig getPipConfig(String id) { - for (PDPPIPConfig config : this.pipConfigs) { - if (config.getId().equals(id)) { - return config; - } - } - return null; - } - - public void setPipConfigs(Set pipConfigs) { - this.pipConfigs = pipConfigs; - this.firePDPGroupChanged(this); - } - - public void removeAllPIPConfigs() { - this.pipConfigs.clear(); - this.firePDPGroupChanged(this); - } - - public Properties getPipConfigProperties() { - Properties properties = new Properties(); - List configs = new ArrayList(); - - for (PDPPIPConfig config : this.pipConfigs) { - configs.add(config.getId()); - properties.putAll(config.getConfiguration()); - } - - properties.setProperty(XACMLProperties.PROP_PIP_ENGINES, Joiner.on(',').join(configs)); - - return properties; - } - - @Override - public void repair() { - // - // Reset the status object - // - this.status.reset(); - // - // Validate our directory - // - boolean fire = false; - if (Files.notExists(directory)) { - logger.warn("Group directory does NOT exist: " + directory.toString()); - try { - Files.createDirectory(directory); - fire = true; - this.status.addLoadWarning("Created missing group directory"); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to create missing Group directory."); - this.status.addLoadError("Failed to create missing Group directory."); - this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); - } - } - // - // Validate our PIP config file - // - Path pipPropertiesFile = Paths.get(directory.toString(), "xacml.pip.properties"); - if (Files.notExists(pipPropertiesFile)) { - try { - Files.createFile(pipPropertiesFile); - fire = true; - this.status.addLoadWarning("Created missing PIP properties file"); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to create missing PIP properties file"); - this.status.addLoadError("Failed to create missing PIP properties file"); - this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); - } - } - // - // Valid our policy properties file - // - Path policyPropertiesFile = Paths.get(directory.toString(), "xacml.policy.properties"); - if (Files.notExists(policyPropertiesFile)) { - try { - Files.createFile(policyPropertiesFile); - fire = true; - this.status.addLoadWarning("Created missing Policy properties file"); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to create missing Policy properties file"); - this.status.addLoadError("Failed to create missing Policy properties file"); - this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); - } - } - this.resetStatus(); - if (fire) { - this.fireChanged(); - } - } - - private void readPolicyProperties(Path directory, Properties properties) { - // - // There are 2 property values that hold policies, root and referenced - // - String[] lists = new String[2]; - lists[0] = properties.getProperty(XACMLProperties.PROP_ROOTPOLICIES); - lists[1] = properties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); - // - // Iterate each policy list - // - boolean isRoot = true; - for (String list : lists) { - // - // Was there actually a property? - // - if (list == null || list.length() == 0) { - isRoot = false; - continue; - } - // - // Parse it out - // - Iterable policyList = Splitter.on(',').trimResults().omitEmptyStrings().split(list); - // - // Was there actually a list - // - if (policyList == null) { - isRoot = false; - continue; - } - for (String id : policyList) { - // - // Construct the policy filename - // - Path policyPath = Paths.get(directory.toString(), id ); - // - // Create the Policy Object - // - StdPDPPolicy policy; - try { - policy = new StdPDPPolicy(id, isRoot, policyPath.toUri(), properties); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to create policy object"); - policy = null; - } - // - // Is it valid? - // - if (policy != null && policy.isValid()) { - this.policies.add(policy); - this.status.addLoadedPolicy(policy); - } else { - this.status.addFailedPolicy(policy); - this.status.setStatus(Status.LOAD_ERRORS); - } - // force all policies to have a name - if (policy!=null && policy.getName() == null) { - policy.setName(policy.getId()); - } - } - isRoot = false; - } - } - - private void readPIPProperties(Path directory, Properties properties) { - String list = properties.getProperty(XACMLProperties.PROP_PIP_ENGINES); - if (list == null || list.length() == 0) { - return; - } - for (String id : list.split("[,]")) { - StdPDPPIPConfig config = new StdPDPPIPConfig(id, properties); - if (config.isConfigured()) { - this.pipConfigs.add(config); - this.status.addLoadedPipConfig(config); - } else { - this.status.addFailedPipConfig(config); - this.status.setStatus(Status.LOAD_ERRORS); - } - } - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StdPDPGroup other = (StdPDPGroup) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - return true; - } - - @Override - public String toString() { - return "StdPDPGroup [id=" + id + ", isDefault=" + isDefault + ", name=" - + name + ", description=" + description + ", status=" + status - + ", pdps=" + pdps + ", policies=" + policies + ", pipConfigs=" - + pipConfigs + ", directory=" + directory + ",selectedPolicies=" - + selectedPolicies + ",operation=" + operation + "]"; - } - - @Override - public void changed() { - - // save the (changed) properties - try { - saveGroupConfiguration(); - } catch (PAPException | IOException e) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdPDPGroup", "Unable to save group configuration change"); - // don't notify other things of change if we cannot save it??? - return; - } - - this.firePDPGroupChanged(this); - - } - - @Override - public void groupChanged(EcompPDPGroup group) { - this.changed(); - } - - @Override - public void pdpChanged(EcompPDP pdp) { - // - // If one of the group's PDP's changed, then the group changed - // - this.changed(); - } - - - // - // Methods needed for JSON deserialization - // - public StdPDPGroup() { - - } - - public StdPDPGroup(EcompPDPGroup group) { - this.id = group.getId(); - this.name = group.getName(); - this.description = group.getDescription(); - this.isDefault = group.isDefaultGroup(); - this.pdps = group.getEcompPdps(); - this.policies = group.getPolicies(); - this.pipConfigs = group.getPipConfigs(); - } - - public boolean isDefault() { - return isDefault; - } - public void setDefault(boolean isDefault) { - this.isDefault = isDefault; - } - public void setStatus(PDPGroupStatus status) { - this.status = new StdPDPGroupStatus(status); - } - public void setPolicies(Set policies) { - this.policies = policies; - } - public void setSelectedPolicies(Set selectedPolicies) { - this.selectedPolicies = selectedPolicies; - } - public void setOperation(String operation) { - this.operation = operation; - } - - public void saveGroupConfiguration() throws PAPException, IOException { - - // First save the Policy properties - - // save the lists of policies - Properties policyProperties = this.getPolicyProperties(); - - // save info about each policy - for (PDPPolicy policy : this.policies){ - policyProperties.put(policy.getId() + ".name", policy.getName()); - } - - // - // Now we can save the file - // - Path file = Paths.get(this.directory.toString(), "xacml.policy.properties"); - try (OutputStream os = Files.newOutputStream(file)) { - policyProperties.store(os, ""); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "STdPDPGroup", "Group Policies Config save failed"); - throw new PAPException("Failed to save policy properties file '" + file +"'"); - } - - - // Now save the PIP Config properties - Properties pipProperties = this.getPipConfigProperties(); - - // - // Now we can save the file - // - file = Paths.get(this.directory.toString(), "xacml.pip.properties"); - try (OutputStream os = Files.newOutputStream(file)) { - pipProperties.store(os, ""); - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Group PIP Config save failed"); - throw new PAPException("Failed to save pip properties file '" + file +"'"); - } - } - - // - // Comparable Interface - // - @Override - public int compareTo(Object arg0) { - if (arg0 == null) { - return -1; - } - if ( ! (arg0 instanceof StdPDPGroup)) { - return -1; - } - if (((StdPDPGroup)arg0).name == null) { - return -1; - } - if (name == null) { - return 1; - } - - return name.compareTo(((StdPDPGroup)arg0).name); - } - - //Adding Default PIP engine(s) while Loading initially. We don't want - // Programmer intervention with the PIP engines. - private Properties setPIPProperties(Properties props){ - props.setProperty("AAF.name", "AAFEngine"); - props.setProperty("AAF.description", "AAFEngine to communicate with AAF to take decisions"); - props.setProperty("AAF.classname","org.openecomp.policy.xacml.std.pip.engines.aaf.AAFEngine"); - props.setProperty(XACMLProperties.PROP_PIP_ENGINES, "AAF"); - // read from PIP properties file. - Path file = Paths.get(StdEngine.pipPropertyFile); - if (!Files.notExists(file)) { - InputStream in; - Properties prop = new Properties(); - try { - in = new FileInputStream(file.toFile()); - prop.load(in); - } catch (IOException e) { - PolicyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "can not load the pip properties from file" +e); - } - props = prop; - } - return props; - } - - -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPGroupStatus.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPGroupStatus.java deleted file mode 100644 index 6b248bf69..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPGroupStatus.java +++ /dev/null @@ -1,405 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.std.pap; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import com.att.research.xacml.api.pap.PDP; -import com.att.research.xacml.api.pap.PDPGroupStatus; -import com.att.research.xacml.api.pap.PDPPIPConfig; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.fasterxml.jackson.annotation.JsonIgnore; - -public class StdPDPGroupStatus implements PDPGroupStatus { - - private Status status = Status.UNKNOWN; - - private Set loadErrors = new HashSet<>(); - - private Set loadWarnings = new HashSet<>(); - - private Set loadedPolicies = new HashSet<>(); - - private Set failedPolicies = new HashSet<>(); - - private Set loadedPIPConfigs = new HashSet<>(); - - private Set failedPIPConfigs = new HashSet<>(); - - private Set inSynchPDPs = new HashSet<>(); - - private Set outOfSynchPDPs = new HashSet<>(); - - private Set failedPDPs = new HashSet<>(); - - private Set updatingPDPs = new HashSet<>(); - - private Set lastUpdateFailedPDPs = new HashSet<>(); - - private Set unknownPDPs = new HashSet<>(); - - - // Constructor needed for JSON deserialization - public StdPDPGroupStatus() { - - } - - public StdPDPGroupStatus(Status status) { - this.status = status; - } - - public StdPDPGroupStatus(PDPGroupStatus stat) { - this.status = stat.getStatus(); - this.failedPDPs.clear(); this.failedPDPs.addAll(stat.getFailedPDPs()); - this.failedPIPConfigs.clear(); this.failedPIPConfigs.addAll(stat.getFailedPipConfigs()); - this.failedPolicies.clear(); this.failedPolicies.addAll(stat.getFailedPolicies()); - this.inSynchPDPs.clear(); this.inSynchPDPs.addAll(stat.getInSynchPDPs()); - this.lastUpdateFailedPDPs.clear(); this.lastUpdateFailedPDPs.addAll(stat.getLastUpdateFailedPDPs()); - this.loadedPIPConfigs.clear(); this.loadedPIPConfigs.addAll(stat.getLoadedPipConfigs()); - this.loadedPolicies.clear(); this.loadedPolicies.addAll(stat.getLoadedPolicies()); - this.loadErrors.clear(); this.loadErrors.addAll(stat.getLoadErrors()); - this.loadWarnings.clear(); this.loadWarnings.addAll(stat.getLoadWarnings()); - this.outOfSynchPDPs.clear(); this.outOfSynchPDPs.addAll(stat.getOutOfSynchPDPs()); - this.unknownPDPs.clear(); this.unknownPDPs.addAll(stat.getUpdatingPDPs()); - this.updatingPDPs.clear(); this.updatingPDPs.addAll(stat.getUpdatingPDPs()); - } - - public Set getLoadedPIPConfigs() { - return loadedPIPConfigs; - } - public void setLoadedPIPConfigs(Set loadedPIPConfigs) { - this.loadedPIPConfigs = loadedPIPConfigs; - } - public Set getFailedPIPConfigs() { - return failedPIPConfigs; - } - public void setFailedPIPConfigs(Set failedPIPConfigs) { - this.failedPIPConfigs = failedPIPConfigs; - } - public Set getUnknownPDPs() { - return unknownPDPs; - } - public void setUnknownPDPs(Set unknownPDPs) { - this.unknownPDPs = unknownPDPs; - } - public void setLoadErrors(Set loadErrors) { - this.loadErrors = loadErrors; - } - public void setLoadWarnings(Set loadWarnings) { - this.loadWarnings = loadWarnings; - } - public void setLoadedPolicies(Set loadedPolicies) { - this.loadedPolicies = loadedPolicies; - } - public void setFailedPolicies(Set failedPolicies) { - this.failedPolicies = failedPolicies; - } - public void setInSynchPDPs(Set inSynchPDPs) { - this.inSynchPDPs = inSynchPDPs; - } - public void setOutOfSynchPDPs(Set outOfSynchPDPs) { - this.outOfSynchPDPs = outOfSynchPDPs; - } - public void setFailedPDPs(Set failedPDPs) { - this.failedPDPs = failedPDPs; - } - public void setUpdatingPDPs(Set updatingPDPs) { - this.updatingPDPs = updatingPDPs; - } - public void setLastUpdateFailedPDPs(Set lastUpdateFailedPDPs) { - this.lastUpdateFailedPDPs = lastUpdateFailedPDPs; - } - - - @Override - public Status getStatus() { - return status; - } - - public void setStatus(Status status) { - this.status = status; - } - - @Override - public Set getLoadErrors() { - return Collections.unmodifiableSet(this.loadErrors); - } - - public void addLoadError(String error) { - this.loadErrors.add(error); - } - - @Override - public Set getLoadWarnings() { - return Collections.unmodifiableSet(this.loadWarnings); - } - - public void addLoadWarning(String warning) { - this.loadWarnings.add(warning); - } - - @Override - public Set getLoadedPolicies() { - return Collections.unmodifiableSet(this.loadedPolicies); - } - - public void addLoadedPolicy(PDPPolicy policy) { - this.loadedPolicies.add(policy); - } - - @Override - public Set getFailedPolicies() { - return Collections.unmodifiableSet(this.failedPolicies); - } - - public void addFailedPolicy(PDPPolicy policy) { - this.failedPolicies.add(policy); - } - - @Override - public boolean policiesOK() { - if (this.failedPolicies.size() > 0) { - return false; - } - return true; - } - - @Override - public Set getLoadedPipConfigs() { - return Collections.unmodifiableSet(this.loadedPIPConfigs); - } - - public void addLoadedPipConfig(PDPPIPConfig config) { - this.loadedPIPConfigs.add(config); - } - - @Override - public Set getFailedPipConfigs() { - return Collections.unmodifiableSet(this.failedPIPConfigs); - } - - public void addFailedPipConfig(PDPPIPConfig config) { - this.failedPIPConfigs.add(config); - } - - @Override - public boolean pipConfigOK() { - if (this.failedPIPConfigs.size() > 0) { - return false; - } - return true; - } - - @Override - public Set getInSynchPDPs() { - return Collections.unmodifiableSet(this.inSynchPDPs); - } - - public void addInSynchPDP(PDP pdp) { - this.inSynchPDPs.add(pdp); - } - - @Override - public Set getOutOfSynchPDPs() { - return Collections.unmodifiableSet(this.outOfSynchPDPs); - } - - public void addOutOfSynchPDP(PDP pdp) { - this.outOfSynchPDPs.add(pdp); - } - - @Override - public Set getFailedPDPs() { - return Collections.unmodifiableSet(this.failedPDPs); - } - - public void addFailedPDP(PDP pdp) { - this.failedPDPs.add(pdp); - } - - @Override - public Set getUpdatingPDPs() { - return Collections.unmodifiableSet(this.updatingPDPs); - } - - public void addUpdatingPDP(PDP pdp) { - this.updatingPDPs.add(pdp); - } - - @Override - public Set getLastUpdateFailedPDPs() { - return Collections.unmodifiableSet(this.lastUpdateFailedPDPs); - } - - public void addLastUpdateFailedPDP(PDP pdp) { - this.lastUpdateFailedPDPs.add(pdp); - } - - @Override - @JsonIgnore - public Set getUnknownStatusPDPs() { - return Collections.unmodifiableSet(this.unknownPDPs); - } - - public void addUnknownPDP(PDP pdp) { - this.unknownPDPs.add(pdp); - } - - @Override - public boolean pdpsOK() { - if (this.outOfSynchPDPs.size() > 0) { - return false; - } - if (this.failedPDPs.size() > 0) { - return false; - } - if (this.lastUpdateFailedPDPs.size() > 0) { - return false; - } - if (this.unknownPDPs.size() > 0) { - return false; - } - return true; - } - - @Override - @JsonIgnore - public boolean isGroupOk() { - if (this.policiesOK() == false) { - return false; - } - if (this.pipConfigOK() == false) { - return false; - } - if (this.pdpsOK() == false) { - return false; - } - if (this.loadErrors.isEmpty() == false) { - return false; - } - return (this.status == Status.OK); - } - - public void reset() { - this.status = Status.OK; - - this.loadErrors.clear(); - this.loadWarnings.clear(); - this.loadedPolicies.clear(); - this.failedPolicies.clear(); - this.loadedPIPConfigs.clear(); - this.failedPIPConfigs.clear(); - this.inSynchPDPs.clear(); - this.outOfSynchPDPs.clear(); - this.failedPDPs.clear(); - this.updatingPDPs.clear(); - this.lastUpdateFailedPDPs.clear(); - this.unknownPDPs.clear(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + (failedPDPs.hashCode()); - result = prime - * result - + (failedPIPConfigs.hashCode()); - result = prime * result - + (failedPolicies.hashCode()); - result = prime * result - + (inSynchPDPs.hashCode()); - result = prime - * result - + (lastUpdateFailedPDPs.hashCode()); - result = prime * result - + (loadErrors.hashCode()); - result = prime * result - + (loadWarnings.hashCode()); - result = prime - * result - + (loadedPIPConfigs.hashCode()); - result = prime * result - + (loadedPolicies.hashCode()); - result = prime * result - + (outOfSynchPDPs.hashCode()); - result = prime * result + (status.hashCode()); - result = prime * result - + (unknownPDPs.hashCode()); - result = prime * result - + (updatingPDPs.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StdPDPGroupStatus other = (StdPDPGroupStatus) obj; - if (!failedPDPs.equals(other.failedPDPs)) - return false; - if (!failedPIPConfigs.equals(other.failedPIPConfigs)) - return false; - if (!failedPolicies.equals(other.failedPolicies)) - return false; - if (!inSynchPDPs.equals(other.inSynchPDPs)) - return false; - if (!lastUpdateFailedPDPs.equals(other.lastUpdateFailedPDPs)) - return false; - if (!loadErrors.equals(other.loadErrors)) - return false; - if (!loadWarnings.equals(other.loadWarnings)) - return false; - if (!loadedPIPConfigs.equals(other.loadedPIPConfigs)) - return false; - if (!loadedPolicies.equals(other.loadedPolicies)) - return false; - if (!outOfSynchPDPs.equals(other.outOfSynchPDPs)) - return false; - if (status != other.status) - return false; - if (!unknownPDPs.equals(other.unknownPDPs)) - return false; - if (!updatingPDPs.equals(other.updatingPDPs)) - return false; - return true; - } - - @Override - public String toString() { - return "StdPDPGroupStatus [status=" + status + ", loadErrors=" - + loadErrors + ", loadWarnings=" + loadWarnings - + ", loadedPolicies=" + loadedPolicies + ", failedPolicies=" - + failedPolicies + ", loadedPIPConfigs=" + loadedPIPConfigs - + ", failedPIPConfigs=" + failedPIPConfigs + ", inSynchPDPs=" - + inSynchPDPs + ", outOfSynchPDPs=" + outOfSynchPDPs - + ", failedPDPs=" + failedPDPs + ", updatingPDPs=" - + updatingPDPs + ", lastUpdateFailedPDPs=" - + lastUpdateFailedPDPs + ", unknownPDPs=" + unknownPDPs + "]"; - } - -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java deleted file mode 100644 index a197d5f3d..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.std.pap; - -import java.util.Collection; -import java.util.LinkedList; - -import org.openecomp.policy.xacml.api.pap.EcompPDP; -import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; - -public class StdPDPItemSetChangeNotifier { - - private Collection listeners = null; - - public interface StdItemSetChangeListener { - - public void changed(); - - public void groupChanged(EcompPDPGroup group); - - public void pdpChanged(EcompPDP pdp); - - } - - public void addItemSetChangeListener(StdItemSetChangeListener listener) { - if (this.listeners == null) { - this.listeners = new LinkedList(); - } - this.listeners.add(listener); - } - - public void removeItemSetChangeListener(StdItemSetChangeListener listener) { - if (this.listeners != null) { - this.listeners.remove(listener); - } - } - - public void fireChanged() { - if (this.listeners == null) { - return; - } - for (StdItemSetChangeListener l : this.listeners) { - l.changed(); - } - } - - public void firePDPGroupChanged(EcompPDPGroup group) { - if (this.listeners == null) { - return; - } - for (StdItemSetChangeListener l : this.listeners) { - l.groupChanged(group); - } - } - - public void firePDPChanged(EcompPDP pdp) { - if (this.listeners == null) { - return; - } - for (StdItemSetChangeListener l : this.listeners) { - l.pdpChanged(pdp); - } - } -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPPIPConfig.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPPIPConfig.java deleted file mode 100644 index 3a609fe07..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPPIPConfig.java +++ /dev/null @@ -1,216 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.std.pap; - -import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import com.att.research.xacml.api.pap.PDPPIPConfig; -import com.fasterxml.jackson.annotation.JsonIgnore; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -public class StdPDPPIPConfig implements PDPPIPConfig, Serializable { - private static final long serialVersionUID = 1L; - private static Logger logger = FlexLogger.getLogger(StdPDPPIPConfig.class); - - private String id; - - private String name; - - private String description; - - private String classname; - - private Map config = new HashMap<>(); - - public StdPDPPIPConfig() { - - } - - public StdPDPPIPConfig(String id) { - this.id = id; - } - - public StdPDPPIPConfig(String id, String name, String description) { - this(id); - this.name = name; - this.description = description; - } - - public StdPDPPIPConfig(String id, Properties properties) { - this(id); - if ( ! this.initialize(properties) ) { - throw new IllegalArgumentException("PIP Engine '" + id + "' has no classname property in config"); - } - } - - public boolean initialize(Properties properties) { - boolean classnameSeen = false; - for (Object key : properties.keySet()) { - if (key.toString().startsWith(this.id + ".")) { - if (logger.isDebugEnabled()) { - logger.debug("Found: " + key); - } - if (key.toString().equals(this.id + ".name")) { - this.name = properties.getProperty(key.toString()); - } else if (key.toString().equals(this.id + ".description")) { - this.description = properties.getProperty(key.toString()); - } else if (key.toString().equals(this.id + ".classname")) { - this.classname = properties.getProperty(key.toString()); - classnameSeen = true; - } - // all properties, including the special ones located above, are included in the properties list - this.config.put(key.toString(), properties.getProperty(key.toString())); - } - } - return classnameSeen; - } - - @Override - public String getId() { - return this.id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Override - public String getClassname() { - return classname; - } - - public void setClassname(String classname) { - this.classname = classname; - } - - @Override - @JsonIgnore - public Map getConfiguration() { - return Collections.unmodifiableMap(this.config); - } - - public void setValues(Map config) { - this.config = config; - } - - @Override - @JsonIgnore - public boolean isConfigured() { - // - // Also include this in the JSON I/O if it is a data field rather than calculated - // - return true; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((classname == null) ? 0 : classname.hashCode()); - result = prime * result + ((config == null) ? 0 : config.hashCode()); - result = prime * result - + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StdPDPPIPConfig other = (StdPDPPIPConfig) obj; - if (classname == null) { - if (other.classname != null) - return false; - } else if (!classname.equals(other.classname)) - return false; - if (config == null) { - if (other.config != null) - return false; - } else if (!config.equals(other.config)) - return false; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } - - @Override - public String toString() { - return "StdPDPPIPConfig [id=" + id + ", name=" + name - + ", description=" + description + ", classname=" + classname - + ", config=" + config + "]"; - } - - - - // - // Methods needed for JSON serialization/deserialization - // - - public Map getConfig() { - return config; - } - public void setConfig(Map config) { - this.config = config; - } - -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPPolicy.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPPolicy.java deleted file mode 100644 index 0300a3d06..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPPolicy.java +++ /dev/null @@ -1,366 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.std.pap; - -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.Serializable; -import java.net.URI; -import java.net.URL; -import java.util.ArrayList; -import java.util.Properties; - -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.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.xacml.util.XACMLPolicyScanner; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.google.common.base.Splitter; -import com.google.common.collect.Lists; - - -public class StdPDPPolicy implements PDPPolicy, Serializable { - private static final long serialVersionUID = 1L; - private static Log logger = LogFactory.getLog(StdPDPPolicy.class); - - private String id = null; - - private String name = null; - - private String policyId = null; - - private String description = null; - - private int[] version = null; - - private boolean isRoot = false; - - private boolean isValid = false; - - private URI location = null; - - - public StdPDPPolicy(String id, boolean isRoot) { - this.id = id; - this.isRoot = isRoot; - } - - public StdPDPPolicy(String id, boolean isRoot, String name) { - this(id, isRoot); - this.name = name; - } - - - public StdPDPPolicy(String id, boolean isRoot, String name, URI location) throws IOException { - this(id, isRoot); - this.name = name; - this.location = location; - - // - // Read the policy data - // - String theID = this.readPolicyData(); - - if (this.id == null) { - logger.debug("id is null so we are calling readPolicyData() to get the policyID"); - this.id = theID; - } - - logger.debug("The final outcome of the constructor returned the following: id = " + id + - ", location = " + location + ", name = " + name); - - } - - public StdPDPPolicy(String id, boolean isRoot, String name, URI location, boolean isValid, String policyId, - String description, String version) throws IOException { - this(id, isRoot); - this.name = name; - this.location = location; - this.policyId = policyId; - this.description = description; - this.version = versionStringToArray(version); - this.isValid = isValid; - - logger.debug("The final outcome of the constructor returned the following: id = " + id + - ", location = " + location + ", name = " + name + ", policyId = " + policyId + - ", description = " + description + ", Version = " + version); - - } - - public StdPDPPolicy(String id, boolean isRoot, String name, URI location, boolean isFromAPI) throws IOException { - this(id, isRoot); - this.name = name; - this.location = location; - this.isValid = isFromAPI; - - logger.debug("The final outcome of the constructor returned the following: id = " + id + - ", location = " + location + ", name = " + name); - - } - - public StdPDPPolicy(String id, boolean isRoot, URI location, Properties properties) throws IOException { - this(id, isRoot); - this.location = location; - // - // Read the policy data - // - this.readPolicyData(); - // - // See if there's a name - // - for (Object key : properties.keySet()) { - if (key.toString().equals(id + ".name")) { - this.name = properties.getProperty(key.toString()); - break; - } - } - } - - - private String readPolicyData() throws IOException { - // - // Extract XACML policy information - // - URL url = this.location.toURL(); - Object rootElement = XACMLPolicyScanner.readPolicy(url.openStream()); - if (rootElement == null || - ( - ! (rootElement instanceof PolicySetType) && - ! (rootElement instanceof PolicyType) - ) ) { - logger.warn("No root policy element in URI: " + this.location.toString() + " : " + rootElement); - this.isValid = false; - } else { - this.version = versionStringToArray(XACMLPolicyScanner.getVersion(rootElement)); - if (rootElement instanceof PolicySetType) { - this.policyId = ((PolicySetType)rootElement).getPolicySetId(); - this.description = ((PolicySetType)rootElement).getDescription(); - this.isValid = true; - this.version = versionStringToArray(((PolicySetType)rootElement).getVersion()); - } else if (rootElement instanceof PolicyType) { - this.policyId = ((PolicyType)rootElement).getPolicyId(); - this.description = ((PolicyType)rootElement).getDescription(); - this.version = versionStringToArray(((PolicyType)rootElement).getVersion()); - this.isValid = true; - } else { - PolicyLogger.error("Unknown root element: " + rootElement.getClass().getCanonicalName()); - } - } - if (this.policyId != null) { - ArrayList foo = Lists.newArrayList(Splitter.on(':').split(this.policyId)); - if (foo.isEmpty() == false) { - return foo.get(foo.size() - 1); - } - } - return null; - } - - @Override - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - @Override - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public String getPolicyId() { - return this.policyId; - } - - @Override - public String getDescription() { - return this.description; - } - - @Override - public String getVersion() { - return versionArrayToString(this.version); - } - - @Override - @JsonIgnore - public int[] getVersionInts() { - return version; - } - - @Override - public boolean isRoot() { - return this.isRoot; - } - - @Override - public boolean isValid() - { - return this.isValid; - } - - @Override - @JsonIgnore - public InputStream getStream() throws PAPException, IOException { - try { - if (this.location != null) { - URL url = this.location.toURL(); - return url.openStream(); - } - return null; - } catch (FileNotFoundException e) { - throw new PAPException(e); - } - } - - @Override - public URI getLocation() throws PAPException { - return this.location; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result - + ((policyId == null) ? 0 : policyId.hashCode()); - result = prime * result; - if (version != null) { - for (int i = 0; i < version.length; i++) { - result += version[i]; - } - } - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StdPDPPolicy other = (StdPDPPolicy) obj; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (policyId == null) { - if (other.policyId != null) - return false; - } else if (!policyId.equals(other.policyId)) - return false; - if (version != other.version) - return false; - return true; - } - - @Override - public String toString() { - return "StdPDPPolicy [id=" + id + ", name=" + name + ", policyId=" - + policyId + ", description=" + description + ", version=" - + this.getVersion() + ", isRoot=" + isRoot + ", isValid=" + isValid - + ", location=" + location + "]"; - } - - - /** - * Given a version string consisting of integers with dots between them, convert it into an array of ints. - * - * @param version - * @return - * @throws NumberFormatException - */ - public static int[] versionStringToArray(String version) throws NumberFormatException { - if (version == null || version.length() == 0) { - return new int[0]; - } - String[] stringArray = version.split("\\."); - int[] resultArray = new int[stringArray.length]; - for (int i = 0; i < stringArray.length; i++) { - resultArray[i] = Integer.parseInt(stringArray[i]); - } - return resultArray; - } - - /** - * Given an array representing a version, create the corresponding dot-separated string. - * - * @param array - * @return - */ - public static String versionArrayToString(int[] array) { - if (array == null || array.length == 0) { - return ""; - } - String versionString = ""; - if (array.length > 0) { - versionString = "" + array[0]; - for (int i = 1; i < array.length; i++) { - versionString += "." + array[i]; - } - } - return versionString; - } - - - - // - // Methods needed for JSON Deserialization - // - public StdPDPPolicy() {} - - public void setPolicyId(String policyId) { - this.policyId = policyId; - } - public void setDescription(String description) { - this.description = description; - } - public void setVersion(String version) { - this.version = versionStringToArray(version); - } - public void setRoot(boolean isRoot) { - this.isRoot = isRoot; - } - public void setValid(boolean isValid) { - this.isValid = isValid; - } - public void setLocation(URI location) { - this.location = location; - } - -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPStatus.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPStatus.java deleted file mode 100644 index ddb799964..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pap/StdPDPStatus.java +++ /dev/null @@ -1,265 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.std.pap; - -import java.io.Serializable; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import com.att.research.xacml.api.pap.PDPPIPConfig; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.att.research.xacml.api.pap.PDPStatus; -import com.fasterxml.jackson.annotation.JsonIgnore; - -public class StdPDPStatus implements Serializable, PDPStatus { - private static final long serialVersionUID = 1L; - - private Status status = Status.UNKNOWN; - - private Set loadErrors = new HashSet<>(); - - private Set loadWarnings = new HashSet<>(); - - private Set loadedPolicies = new HashSet<>(); - - private Set loadedRootPolicies = new HashSet<>(); - - private Set failedPolicies = new HashSet<>(); - - private Set loadedPIPConfigs = new HashSet<>(); - - private Set failedPIPConfigs = new HashSet<>(); - - public StdPDPStatus() { - } - - public void set(StdPDPStatus newStatus) { - this.status = newStatus.status; - this.loadErrors.clear(); - this.loadErrors.addAll(newStatus.getLoadErrors()); - this.loadWarnings.clear(); - this.loadWarnings.addAll(newStatus.getLoadWarnings()); - this.loadedPolicies.clear(); - this.loadedPolicies.addAll(newStatus.getLoadedPolicies()); - this.loadedRootPolicies.clear(); - this.loadedRootPolicies.addAll(newStatus.getLoadedRootPolicies()); - this.failedPolicies.clear(); - this.failedPolicies.addAll(newStatus.getFailedPolicies()); - this.loadedPIPConfigs.clear(); - this.loadedPIPConfigs.addAll(newStatus.getLoadedPipConfigs()); - this.failedPIPConfigs.clear(); - this.failedPIPConfigs.addAll(newStatus.getFailedPipConfigs()); - } - - - - @Override - public Status getStatus() { - return this.status; - } - - public void setStatus(Status status) { - this.status = status; - } - - @Override - public Set getLoadErrors() { - return Collections.unmodifiableSet(this.loadErrors); - } - - public void setLoadErrors(Set errors) { - this.loadErrors = errors; - } - - public void addLoadError(String error) { - this.loadErrors.add(error); - } - - @Override - public Set getLoadWarnings() { - return Collections.unmodifiableSet(this.loadWarnings); - } - - public void setLoadWarnings(Set warnings) { - this.loadWarnings = warnings; - } - - public void addLoadWarning(String warning) { - this.loadWarnings.add(warning); - } - - @Override - public Set getLoadedPolicies() { - return Collections.unmodifiableSet(this.loadedPolicies); - } - - public void setLoadedPolicies(Set policies) { - this.loadedPolicies = policies; - } - - public void addLoadedPolicy(PDPPolicy policy) { - this.loadedPolicies.add(policy); - } - - @Override - public Set getLoadedRootPolicies() { - return Collections.unmodifiableSet(this.loadedRootPolicies); - } - - public void setLoadedRootPolicies(Set policies) { - this.loadedRootPolicies = policies; - } - - public void addRootPolicy(PDPPolicy policy) { - this.loadedRootPolicies.add(policy); - } - - public void addAllLoadedRootPolicies(Set policies) { - this.loadedRootPolicies.addAll(policies); - } - - @Override - public Set getFailedPolicies() { - return Collections.unmodifiableSet(this.failedPolicies); - } - - public void setFailedPolicies(Set policies) { - this.failedPolicies = policies; - } - - public void addFailedPolicy(PDPPolicy policy) { - this.failedPolicies.add(policy); - } - - @Override - public boolean policiesOK() { - if (this.failedPolicies.size() > 0) { - return false; - } - return true; - } - - @Override - public Set getLoadedPipConfigs() { - return Collections.unmodifiableSet(this.loadedPIPConfigs); - } - - public void setLoadedPipConfigs(Set configs) { - this.loadedPIPConfigs = configs; - } - - public void addLoadedPipConfig(PDPPIPConfig config) { - this.loadedPIPConfigs.add(config); - } - - @Override - public Set getFailedPipConfigs() { - return Collections.unmodifiableSet(this.failedPIPConfigs); - } - - public void setFailedPipConfigs(Set configs) { - this.failedPIPConfigs = configs; - } - - public void addFailedPipConfig(PDPPIPConfig config) { - this.failedPIPConfigs.add(config); - } - - @Override - public boolean pipConfigOK() { - if (this.failedPIPConfigs.size() > 0) { - return false; - } - return true; - } - - @Override - @JsonIgnore - public boolean isOk() { - if (this.policiesOK() == false) { - return false; - } - if (this.pipConfigOK() == false) { - return false; - } - return (this.status == Status.UP_TO_DATE); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime - * result - + (failedPIPConfigs.hashCode()); - result = prime * result - + (failedPolicies.hashCode()); - result = prime * result - + (loadErrors.hashCode()); - result = prime * result - + (loadWarnings.hashCode()); - result = prime - * result - + (loadedPIPConfigs.hashCode()); - result = prime * result - + (loadedPolicies.hashCode()); - result = prime * result + (status.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StdPDPStatus other = (StdPDPStatus) obj; - if (!failedPIPConfigs.equals(other.failedPIPConfigs)) - return false; - if (!failedPolicies.equals(other.failedPolicies)) - return false; - if (!loadErrors.equals(other.loadErrors)) - return false; - if (!loadWarnings.equals(other.loadWarnings)) - return false; - if (!loadedPIPConfigs.equals(other.loadedPIPConfigs)) - return false; - if (!loadedPolicies.equals(other.loadedPolicies)) - return false; - if (status != other.status) - return false; - return true; - } - - @Override - public String toString() { - return "StdPDPStatus [status=" + status + ", loadErrors=" + loadErrors - + ", loadWarnings=" + loadWarnings + ", loadedPolicies=" - + loadedPolicies + ", loadedRootPolicies=" + loadedRootPolicies - + ", failedPolicies=" + failedPolicies - + ", loadedPIPConfigs=" + loadedPIPConfigs - + ", failedPIPConfigs=" + failedPIPConfigs + "]"; - } - - -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pip/engines/OperationHistoryEngine.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pip/engines/OperationHistoryEngine.java deleted file mode 100644 index 30b59cdd8..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pip/engines/OperationHistoryEngine.java +++ /dev/null @@ -1,297 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.std.pip.engines; - -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Properties; -import java.util.Set; - -import javax.persistence.EntityManager; -import javax.persistence.Persistence; -import javax.persistence.Query; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.eclipse.persistence.config.PersistenceUnitProperties; - -import com.att.research.xacml.api.Attribute; -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.api.XACML; -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.api.pip.PIPException; -import com.att.research.xacml.api.pip.PIPFinder; -import com.att.research.xacml.api.pip.PIPRequest; -import com.att.research.xacml.api.pip.PIPResponse; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.StdMutableAttribute; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacml.std.pip.StdMutablePIPResponse; -import com.att.research.xacml.std.pip.StdPIPRequest; -import com.att.research.xacml.std.pip.StdPIPResponse; -import com.att.research.xacml.std.pip.engines.StdConfigurableEngine; -import com.att.research.xacml.util.XACMLProperties; - -/** - * PIP Engine for Implementing {@link com.att.research.xacml.std.pip.engines.ConfigurableEngine} interface to provide - * attribute retrieval from Operation History Table. - * - * @version $Revision$ - */ -public class OperationHistoryEngine extends StdConfigurableEngine{ - public static final String DEFAULT_DESCRIPTION = "PIP for retrieving Operations History from DB"; - public static final String DEFAULT_ISSUER = "org:onap:xacml:guard:historydb"; - - private static final Log LOGGER= LogFactory.getLog(OperationHistoryEngine.class); - - private static final PIPRequest PIP_REQUEST_ACTOR = new StdPIPRequest( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("actor"), - XACML.ID_DATATYPE_STRING); - - private static final PIPRequest PIP_REQUEST_RECIPE = new StdPIPRequest( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("recipe"), - XACML.ID_DATATYPE_STRING); - - private static final PIPRequest PIP_REQUEST_TARGET = new StdPIPRequest( - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("target"), - XACML.ID_DATATYPE_STRING); - - private void addIntegerAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, int value, PIPRequest pipRequest) { - AttributeValue attributeValue = null; - try { - attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value); - } catch (Exception ex) { - LOGGER.error("Failed to convert " + value + " to an AttributeValue", ex); - } - if (attributeValue != null) { - stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, pipRequest.getIssuer()/*this.getIssuer()*/, false)); - } - } - - public OperationHistoryEngine() { - super(); - } - - @Override - public Collection attributesRequired() { - return new ArrayList<>(); - } - - @Override - public Collection attributesProvided() { - return new ArrayList<>(); - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { - LOGGER.info("Entering FeqLimiter PIP"); - /* - * First check to see if the issuer is set and then match it - */ - String string; - if ((string = pipRequest.getIssuer()) == null) { - LOGGER.info("FeqLimiter PIP - No issuer in the request!"); - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - else{ - //Notice, we are checking here for the base issuer prefix. - if (!string.contains(this.getIssuer())) { - LOGGER.debug("Requested issuer '" + string + "' does not match " + (this.getIssuer() == null ? "null" : "'" + this.getIssuer() + "'")); - LOGGER.info("FeqLimiter PIP - Issuer "+ string +" does not match with: "+this.getIssuer()); - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - } - String[] s1 = string.split("tw:"); - String[] s2 = s1[1].split(":"); - int timeWindowVal = Integer.parseInt(s2[0]);// number [of minutes, hours, days...] - String timeWindowScale = s2[1];//e.g., minute, hour, day, week, month, year - String actor = getActor(pipFinder).iterator().next(); - String operation = getRecipe(pipFinder).iterator().next(); - String target = getTarget(pipFinder).iterator().next(); - String timeWindow = timeWindowVal + " " + timeWindowScale; - LOGGER.info("Going to query DB about: "+actor + " " + operation + " " + target + " " + timeWindow); - int countFromDB = getCountFromDB(actor, operation, target, timeWindowVal, timeWindowScale); - StdMutablePIPResponse stdPIPResponse = new StdMutablePIPResponse(); - this.addIntegerAttribute(stdPIPResponse, - XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, - new IdentifierImpl("count"), - countFromDB, - pipRequest); - return new StdPIPResponse(stdPIPResponse); - } - - @Override - public void configure(String id, Properties properties) throws PIPException { - super.configure(id, properties); - if (this.getDescription() == null) { - this.setDescription(DEFAULT_DESCRIPTION); - } - if (this.getIssuer() == null) { - this.setIssuer(DEFAULT_ISSUER); - } - } - - private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { - PIPResponse pipResponse = null; - try { - pipResponse = pipFinder.getMatchingAttributes(pipRequest, this); - if (pipResponse.getStatus() != null && !pipResponse.getStatus().isOk()) { - LOGGER.info("Error retrieving " + pipRequest.getAttributeId().stringValue() + ": " + pipResponse.getStatus().toString()); - pipResponse = null; - } - if (pipResponse!=null && pipResponse.getAttributes().isEmpty()) { - LOGGER.info("No value for " + pipRequest.getAttributeId().stringValue()); - pipResponse = null; - } - } catch (PIPException ex) { - LOGGER.error("PIPException getting subject-id attribute: " + ex.getMessage(), ex); - } - return pipResponse; - } - - - private Set getActor(PIPFinder pipFinder) { - /* - * Get the AT&T UID from either the subject id or the attuid property - */ - PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_ACTOR, pipFinder); - if (pipResponseATTUID == null) { - return new HashSet<>(); - } - /* - * Iterate over all of the returned results and do the LDAP requests - */ - Collection listATTUIDs = pipResponseATTUID.getAttributes(); - Set setATTUIDs = new HashSet<>(); - for (Attribute attributeATTUID: listATTUIDs) { - Iterator> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); - if (iterAttributeValues != null) { - while (iterAttributeValues.hasNext()) { - String attuid = iterAttributeValues.next().getValue(); - if (attuid != null) { - setATTUIDs.add(attuid); - } - } - } - } - return setATTUIDs; - } - - private Set getRecipe(PIPFinder pipFinder) { - /* - * Get the AT&T UID from either the subject id or the attuid property - */ - PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_RECIPE, pipFinder); - if (pipResponseATTUID == null) { - return new HashSet<>(); - } - /* - * Iterate over all of the returned results and do the LDAP requests - */ - Collection listATTUIDs = pipResponseATTUID.getAttributes(); - Set setATTUIDs = new HashSet<>(); - for (Attribute attributeATTUID: listATTUIDs) { - Iterator> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); - if (iterAttributeValues != null) { - while (iterAttributeValues.hasNext()) { - String attuid = iterAttributeValues.next().getValue(); - if (attuid != null) { - setATTUIDs.add(attuid); - } - } - } - } - return setATTUIDs; - } - - - private Set getTarget(PIPFinder pipFinder) { - /* - * Get the AT&T UID from either the subject id or the attuid property - */ - PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_TARGET, pipFinder); - if (pipResponseATTUID == null) { - return new HashSet<>(); - } - /* - * Iterate over all of the returned results and do the LDAP requests - */ - Collection listATTUIDs = pipResponseATTUID.getAttributes(); - Set setATTUIDs = new HashSet<>(); - for (Attribute attributeATTUID: listATTUIDs) { - Iterator> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); - if (iterAttributeValues != null) { - while (iterAttributeValues.hasNext()) { - String attuid = iterAttributeValues.next().getValue(); - if (attuid != null) { - setATTUIDs.add(attuid); - } - } - } - } - return setATTUIDs; - } - - private static int getCountFromDB(String actor, String operation, String target, int timeWindow, String timeUnits){ - EntityManager em; - try{ - Properties properties = XACMLProperties.getProperties(); - properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/operationHistoryPU.xml"); - em = Persistence.createEntityManagerFactory("OperationsHistoryPU",properties).createEntityManager(); - }catch(Exception e){ - LOGGER.error("Test thread got Exception " + e.getLocalizedMessage() + " Can't connect to Operations History DB.", e); - return -1; - } - // Preventing SQL injection - if(!validTimeUnits(timeUnits)){ - LOGGER.error("given PIP timeUnits is not valid. " + timeUnits); - em.close(); - return -1; - } - String sql = "select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor=?" - + " and operation=?" - + " and target=?" - + " and endtime between date_sub(now(),interval ? "+timeUnits+") and now()"; - Query nq = em.createNativeQuery(sql); - nq.setParameter(1, actor); - nq.setParameter(2, operation); - nq.setParameter(3, target); - nq.setParameter(4, timeWindow); - int ret = ((Number)nq.getSingleResult()).intValue(); - LOGGER.info("###########************** History count: " + ret); - em.close(); - return ret; - } - - // Validating Time Units to prevent SQL Injection. - private static boolean validTimeUnits(String timeUnits) { - return (timeUnits.equalsIgnoreCase("minute") || timeUnits.equalsIgnoreCase("hour") || timeUnits.equalsIgnoreCase("day") - || timeUnits.equalsIgnoreCase("week") || timeUnits.equalsIgnoreCase("month")||timeUnits.equalsIgnoreCase("year"))? - true: false; - } -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pip/engines/aaf/AAFEngine.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pip/engines/aaf/AAFEngine.java deleted file mode 100644 index bdf4d342d..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/std/pip/engines/aaf/AAFEngine.java +++ /dev/null @@ -1,272 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.std.pip.engines.aaf; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.openecomp.policy.utils.AAFPolicyClient; -import org.openecomp.policy.utils.AAFPolicyException; - -import com.att.research.xacml.api.Attribute; -import com.att.research.xacml.api.AttributeValue; -import com.att.research.xacml.api.Identifier; -import com.att.research.xacml.api.XACML3; -import com.att.research.xacml.api.pip.PIPException; -import com.att.research.xacml.api.pip.PIPFinder; -import com.att.research.xacml.api.pip.PIPRequest; -import com.att.research.xacml.api.pip.PIPResponse; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.StdMutableAttribute; -import com.att.research.xacml.std.datatypes.DataTypes; -import com.att.research.xacml.std.pip.StdMutablePIPResponse; -import com.att.research.xacml.std.pip.StdPIPRequest; -import com.att.research.xacml.std.pip.StdPIPResponse; -import com.att.research.xacml.std.pip.engines.StdConfigurableEngine; -import com.att.research.xacml.util.XACMLProperties; - -/** - * PIP Engine for Implementing {@link com.att.research.xacml.std.pip.engines.ConfigurableEngine} interface to provide - * attribute retrieval from AAF interface. - * - * @version $Revision$ - */ -public class AAFEngine extends StdConfigurableEngine { - - public static final String DEFAULT_DESCRIPTION = "PIP for authenticating aaf attributes using the AAF REST interface"; - public static final String DEFAULT_ISSUER = "aaf"; - - private static final String SUCCESS = "Success"; - - public static final String AAF_RESULT= "AAF_RESULT"; - public static final String AAF_RESPONSE= "AAF_RESPONSE"; - // - public static final Identifier AAF_RESPONSE_ID = new IdentifierImpl(AAF_RESPONSE); - public static final Identifier AAF_RESULT_ID = new IdentifierImpl(AAF_RESULT); - - // - private static final PIPRequest PIP_REQUEST_UID = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("AAF_ID"), XACML3.ID_DATATYPE_STRING); - private static final PIPRequest PIP_REQUEST_PASS = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("AAF_PASS"), XACML3.ID_DATATYPE_STRING); - private static final PIPRequest PIP_REQUEST_TYPE = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("AAF_TYPE"), XACML3.ID_DATATYPE_STRING); - private static final PIPRequest PIP_REQUEST_INSTANCE = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("AAF_INSTANCE"), XACML3.ID_DATATYPE_STRING); - private static final PIPRequest PIP_REQUEST_ACTION = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("AAF_ACTION"), XACML3.ID_DATATYPE_STRING); - - private static final List mapRequiredAttributes = new ArrayList<>(); - static{ - mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_UID)); - mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_PASS)); - mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_TYPE)); - mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_INSTANCE)); - mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_ACTION)); - } - - private static final Map mapSupportedAttributes = new HashMap<>(); - static{ - mapSupportedAttributes.put(new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESPONSE_ID, XACML3.ID_DATATYPE_STRING), "response"); - mapSupportedAttributes.put(new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESULT_ID, XACML3.ID_DATATYPE_BOOLEAN), "result"); - } - - protected Log logger = LogFactory.getLog(this.getClass()); - - public AAFEngine(){ - //default constructor - } - - private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { - PIPResponse pipResponse = null; - try { - pipResponse = pipFinder.getMatchingAttributes(pipRequest, this); - if (pipResponse.getStatus() != null && !pipResponse.getStatus().isOk()) { - this.logger.warn("Error retrieving " + pipRequest.getAttributeId().stringValue() + ": " + pipResponse.getStatus().toString()); - pipResponse = null; - } - if (pipResponse != null && pipResponse.getAttributes().isEmpty()) { - this.logger.warn("No value for " + pipRequest.getAttributeId().stringValue()); - pipResponse = null; - } - } catch (PIPException ex) { - this.logger.error("PIPException getting subject-id attribute: " + ex.getMessage(), ex); - } - return pipResponse; - } - - private String getValue(PIPResponse pipResponse){ - String result = null; - Collection listAttributes = pipResponse.getAttributes(); - for(Attribute attribute: listAttributes){ - Iterator> iterAttributeValues = attribute.findValues(DataTypes.DT_STRING); - if(iterAttributeValues!=null) { - while(iterAttributeValues.hasNext()){ - result = iterAttributeValues.next().getValue(); - break; - } - } - } - return result; - } - - private synchronized String getResult(PIPFinder pipFinder) { - PIPResponse pipResponseUID = this.getAttribute(PIP_REQUEST_UID, pipFinder); - PIPResponse pipResponsePass = this.getAttribute(PIP_REQUEST_PASS, pipFinder); - PIPResponse pipResponseType = this.getAttribute(PIP_REQUEST_TYPE, pipFinder); - PIPResponse pipResponseAction = this.getAttribute(PIP_REQUEST_ACTION, pipFinder); - PIPResponse pipResponseInstance = this.getAttribute(PIP_REQUEST_INSTANCE, pipFinder); - String response = null; - // Evaluate AAF if we have all the required values. - if(pipResponseUID!=null && pipResponsePass!=null && pipResponseType != null && pipResponseAction!= null && pipResponseInstance!=null){ - String userName = getValue(pipResponseUID); - String pass = getValue(pipResponsePass); - - AAFPolicyClient aafClient = null; - Properties properties; - try { - properties = XACMLProperties.getProperties(); - logger.debug("environment : " + properties.getProperty("ENVIRONMENT")); - } catch (IOException e1) { - logger.error("Exception while getting the properties " + e1); - properties = new Properties(); - properties.setProperty("AAF_LOG_LEVEL", "DEBUG"); - } - if(userName!=null && pass!=null){ - try { - aafClient = AAFPolicyClient.getInstance(properties); - } catch (AAFPolicyException e) { - logger.error("AAF configuration failed. " + e.getMessage() +e); - } - if(aafClient!=null){ - if(aafClient.checkAuth(userName, pass)){ - String type = getValue(pipResponseType); - String instance = getValue(pipResponseInstance); - String action = getValue(pipResponseAction); - if(aafClient.checkPerm(userName, pass, type, instance, action)){ - response = SUCCESS + "Permissions Validated"; - }else{ - response = "No Permissions for "+userName+" to: "+type+", "+instance+", "+action; - } - }else{ - response = "Authentication Failed for the given Values"; - } - } - }else{ - response = "ID and Password are not given"; - } - - }else{ - response = "Insufficient Values to Evaluate AAF"; - } - return response; - } - - private void addStringAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, String value) { - if (value != null) { - AttributeValue attributeValue = null; - try { - attributeValue = DataTypes.DT_STRING.createAttributeValue(value); - } catch (Exception ex) { - this.logger.error("Failed to convert " + value + " to an AttributeValue", ex); - } - if (attributeValue != null) { - stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, this.getIssuer(), false)); - } - } - } - - private void addBooleanAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, boolean value) { - AttributeValue attributeValue = null; - try { - attributeValue = DataTypes.DT_BOOLEAN.createAttributeValue(value); - } catch (Exception ex) { - this.logger.error("Failed to convert " + value + " to an AttributeValue", ex); - } - if (attributeValue != null) { - stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, this.getIssuer(), false)); - } - } - - @Override - public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { - /* - * First check to see if the issuer is set and then match it - */ - String string; - - if((string = pipRequest.getIssuer()) != null && !string.equals(this.getIssuer())) { - this.logger.debug("Requested issuer '" + string + "' does not match " + (this.getIssuer() == null ? "null" : "'" + this.getIssuer() + "'")); - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - - - /* - * Drop the issuer and see if the request matches any of our supported queries - */ - PIPRequest pipRequestSupported = (pipRequest.getIssuer() == null ? pipRequest : new StdPIPRequest(pipRequest.getCategory(), pipRequest.getAttributeId(), pipRequest.getDataTypeId())); - if (!mapSupportedAttributes.containsKey(pipRequestSupported)) { - this.logger.debug("Requested attribute '" + pipRequest.toString() + "' is not supported"); - return StdPIPResponse.PIP_RESPONSE_EMPTY; - } - StdMutablePIPResponse stdPIPResponse = new StdMutablePIPResponse(); - String response = this.getResult(pipFinder); - boolean result = false; - if(response != null && response.contains(SUCCESS)){ - result = true; - } - this.addBooleanAttribute(stdPIPResponse, XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESULT_ID, result); - this.addStringAttribute(stdPIPResponse, XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESPONSE_ID, response); - return new StdPIPResponse(stdPIPResponse); - } - - @Override - public void configure(String id, Properties properties) throws PIPException { - super.configure(id, properties); - if (this.getDescription() == null) { - this.setDescription(DEFAULT_DESCRIPTION); - } - if (this.getIssuer() == null) { - this.setIssuer(DEFAULT_ISSUER); - } - } - - @Override - public Collection attributesRequired() { - List attributes = new ArrayList<>(); - for (PIPRequest attribute: mapRequiredAttributes) { - attributes.add(new StdPIPRequest(attribute)); - } - return attributes; - } - - @Override - public Collection attributesProvided() { - List attributes = new ArrayList<>(); - for (PIPRequest attribute : mapSupportedAttributes.keySet()) { - attributes.add(new StdPIPRequest(attribute)); - } - return attributes; - } - -} \ No newline at end of file diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/util/MetricsUtil.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/util/MetricsUtil.java deleted file mode 100644 index 45a51a191..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/util/MetricsUtil.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.util; - -public class MetricsUtil { - - public static class AvgLatency { - private long cumLatency = 0; - private long count = 0; - - public void compute(long latency) { - cumLatency += latency; - count++; - } - - public long avg() { - if (count == 0) - return 0; - - return (cumLatency / count); - } - - public void reset() { - cumLatency = 0; - count = 0; - } - } - - public static class MinLatency { - private long min = Long.MAX_VALUE; - - public synchronized void compute(long ts) { - if (ts < min) - min = ts; - } - - public long min() { - return min; - } - - public void reset() { - min = Long.MAX_VALUE; - } - } - - public static class MaxLatency { - private long max = Long.MIN_VALUE; - - public synchronized void compute(long ts) { - if (ts > max) - max = ts; - } - - public long max() { - return max; - } - - public void reset() { - max = Long.MIN_VALUE; - } - } - -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/util/XACMLPolicyScanner.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/util/XACMLPolicyScanner.java deleted file mode 100644 index 7b91426b5..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/util/XACMLPolicyScanner.java +++ /dev/null @@ -1,722 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.util; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.Unmarshaller; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - -import com.att.research.xacml.api.AttributeAssignment; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.std.StdAttribute; -import com.att.research.xacml.std.StdAttributeAssignment; -import com.att.research.xacml.std.StdAttributeValue; -import com.att.research.xacml.std.StdMutableAdvice; -import com.att.research.xacml.std.StdMutableObligation; -import com.att.research.xacml.util.XACMLPolicyScanner.Callback; -import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult; - -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.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.IdReferenceType; -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.TargetType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; - -/** - * class XACMLPolicyScanner - * - * This class traverses the hierarchy of a XACML 3.0 policy. You can optionally pass a Callback class - * and override any desired methods to retrieve information from a policy. - * - * - */ -public class XACMLPolicyScanner { - - private static final Log logger = LogFactory.getLog(XACMLPolicyScanner.class); - private Object policyObject = null; - private Callback callback = null; - - public XACMLPolicyScanner(Path filename, Callback callback) { - try (InputStream is = Files.newInputStream(filename)) { - this.policyObject = XACMLPolicyScanner.readPolicy(is); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy"); - } - this.callback = callback; - } - - public XACMLPolicyScanner(InputStream filename, Callback callback) { - try (InputStream is = filename) { - this.policyObject = XACMLPolicyScanner.readPolicy(is); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy"); - } - this.callback = callback; - } - - public XACMLPolicyScanner(PolicySetType policySet, Callback callback) { - this.policyObject = policySet; - this.callback = callback; - } - - public XACMLPolicyScanner(PolicySetType policySet) { - this(policySet, null); - } - - public XACMLPolicyScanner(PolicyType policy, Callback callback) { - this.policyObject = policy; - this.callback = callback; - } - - public XACMLPolicyScanner(PolicyType policy) { - this(policy, null); - } - - /** - * Sets the callback interface to be used. - * - * @param cb - */ - public void setCallback(Callback cb) { - this.callback = cb; - } - - /** - * Saves the given callback object then calls the scan() method. - * - * @param cb - * @return - */ - public Object scan(Callback cb) { - this.callback = cb; - return this.scan(); - } - - /** - * - * This begins the scanning of the contained object. - * - * @return - The PolicySet/Policy that was scanned. - */ - public Object scan() { - if (this.policyObject == null) { - return null; - } - if (this.callback != null) { - if (this.callback.onBeginScan(this.policyObject) == CallbackResult.STOP) { - return this.policyObject; - } - } - if (this.policyObject instanceof PolicyType) { - this.scanPolicy(null, (PolicyType) this.policyObject); - } else if (this.policyObject instanceof PolicySetType) { - this.scanPolicySet(null, (PolicySetType) this.policyObject); - } else { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + "Unknown class type: " + this.policyObject.getClass().getCanonicalName()); - } - if (this.callback != null) { - this.callback.onFinishScan(this.policyObject); - } - return this.policyObject; - } - - /** - * This performs the scan of a PolicySet - * - * @param parent - Its parent PolicySet. Can be null if this is the root. - * @param policySet - The PolicySet object. - * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. - */ - /** - * @param parent - * @param policySet - * @return - */ - protected CallbackResult scanPolicySet(PolicySetType parent, PolicySetType policySet) { - if (logger.isTraceEnabled()) { - logger.trace("scanning policy set: " + policySet.getPolicySetId() + " " + policySet.getDescription()); - } - if (this.callback != null) { - if (this.callback.onPreVisitPolicySet(parent, policySet) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - // - // Scan its info - // - if (this.scanTarget(policySet, policySet.getTarget()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanObligations(policySet, policySet.getObligationExpressions()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanAdvice(policySet, policySet.getAdviceExpressions()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - // - // Iterate the policy sets and/or policies - // - List> list = policySet.getPolicySetOrPolicyOrPolicySetIdReference(); - for (JAXBElement element: list) { - if (element.getName().getLocalPart().equals("PolicySet")) { - if (this.scanPolicySet(policySet, (PolicySetType)element.getValue()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } else if (element.getName().getLocalPart().equals("Policy")) { - if (this.scanPolicy(policySet, (PolicyType)element.getValue()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } else if (element.getValue() instanceof IdReferenceType) { - if (element.getName().getLocalPart().equals("PolicySetIdReference")) { - - } else if (element.getName().getLocalPart().equals("PolicyIdReference")) { - - } - } else { - logger.warn("generating policy sets found unsupported element: " + element.getName().getNamespaceURI()); - } - } - if (this.callback != null) { - if (this.callback.onPostVisitPolicySet(parent, policySet) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - return CallbackResult.CONTINUE; - } - - /** - * - * This performs scanning of the Policy object. - * - * @param parent - The parent PolicySet of the policy. This can be null if this is a root Policy. - * @param policy - The policy being scanned. - * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. - */ - protected CallbackResult scanPolicy(PolicySetType parent, PolicyType policy) { - if (logger.isTraceEnabled()) { - logger.trace("scanning policy: " + policy.getPolicyId() + " " + policy.getDescription()); - } - if (this.callback != null) { - if (this.callback.onPreVisitPolicy(parent, policy) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - // - // Scan its info - // - if (this.scanTarget(policy, policy.getTarget()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanVariables(policy, policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanObligations(policy, policy.getObligationExpressions()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanAdvice(policy, policy.getAdviceExpressions()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - // - // Iterate the rules - // - List list = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - for (Object o: list) { - if (o instanceof RuleType) { - RuleType rule = (RuleType) o; - if (logger.isTraceEnabled()) { - logger.trace("scanning rule: " + rule.getRuleId() + " " + rule.getDescription()); - } - if (this.callback != null) { - if (this.callback.onPreVisitRule(policy, rule) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - if (this.scanTarget(rule, rule.getTarget()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanConditions(rule, rule.getCondition()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanObligations(rule, rule.getObligationExpressions()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.scanAdvice(rule, rule.getAdviceExpressions()) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - if (this.callback != null) { - if (this.callback.onPostVisitRule(policy, rule) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - } else if (o instanceof VariableDefinitionType) { - if (this.callback != null) { - if (this.callback.onVariable(policy, (VariableDefinitionType) o) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - } else { - if (logger.isDebugEnabled()) { - logger.debug("scanning policy rules found unsupported object:" + o.toString()); - } - } - } - if (this.callback != null) { - if (this.callback.onPostVisitPolicy(parent, policy) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - return CallbackResult.CONTINUE; - } - - /** - * Scans the given target for attributes. Its sole purpose is to return attributes found. - * - * @param parent - The parent PolicySet/Policy/Rule for the target. - * @param target - The target. - * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. - */ - protected CallbackResult scanTarget(Object parent, TargetType target) { - if (target == null) { - return CallbackResult.CONTINUE; - } - List anyOfList = target.getAnyOf(); - if (anyOfList != null) { - Iterator iterAnyOf = anyOfList.iterator(); - 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(); - while (iterMatch.hasNext()) { - MatchType match = iterMatch.next(); - // - // Finally down to the actual attribute - // - StdAttribute attribute = null; - AttributeValueType value = match.getAttributeValue(); - if (match.getAttributeDesignator() != null && value != null) { - AttributeDesignatorType designator = match.getAttributeDesignator(); - // - // The content may be tricky - // - attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()), - new IdentifierImpl(designator.getAttributeId()), - new StdAttributeValue>(new IdentifierImpl(value.getDataType()), value.getContent()), - designator.getIssuer(), - false); - } 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); - } else { - logger.warn("NULL designator/selector or value for match."); - } - if (attribute != null && this.callback != null) { - if (this.callback.onAttribute(parent, target, attribute) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - } - } - } - } - } - } - return CallbackResult.CONTINUE; - } - - /** - * Scan the list of obligations. - * - * @param parent - The parent PolicySet/Policy/Rule for the obligation. - * @param obligationExpressionsType - All the obligation expressions. - * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. - */ - protected CallbackResult scanObligations(Object parent, ObligationExpressionsType obligationExpressionsType) { - if (obligationExpressionsType == null) { - return CallbackResult.CONTINUE; - } - List expressions = obligationExpressionsType.getObligationExpression(); - if (expressions == null || expressions.size() == 0) { - return CallbackResult.CONTINUE; - } - for (ObligationExpressionType expression : expressions) { - StdMutableObligation ob = new StdMutableObligation(new IdentifierImpl(expression.getObligationId())); - List assignments = expression.getAttributeAssignmentExpression(); - if (assignments != null) { - for (AttributeAssignmentExpressionType assignment : assignments) { - // category is optional and may be null - IdentifierImpl categoryId = null; - if (assignment.getCategory() != null) { - categoryId = new IdentifierImpl(assignment.getCategory()); - } - AttributeAssignment attribute = new StdAttributeAssignment( - categoryId, - new IdentifierImpl(assignment.getAttributeId()), - assignment.getIssuer(), - new StdAttributeValue(null, null) - ); - ob.addAttributeAssignment(attribute); - } - } - if (this.callback != null) { - if (this.callback.onObligation(parent, expression, ob) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - } - return CallbackResult.CONTINUE; - } - - /** - * - * Scans the list of advice expressions returning each individually. - * - * @param parent - The parent PolicySet/Policy/Rule for the advice. - * @param adviceExpressionstype - The list of advice expressions. - * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. - */ - protected CallbackResult scanAdvice(Object parent, AdviceExpressionsType adviceExpressionstype) { - if (adviceExpressionstype == null) { - return CallbackResult.CONTINUE; - } - List expressions = adviceExpressionstype.getAdviceExpression(); - if (expressions == null || expressions.size() == 0) { - return CallbackResult.CONTINUE; - } - for (AdviceExpressionType expression : expressions) { - StdMutableAdvice ob = new StdMutableAdvice(new IdentifierImpl(expression.getAdviceId())); - List assignments = expression.getAttributeAssignmentExpression(); - if (assignments != null) { - for (AttributeAssignmentExpressionType assignment : assignments) { - IdentifierImpl categoryId = null; - if (assignment.getCategory() != null) { - categoryId = new IdentifierImpl(assignment.getCategory()); - } - AttributeAssignment attribute = new StdAttributeAssignment( - categoryId, - new IdentifierImpl(assignment.getAttributeId()), - assignment.getIssuer(), - new StdAttributeValue(null, null) - ); - ob.addAttributeAssignment(attribute); - } - } - if (this.callback != null) { - if (this.callback.onAdvice(parent, expression, ob) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - } - return CallbackResult.CONTINUE; - } - - /** - * Scans the list of variable definitions. - * - * @param policy - Policy object containing the variable definition. - * @param list - List of variable definitions. - * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. - */ - protected CallbackResult scanVariables(PolicyType policy, List list) { - if (list == null) { - return CallbackResult.CONTINUE; - } - for (Object o : list) { - if (o instanceof VariableDefinitionType) { - if (this.callback != null) { - if (this.callback.onVariable(policy, (VariableDefinitionType) o) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - } - } - - return CallbackResult.CONTINUE; - } - - /** - * Scans the list of conditions. - * - * @param rule - * @param condition - * @return - */ - protected CallbackResult scanConditions(RuleType rule, ConditionType condition) { - if (condition != null) { - if (this.callback != null) { - if (this.callback.onCondition(rule, condition) == CallbackResult.STOP) { - return CallbackResult.STOP; - } - } - } - return CallbackResult.CONTINUE; - } - - /** - * Reads the XACML XML policy file in and returns the version contained in the root Policy/PolicySet element. - * - * @param policy - The policy file. - * @return - The version string from the file (uninterpreted) - * @throws IOException - */ - public static String getVersion(Path policy) throws IOException { - Object data = null; - try (InputStream is = Files.newInputStream(policy)) { - data = XACMLPolicyScanner.readPolicy(is); - } catch (IOException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy"); - throw e; - } - if (data == null) { - logger.warn("Version is null."); - return null; - } - return getVersion(data); - } - - /** - * Reads the Policy/PolicySet element object and returns its current version. - * - * @param data - Either a PolicySet or Policy XACML type object. - * @return - The integer version value. -1 if it doesn't exist or was un-parsable. - */ - public static String getVersion(Object data) { - String version = null; - try { - if (data instanceof PolicySetType) { - version = ((PolicySetType)data).getVersion(); - } else if (data instanceof PolicyType) { - version = ((PolicyType)data).getVersion(); - } else { - if (data != null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + data.getClass().getCanonicalName()); - } - return null; - } - if (version != null && version.length() > 0) { - return version; - } else { - logger.warn("No version set in policy"); - } - } catch (NumberFormatException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Invalid version contained in policy: " + version); - return null; - } - return null; - } - - /** - * Returns the Policy or PolicySet ID. - * - * @param data - A XACML 3.0 Policy or PolicySet element object. - * @return The policy/policyset's policy ID - */ - public static String getID(Object data) { - if (data instanceof PolicySetType) { - return ((PolicySetType)data).getPolicySetId(); - } else if (data instanceof PolicyType) { - return ((PolicyType)data).getPolicyId(); - } else { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + data.getClass().getCanonicalName()); - return null; - } - } - - public static List getCreatedByModifiedBy(Path policyPath) throws IOException{ - String createdBy = ""; - String modifiedBy= ""; - String cValue = "@CreatedBy:"; - String mValue = "@ModifiedBy:"; - for(String line: Files.readAllLines(policyPath)){ - line = line.replaceAll("\\s+", ""); - if(line.isEmpty()){ - continue; - } - if(line.contains("") && line.contains(cValue) && line.contains(mValue)){ - createdBy = line.substring(line.indexOf(cValue) + cValue.length(), line.lastIndexOf(cValue)); - modifiedBy = line.substring(line.indexOf(mValue) + mValue.length(), line.lastIndexOf(mValue)); - break; - } - } - return Arrays.asList(createdBy, modifiedBy); - } - - //get the Created Name of the User on reading the Xml file - public static String getCreatedBy(Path policyPath) throws IOException{ - String userId = ""; - String value = "@CreatedBy:"; - for(String line: Files.readAllLines(policyPath)){ - line = line.replaceAll("\\s+", ""); - if(line.isEmpty()){ - continue; - } - if(line.contains("") && line.contains(value)){ - userId = line.substring(line.indexOf(value) + value.length(), line.lastIndexOf(value)); - break; - } - } - return userId; - } - - //get the Modified Name of the User on reading the Xml file - public static String getModifiedBy(Path policyPath) throws IOException{ - String modifiedBy = ""; - String value = "@ModifiedBy:"; - for(String line: Files.readAllLines(policyPath)){ - line = line.replaceAll("\\s+", ""); - if(line.isEmpty()){ - continue; - } - if(line.contains("") && line.contains(value)){ - modifiedBy = line.substring(line.indexOf(value) + value.length(), line.lastIndexOf(value)); - break; - } - } - return modifiedBy; - } - - /** - * readPolicy - does the work to read in policy data from a file. - * - * @param policy - The path to the policy file. - * @return - The policy data object. This *should* be either a PolicySet or a Policy. - */ - public static Object readPolicy(InputStream is) { - try { - // - // Create a DOM parser - // - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder db = dbf.newDocumentBuilder(); - // - // Parse the policy file - // - Document doc = db.parse(is); - // - // Because there is no root defined in xacml, - // find the first element - // - NodeList nodes = doc.getChildNodes(); - Node node = nodes.item(0); - Element e = null; - if (node.getNodeType() == Node.ELEMENT_NODE) { - e = (Element) node; - // - // Is it a 3.0 policy? - // - if (e.getNamespaceURI().equals("urn:oasis:names:tc:xacml:3.0:core:schema:wd-17")) { - // - // A policyset or policy could be the root - // - if (e.getNodeName().endsWith("Policy")) { - // - // Now we can create the context for the policy set - // and unmarshall the policy into a class. - // - JAXBContext context = JAXBContext.newInstance(PolicyType.class); - Unmarshaller um = context.createUnmarshaller(); - JAXBElement root = um.unmarshal(e, PolicyType.class); - // - // Here is our policy set class - // - return root.getValue(); - } else if (e.getNodeName().endsWith("PolicySet")) { - // - // Now we can create the context for the policy set - // and unmarshall the policy into a class. - // - JAXBContext context = JAXBContext.newInstance(PolicySetType.class); - Unmarshaller um = context.createUnmarshaller(); - JAXBElement root = um.unmarshal(e, PolicySetType.class); - // - // Here is our policy set class - // - return root.getValue(); - } else { - if (logger.isDebugEnabled()) { - logger.debug("Not supported yet: " + e.getNodeName()); - } - } - } else { - logger.warn("unsupported namespace: " + e.getNamespaceURI()); - } - } else { - if (logger.isDebugEnabled()) { - logger.debug("No root element contained in policy " + - " Name: " + node.getNodeName() + " type: " + node.getNodeType() + - " Value: " + node.getNodeValue()); - } - } - } catch (Exception e) { - PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPolicyScanner", "Exception in readPolicy"); - } - return null; - } - - /** - * @return the policyObject - */ - public Object getPolicyObject() { - return policyObject; - } -} diff --git a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/util/XACMLPolicyWriter.java b/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/util/XACMLPolicyWriter.java deleted file mode 100644 index 3706bda3f..000000000 --- a/ECOMP-XACML/src/main/java/org/openecomp/policy/xacml/util/XACMLPolicyWriter.java +++ /dev/null @@ -1,344 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.util; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Iterator; -import java.util.List; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.Unmarshaller; - -import org.openecomp.policy.common.logging.eelf.MessageCodes; -import org.openecomp.policy.common.logging.eelf.PolicyLogger; - - -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.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -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.TargetType; - -/** - * Helper static class for policy writing. - * - * - */ -public class XACMLPolicyWriter { - - /** - * Helper static class that does the work to write a policy set to a file on disk. - * - * - */ - public static Path writePolicyFile(Path filename, PolicySetType policySet) { - JAXBElement policySetElement = new ObjectFactory().createPolicySet(policySet); - try { - JAXBContext context = JAXBContext.newInstance(PolicySetType.class); - Marshaller m = context.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - m.marshal(policySetElement, filename.toFile()); - - if (Files.exists(filename)) { - return filename; - } else { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "File does not exist after marshalling."); - return null; - } - - } catch (JAXBException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed"); - return null; - } - } - - /** - * Helper static class that does the work to write a policy set to an output stream. - * - * - */ - public static void writePolicyFile(OutputStream os, PolicySetType policySet) { - JAXBElement policySetElement = new ObjectFactory().createPolicySet(policySet); - try { - JAXBContext context = JAXBContext.newInstance(PolicySetType.class); - Marshaller m = context.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - m.marshal(policySetElement, os); - } catch (JAXBException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed"); - } - } - - /** - * Helper static class that does the work to write a policy to a file on disk. - * - * - */ - public static Path writePolicyFile(Path filename, PolicyType policy) { - JAXBElement policyElement = new ObjectFactory().createPolicy(policy); - try { - JAXBContext context = JAXBContext.newInstance(PolicyType.class); - Marshaller m = context.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - m.marshal(policyElement, filename.toFile()); - - if (Files.exists(filename)) { - return filename; - } else { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "File does not exist after marshalling."); - return null; - } - - } catch (JAXBException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed"); - return null; - } - } - - - /** - * Helper static class that does the work to write a policy to a file on disk. - * - * - */ - public static InputStream getXmlAsInputStream(PolicyType policy) { - JAXBElement policyElement = new ObjectFactory().createPolicy(policy); - try { - ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - JAXBContext context = JAXBContext.newInstance(PolicyType.class); - Marshaller m = context.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - m.marshal(policyElement, byteArrayOutputStream); - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); - - return byteArrayInputStream; - - } catch (JAXBException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed"); - return null; - } - } - /** - * Helper static class that does the work to write a policy set to an output stream. - * - * - */ - public static void writePolicyFile(OutputStream os, PolicyType policy) { - JAXBElement policySetElement = new ObjectFactory().createPolicy(policy); - try { - JAXBContext context = JAXBContext.newInstance(PolicyType.class); - Marshaller m = context.createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - m.marshal(policySetElement, os); - } catch (JAXBException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed"); - } - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static String changeFileNameInXmlWhenRenamePolicy(Path filename) { - - PolicyType policyType = null; - String extension = ""; - String domain = null; - String repository = "repository"; - if(filename.toString().contains("Config_")){ - domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.toString().length()+1), filename.toString().indexOf("Config_")); - }else if(filename.toString().contains("Action_")){ - domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.toString().length()+1), filename.toString().indexOf("Action_")); - }else if(filename.toString().contains("Decision_")){ - domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.toString().length()+1), filename.toString().indexOf("Decision_")); - } - if(domain.contains(File.separator)){ - domain = domain.replace(File.separator, "."); - } - try { - JAXBContext context = JAXBContext.newInstance(PolicyType.class); - Unmarshaller m = context.createUnmarshaller(); - JAXBElement policyElement = (JAXBElement) m.unmarshal(filename.toFile()); - policyType = policyElement.getValue(); - if (policyType != null) { - TargetType targetType = policyType.getTarget(); - List anyOfTypes = targetType.getAnyOf(); - for( Iterator anyOfIte = anyOfTypes.iterator(); anyOfIte.hasNext(); ){ - AnyOfType anyOfType = (AnyOfType) anyOfIte.next(); - List allOf = anyOfType.getAllOf(); - for( Iterator allOfIte = allOf.iterator(); allOfIte.hasNext(); ){ - AllOfType allOfType = (AllOfType) allOfIte.next(); - List match = allOfType.getMatch(); - for( Iterator matchIte = match.iterator(); matchIte.hasNext();) { - MatchType matchType = (MatchType) matchIte.next(); - if(matchType.getAttributeDesignator().getAttributeId().equals("PolicyName")){ - AttributeValueType attributeValueType = matchType.getAttributeValue(); - List contents = attributeValueType.getContent(); - if (contents != null && contents.size() > 0) { - String value = (String) contents.get(0); - String version = value; - version = version.substring(0, version.lastIndexOf(".")); - version = version.substring(version.lastIndexOf(".")); - if(filename.toString().contains("Config_")){ - value = value.substring(0, value.indexOf("Config_")); - }else{ - value = value.substring(0, value.indexOf("Decision_")); - } - String tmp = filename.getFileName()+""; - String newName = tmp.substring(0, tmp.lastIndexOf(".")); - attributeValueType.getContent().clear(); - attributeValueType.getContent().add(domain + newName + "." + "xml"); - } - } - } - } - } - if(filename.toString().contains("Config_") || filename.toString().contains("Action_")){ - List objects = policyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); - if (objects != null && objects.size() > 0) { - for (Iterator ite = objects.iterator(); ite.hasNext();) { - - RuleType ruleType = (RuleType ) ite.next(); - AdviceExpressionsType adviceExpressionsType = ruleType.getAdviceExpressions(); - if (adviceExpressionsType != null) { - List adviceExpressionTypes = adviceExpressionsType.getAdviceExpression(); - if (adviceExpressionTypes != null && adviceExpressionTypes.size() > 0) { - for (Iterator iterator = adviceExpressionTypes - .iterator(); iterator.hasNext();) { - AdviceExpressionType adviceExpressionType = (AdviceExpressionType) iterator - .next(); - if (adviceExpressionType.getAdviceId() != null && !adviceExpressionType.getAdviceId().equals("") && (adviceExpressionType.getAdviceId().equals("configID") - || adviceExpressionType.getAdviceId().equals("faultID") || adviceExpressionType.getAdviceId().equals("PMID")||adviceExpressionType.getAdviceId().equals("firewallConfigID") - || adviceExpressionType.getAdviceId().equals("MSID")) || adviceExpressionType.getAdviceId().equals("GocID")||adviceExpressionType.getAdviceId().equals("GocHPID")||adviceExpressionType.getAdviceId().equals("BRMSRAWID") - ||adviceExpressionType.getAdviceId().equals("BRMSPARAMID")|| adviceExpressionType.getAdviceId().equals("HPSuppID") || adviceExpressionType.getAdviceId().equals("HPFlapID") || adviceExpressionType.getAdviceId().equals("HPOverID")) - { - List attributeAssignmentExpressionTypes = adviceExpressionType.getAttributeAssignmentExpression(); - if (attributeAssignmentExpressionTypes != null && attributeAssignmentExpressionTypes.size() > 0) { - for (Iterator iterator2 = attributeAssignmentExpressionTypes - .iterator(); iterator2.hasNext();) { - AttributeAssignmentExpressionType attributeAssignmentExpressionType = (AttributeAssignmentExpressionType) iterator2 - .next(); - if (attributeAssignmentExpressionType.getAttributeId().equals("URLID")) { - JAXBElement attributeValueType = (JAXBElement) attributeAssignmentExpressionType.getExpression(); - AttributeValueType attributeValueType1 = attributeValueType.getValue(); - String configUrl = "$URL"; - String urlVal = (String) attributeValueType1.getContent().get(0); - String origExtension = urlVal.substring(urlVal.lastIndexOf('.')+1).trim(); - extension = origExtension; - attributeValueType1.getContent().clear(); - String txtFileName = filename.getFileName().toString(); - txtFileName = txtFileName.substring(0, txtFileName.lastIndexOf(".")+1) + origExtension; - txtFileName = configUrl+ File.separator + "Config" + File.separator + domain + txtFileName; - attributeValueType1.getContent().add(txtFileName); - } else if (attributeAssignmentExpressionType.getAttributeId().equals("PolicyName")) { - JAXBElement attributeValueType = (JAXBElement) attributeAssignmentExpressionType.getExpression(); - AttributeValueType attributeValueType1 = attributeValueType.getValue(); - List contents = attributeValueType1.getContent(); - if (contents != null && contents.size() > 0) { - String value = (String) contents.get(0); - String version = value; - version = version.substring(0, version.lastIndexOf(".")); - version = version.substring(version.lastIndexOf(".")); - value = value.substring(0, value.indexOf("Config_")); - String tmp = filename.getFileName()+""; - String newName = tmp.substring(0, tmp.lastIndexOf(".")); - attributeValueType1.getContent().clear(); - attributeValueType1.getContent().add(domain + newName + "." + "xml"); - } - - } - - } - } - } - } - } - } - } - if (objects != null && objects.size() > 0) { - for (Iterator ite1 = objects.iterator(); ite1.hasNext();) { - - RuleType ruleType1 = (RuleType ) ite1.next(); - ObligationExpressionsType obligationExpressionsType = ruleType1.getObligationExpressions(); - if (obligationExpressionsType != null) { - List obligationExpressionType = obligationExpressionsType.getObligationExpression(); - if (obligationExpressionType != null && obligationExpressionType.size() > 0) { - for (Iterator iterator = obligationExpressionType - .iterator(); iterator.hasNext();) { - ObligationExpressionType obligationExpressionTypes = (ObligationExpressionType) iterator - .next(); - if (obligationExpressionTypes.getObligationId() != null && !obligationExpressionTypes.getObligationId().equals("")) { - List attributeAssignmentExpressionTypes = obligationExpressionTypes.getAttributeAssignmentExpression(); - if (attributeAssignmentExpressionTypes != null && attributeAssignmentExpressionTypes.size() > 0) { - for (Iterator iterator2 = attributeAssignmentExpressionTypes - .iterator(); iterator2.hasNext();) { - AttributeAssignmentExpressionType attributeAssignmentExpressionType = (AttributeAssignmentExpressionType) iterator2 - .next(); - if (attributeAssignmentExpressionType.getAttributeId().equals("body")) { - JAXBElement attributeValueType = (JAXBElement) attributeAssignmentExpressionType.getExpression(); - AttributeValueType attributeValueType1 = attributeValueType.getValue(); - String configUrl = "$URL"; - String urlVal = (String) attributeValueType1.getContent().get(0); - String origExtension = urlVal.substring(urlVal.lastIndexOf('.')+1).trim(); - extension = "json"; - attributeValueType1.getContent().clear(); - String txtFileName = filename.getFileName().toString(); - txtFileName = txtFileName.substring(0, txtFileName.lastIndexOf(".")+1) + origExtension; - txtFileName = configUrl+ File.separator + "Action" + File.separator + domain + txtFileName; - attributeValueType1.getContent().add(txtFileName); - } - - } - } - - } - - } - } - } - } - } - } - } - writePolicyFile(filename, policyType); - } - }catch (JAXBException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed"); - } - - return extension; - } - -} diff --git a/ECOMP-XACML/src/main/resources/xacml.properties b/ECOMP-XACML/src/main/resources/xacml.properties deleted file mode 100644 index 9cdf680f2..000000000 --- a/ECOMP-XACML/src/main/resources/xacml.properties +++ /dev/null @@ -1,46 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-XACML -# ================================================================================ -# 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========================================================= -### - -# Default XACML Properties File -# Standard API Factories -# -xacml.dataTypeFactory=org.openecomp.policy.xacml.std.StdDataTypeFactory -xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory -xacml.pepEngineFactory=org.openecomp.policy.xacml.std.pep.StdEngineFactory -xacml.pipFinderFactory=org.openecomp.policy.xacml.std.pip.StdPIPFinderFactory - -# If there is a standard set of PIPEngines: -# xacml.pip.engines=engine1,engine2,...,engineN -# engine1.classname=com.att.research.xacmlpip.OraclePIP -# engine1.prop1=foo -# engine1.prop2=bar -# ... -# engine2.classname=com.att.research.xacmlpip.ActiveDirectoryPIP -# ... - -# AT&T PDP Implementation Factories -# -xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory -xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory -xacml.att.functionDefinitionFactory=com.att.research.xacmlatt.pdp.std.StdFunctionDefinitionFactory -xacml.att.policyFinderFactory=com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory - -# If there is a standard policy for the engine: -# xacml.att.stdPolicyFinderFactory.rootPolicyFile=/etc/stdpolicyset.xml diff --git a/ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/std/pap/StdEngineFactoryTest.java b/ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/std/pap/StdEngineFactoryTest.java deleted file mode 100644 index 3c1a3385b..000000000 --- a/ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/std/pap/StdEngineFactoryTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.test.std.pap; - -import static org.junit.Assert.assertTrue; - -import java.io.IOException; -import java.util.Properties; - -import org.junit.Test; -import org.openecomp.policy.xacml.std.pap.StdEngineFactory; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.util.FactoryException; - -public class StdEngineFactoryTest { - - - @Test - public void testStdEngineFactory() throws FactoryException, PAPException, IOException{ - - StdEngineFactory stdFactory = new StdEngineFactory(); - System.setProperty("xacml.pap.pdps", "src/test/resources/pdps"); - assertTrue(stdFactory.newEngine() != null); - Properties properties = new Properties(); - properties.setProperty("xacml.pap.pdps", "src/test/resources/pdps"); - assertTrue(stdFactory.newEngine(properties) != null); - - StdEngineFactory stdFactoryNew = new StdEngineFactory(); - System.setProperty("xacml.pap.pdps", "src/test/resources/pdpstest"); - assertTrue(stdFactoryNew.newEngine() != null); - - } -} diff --git a/ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/AAFEngineTest.java b/ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/AAFEngineTest.java deleted file mode 100644 index a7f7817cd..000000000 --- a/ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/AAFEngineTest.java +++ /dev/null @@ -1,24 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.test.util; - -public class AAFEngineTest { - -} diff --git a/ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/MetricsUtilTest.java b/ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/MetricsUtilTest.java deleted file mode 100644 index 1c48d0c89..000000000 --- a/ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/MetricsUtilTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.test.util; - -import static org.junit.Assert.*; - -import org.junit.Test; -import org.openecomp.policy.xacml.util.MetricsUtil; - -public class MetricsUtilTest { - - @Test - public void metricsUtilTest(){ - MetricsUtil.AvgLatency avgLatency = new MetricsUtil.AvgLatency(); - avgLatency.compute(0); - assertTrue(avgLatency.avg() == 0); - avgLatency.compute(2); - assertTrue(avgLatency.avg() == 1); - avgLatency.reset(); - assertTrue(avgLatency.avg() == 0); - - MetricsUtil.MaxLatency maxLatency = new MetricsUtil.MaxLatency(); - maxLatency.compute(2); - assertTrue(maxLatency.max() == 2); - maxLatency.reset(); - assertTrue(maxLatency.max() < 0); - - MetricsUtil.MinLatency minLatency = new MetricsUtil.MinLatency(); - minLatency.compute(2); - assertTrue(minLatency.min() == 2); - minLatency.reset(); - assertTrue(minLatency.min() > 0); - } - -} diff --git a/ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/XACMLPolicyScannerTest.java b/ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/XACMLPolicyScannerTest.java deleted file mode 100644 index b7a12daa8..000000000 --- a/ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/XACMLPolicyScannerTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.test.util; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Path; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.policy.xacml.util.XACMLPolicyScanner; - -import com.att.research.xacml.util.XACMLPolicyScanner.Callback; - -public class XACMLPolicyScannerTest { - - private static final Log logger = LogFactory.getLog(XACMLPolicyScannerTest.class); - private static Path configPolicyPathValue; - private static Path actionPolicyPathValue; - - @Before - public void setUp() { - File templateFile; - ClassLoader classLoader = getClass().getClassLoader(); - try { - templateFile = new File(classLoader.getResource("Config_SampleTest1206.1.xml").getFile()); - configPolicyPathValue = templateFile.toPath(); - templateFile = new File(classLoader.getResource("Action_TestActionPolicy.1.xml").getFile()); - actionPolicyPathValue = templateFile.toPath(); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - } - } - - @Test - public void xacmlPolicyScannerTest() throws IOException{ - Callback callback = null; - try{ - XACMLPolicyScanner actionScanner = new XACMLPolicyScanner(actionPolicyPathValue, callback); - assertTrue(actionScanner.getPolicyObject() != null); - Object actionObject = actionScanner.scan(); - assertTrue(actionObject != null); - - XACMLPolicyScanner scanner = new XACMLPolicyScanner(configPolicyPathValue, callback); - assertTrue(scanner.getPolicyObject() != null); - Object object = scanner.scan(); - assertTrue(object != null); - String id = XACMLPolicyScanner.getID(scanner.getPolicyObject()); - assertTrue(id.equals("urn:com:xacml:policy:id:0b67998b-57e2-4e25-9ea9-f9154bf18df1")); - String version = XACMLPolicyScanner.getVersion(scanner.getPolicyObject()); - assertTrue(version.equals("1")); - String versionFromPath = XACMLPolicyScanner.getVersion(configPolicyPathValue); - assertTrue(versionFromPath.equals("1")); - List returnValue = XACMLPolicyScanner.getCreatedByModifiedBy(configPolicyPathValue); - assertTrue(returnValue.get(0).equals("test")); - String createdBy = XACMLPolicyScanner.getCreatedBy(configPolicyPathValue); - assertTrue(createdBy.equals("test")); - String modifiedBy = XACMLPolicyScanner.getModifiedBy(configPolicyPathValue); - assertTrue(modifiedBy.equals("test")); - }catch(Exception e){ - fail(); - logger.error("Exception Occured"+e); - } - } -} diff --git a/ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/XACMLPolicyWriterTest.java b/ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/XACMLPolicyWriterTest.java deleted file mode 100644 index 0a6fbf5e9..000000000 --- a/ECOMP-XACML/src/test/java/org/openecomp/policy/xacml/test/util/XACMLPolicyWriterTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ECOMP-XACML - * ================================================================================ - * 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.xacml.test.util; - -import static org.junit.Assert.assertTrue; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Path; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.policy.xacml.util.XACMLPolicyWriter; - -public class XACMLPolicyWriterTest { - private static final Log logger = LogFactory.getLog(XACMLPolicyWriterTest.class); - private static Path configPolicyPathValue; - private static Path actionPolicyPathValue; - - @Before - public void setUp() { - File templateFile; - ClassLoader classLoader = getClass().getClassLoader(); - try { - templateFile = new File(classLoader.getResource("Config_SampleTest1206.1.xml").getFile()); - configPolicyPathValue = templateFile.toPath(); - templateFile = new File(classLoader.getResource("Action_TestActionPolicy.1.xml").getFile()); - actionPolicyPathValue = templateFile.toPath(); - } catch (Exception e1) { - logger.error("Exception Occured"+e1); - } - } - - @SuppressWarnings("static-access") - @Test - public void xacmlPolicyWriterTest() throws IOException{ - XACMLPolicyWriter writer = new XACMLPolicyWriter(); - String configResponseValue = writer.changeFileNameInXmlWhenRenamePolicy(configPolicyPathValue); - assertTrue(configResponseValue.equals("txt")); - String actionResponseValue = writer.changeFileNameInXmlWhenRenamePolicy(actionPolicyPathValue); - assertTrue(actionResponseValue.equals("json")); - } -} diff --git a/ECOMP-XACML/src/test/resources/Action_TestActionPolicy.1.xml b/ECOMP-XACML/src/test/resources/Action_TestActionPolicy.1.xml deleted file mode 100644 index 56f843c8d..000000000 --- a/ECOMP-XACML/src/test/resources/Action_TestActionPolicy.1.xml +++ /dev/null @@ -1,52 +0,0 @@ - - - TestActionPolicy@CreatedBy:test@CreatedBy:@ModifiedBy:test@ModifiedBy: - - - - - 12 - - - - - - - - - - - - - - test - - - - - - Sample - - - - - - - PEPAction - - - REST - - - http://localhost.com - - - GET - - - $URL/Action/com.Action_TestActionPolicy.1.xml.json - - - - - \ No newline at end of file diff --git a/ECOMP-XACML/src/test/resources/CSVPolicy.xml b/ECOMP-XACML/src/test/resources/CSVPolicy.xml deleted file mode 100644 index 02a79b104..000000000 --- a/ECOMP-XACML/src/test/resources/CSVPolicy.xml +++ /dev/null @@ -1,205 +0,0 @@ - - - - - This Policy handles the Take action and Advice action operations. - - - - - Check the CPU Utilization or Network Load - - Load - - - - 95 - - - - CPU - - - - 95 - - - - - - Permit to create a new VM with Obligation - - - - - If the Requirement has met create the VM - - true - - - - - - Action_Info - - - - - Create_NEW_VM - - - - - - Permit to create a new VM with Advice - - - - - create_adviceAction - - - - - - - - If the Requirement has met create the VM - - true - - - - - - Action_Info - - - - - Created New VM - - - http://localhost:8080/pdp/?type=hb - - - - - - - - - - - - - - - - Permit to remove a VM with Obligation - - - - - remove_Action - - - - - - - - If the resource usage is low then remove the VM - - true - - - - - - Action_Info - - - - - Remove_VM - - - - - - Permit to remove a VM with Advice - - - - - remove_adviceAction - - - - - - - - If the resource usage is low then remove the VM - - true - - - - - - Action_Info - - - - - Removed VM - - - http://localhost:8080/pdp/?type=hb - - - - - diff --git a/ECOMP-XACML/src/test/resources/Config_SampleTest1206.1.xml b/ECOMP-XACML/src/test/resources/Config_SampleTest1206.1.xml deleted file mode 100644 index 5390548d9..000000000 --- a/ECOMP-XACML/src/test/resources/Config_SampleTest1206.1.xml +++ /dev/null @@ -1,90 +0,0 @@ - - - SampleTest1206@CreatedBy:test@CreatedBy:@ModifiedBy:test@ModifiedBy: - - - - - com.Config_SampleTest1206.1.xml - - - - - - success - - - - PROD - - - - 1 - - - - True - - - - 08-06-2017 - - - - SampleTest1206 - - - - - - - - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - $URL/Config/com.Config_SampleTest1206.1.txt - - - com.Config_SampleTest1206.1.xml - - - 1 - - - success - - - SampleTest1206 - - - PROD - - - 1 - - - True - - - 08-06-2017 - - - - - diff --git a/ECOMP-XACML/src/test/resources/log4j.properties b/ECOMP-XACML/src/test/resources/log4j.properties deleted file mode 100644 index 4c9773d76..000000000 --- a/ECOMP-XACML/src/test/resources/log4j.properties +++ /dev/null @@ -1,42 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-XACML -# ================================================================================ -# 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========================================================= -### - -# -# Use this properties for debugging and development. -# -# -# Set root logger level to DEBUG and its only appender to A1. -log4j.rootLogger=INFO, MAIN_LOG - -# A1 is set to be a ConsoleAppender. -log4j.appender.MAIN_LOG=org.apache.log4j.ConsoleAppender - -# A1 uses PatternLayout. -log4j.appender.MAIN_LOG.layout=org.apache.log4j.PatternLayout -log4j.appender.MAIN_LOG.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n - -# -# This is specifically for Xacml request/response logging -# -log4j.logger.xacml.request=INFO, REQUEST_LOG - -log4j.appender.REQUEST_LOG=org.apache.log4j.ConsoleAppender -log4j.appender.REQUEST_LOG.layout=org.apache.log4j.PatternLayout -log4j.appender.REQUEST_LOG.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} %m%n diff --git a/ECOMP-XACML/src/test/resources/logback.xml b/ECOMP-XACML/src/test/resources/logback.xml deleted file mode 100644 index 2f92f709b..000000000 --- a/ECOMP-XACML/src/test/resources/logback.xml +++ /dev/null @@ -1,253 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --> - - - - - - - - - - - - - - - - - - - - ${defaultPattern} - - - - - - - - - - - - - ${logDirectory}/${auditLogName}.log - - ${logDirectory}/${auditLogName}.%i.log.zip - - 1 - 9 - - - 5MB - - - ${defaultAuditPattern} - - - - - 256 - - - - - - - - ${logDirectory}/${metricsLogName}.log - - ${logDirectory}/${metricsLogName}.%i.log.zip - - 1 - 9 - - - 5MB - - - - ${defaultMetricPattern} - - - - - 256 - - - - - - - - ${logDirectory}/${errorLogName}.log - - ${logDirectory}/${errorLogName}.%i.log.zip - - 1 - 9 - - - ERROR - - - 5MB - - - ${defaultErrorPattern} - - - - - 256 - - - - - - - ${debugLogDirectory}/${debugLogName}.log - - ${debugLogDirectory}/${debugLogName}.%i.log.zip - - 1 - 9 - - - INFO - - - 5MB - - - ${debugLoggerPattern} - - - - - 256 - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ECOMP-XACML/src/test/resources/logging.properties b/ECOMP-XACML/src/test/resources/logging.properties deleted file mode 100644 index 6d1bd488e..000000000 --- a/ECOMP-XACML/src/test/resources/logging.properties +++ /dev/null @@ -1,32 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-XACML -# ================================================================================ -# 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========================================================= -### - -handlers = java.util.logging.ConsoleHandler, java.util.logging.FileHandler - -.level = FINE - -java.util.logging.SimpleFormatter.format=%4$s: %5$s %n - -java.util.logging.ConsoleHandler.level = FINEST -java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter - -java.util.logging.FileHandler.level = SEVERE -java.util.logging.FileHandler.pattern=%h/xacml_log%u.log -java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter diff --git a/ECOMP-XACML/src/test/resources/pdps/default/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml b/ECOMP-XACML/src/test/resources/pdps/default/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml deleted file mode 100644 index 33c0c4a8d..000000000 --- a/ECOMP-XACML/src/test/resources/pdps/default/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml +++ /dev/null @@ -1,93 +0,0 @@ - - - vFW Demo Policy@CreatedBy:@CreatedBy:@ModifiedBy:@ModifiedBy: - - - - - com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml - - - - - - DROOLS - - - - BRMS_PARAM_RULE - - - - SampleRiskType - - - - 1 - - - - False - - - - NA - - - - - - - - - - - ACCESS - - - - Config - - - - - - - - - Configuration - - - $URL/Config/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt - - - com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml - - - 1 - - - DROOLS - - - BRMS_PARAM_RULE - - - vFW - - - SampleRiskType - - - 1 - - - False - - - NA - - - - - \ No newline at end of file diff --git a/ECOMP-XACML/src/test/resources/pdps/default/xacml.pip.properties b/ECOMP-XACML/src/test/resources/pdps/default/xacml.pip.properties deleted file mode 100644 index 4dba1f554..000000000 --- a/ECOMP-XACML/src/test/resources/pdps/default/xacml.pip.properties +++ /dev/null @@ -1,6 +0,0 @@ -# -#Tue Feb 07 10:35:08 EST 2017 -AAF.description=AAFEngine to communicate with AAF to take decisions -AAF.classname=org.openecomp.policy.xacml.std.pip.engines.aaf.AAFEngine -AAF.name=AAFEngine -xacml.pip.engines=AAF \ No newline at end of file diff --git a/ECOMP-XACML/src/test/resources/xacml.pip.properties b/ECOMP-XACML/src/test/resources/xacml.pip.properties deleted file mode 100644 index dbff01086..000000000 --- a/ECOMP-XACML/src/test/resources/xacml.pip.properties +++ /dev/null @@ -1,23 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-XACML -# ================================================================================ -# 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========================================================= -### - -# -#Fri Mar 06 12:06:30 EST 2015 -xacml.pip.engines= diff --git a/ECOMP-XACML/src/test/resources/xacml.policy.properties b/ECOMP-XACML/src/test/resources/xacml.policy.properties deleted file mode 100644 index b1247cdfc..000000000 --- a/ECOMP-XACML/src/test/resources/xacml.policy.properties +++ /dev/null @@ -1,25 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-XACML -# ================================================================================ -# 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========================================================= -### - -# -#Fri Mar 06 12:06:30 EST 2015 -xacml.referencedPolicies= -xacml.rootPolicies= - diff --git a/ECOMP-XACML/testclient.properties b/ECOMP-XACML/testclient.properties deleted file mode 100644 index 84bcd4363..000000000 --- a/ECOMP-XACML/testclient.properties +++ /dev/null @@ -1,21 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-XACML -# ================================================================================ -# 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========================================================= -### - -test=test,MASTER diff --git a/ECOMP-XACML/testpdp.properties b/ECOMP-XACML/testpdp.properties deleted file mode 100644 index 500f8a406..000000000 --- a/ECOMP-XACML/testpdp.properties +++ /dev/null @@ -1,21 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-XACML -# ================================================================================ -# 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========================================================= -### - -PDP_URL= , test, test diff --git a/ECOMP-XACML/xacml.pap.properties b/ECOMP-XACML/xacml.pap.properties deleted file mode 100644 index 15c5cfb9c..000000000 --- a/ECOMP-XACML/xacml.pap.properties +++ /dev/null @@ -1,107 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-XACML -# ================================================================================ -# 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========================================================= -### - -# -# This is our factory that will create our engine -# -xacml.PAP.papEngineFactory=org.openecomp.policy.xacml.std.pap.StdEngineFactory - -# -# Where we store our PAP PDP Group/Node information -# -xacml.pap.pdps=pdps -# -# Need the PAP's url (how PDPs will reach it) configured here -# because we need it to generate the URLs of the Policy Files -# sent to the PDPs in the configuration when the PAP is first brought up. -# (In other cases, such as the PDP calling the PAP, we could generate this URL, -# but for startup there is no other way to get it.) -# -# - -xacml.rest.pap.url=http://localhost:8070/pap/ - -# -# Upon startup, have the PAP servlet send latest configuration information to all -# the PDP nodes it knows about. -# -xacml.rest.pap.initiate.pdp=true -# -# Heartbeat from PAP to PDPs -# -# How much time (in milliseconds) between heartbeats -# (i.e. the time between completing the heartbeat with all PDPs and starting the next cycle) -# -xacml.rest.pap.heartbeat.interval=10000 -# -# Heartbeat connection timeout (in milliseconds) -# -xacml.rest.pap.heartbeat.timeout=10000 - -################################################################################################ -# Adding properties for getting properties previously used by PAP-ADMIN for creating Policies -# THis is part of the Policy Creation API project -################################################################################################ - -# Set your domain here: -xacml.rest.pap.domain=com - -# Location where all the user workspaces are located. -xacml.rest.pap.workspace=workspace - -# Location where the GIT repository is located -xacml.rest.pap.repository=repository - -# new Property Please mention your PAP-REST webapps Location here. -xacml.rest.config.webapps=C:\\Second Tomcat\\apache-tomcat-8.0.23\\webapps\\ConfigPAP\\ - -#Turn the audit on to synchronize the DB/file system -#xacml.rest.pap.run.audit.flag=true -#Turn the audit off to not synchronize the DB/file system -#xacml.rest.pap.run.audit.flag=false -xacml.rest.pap.run.audit.flag=false - -#Audit will synchronize the file system to match the contents of the DB -#xacml.rest.pap.filesystem.audit=true -#Audit will synchronize the DB to match the contents of the file system -#xacml.rest.pap.filesystem.audit=false -xacml.rest.pap.filesystem.audit=false - -# id -xacml.rest.pap.userid=testpap -# pass -xacml.rest.pap.password=alpha123 -# pdps file -xacml.rest.pdp.idfile=test.properties - -#Properties for db access -javax.persistence.jdbc.driver=org.h2.Driver -javax.persistence.jdbc.url=jdbc:h2:file:./sql/xacmlTest -javax.persistence.jdbc.user=sa -javax.persistence.jdbc.password= - -#Time in ms which a Policy DB transaction will wait to get the transaction lock object -xacml.rest.pap.transaction.waitms=1000 - -#Policy DB transaction timeout in ms after it has obtained the transaction lock object -xacml.rest.pap.transaction.timeoutms=500 - -#Policy Audit timeout in ms after it has obtained the transaction lock object -xacml.rest.pap.audit.timeoutms=5000 diff --git a/ECOMP-XACML/xacml.pdp.properties b/ECOMP-XACML/xacml.pdp.properties deleted file mode 100644 index fc731bf29..000000000 --- a/ECOMP-XACML/xacml.pdp.properties +++ /dev/null @@ -1,86 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-XACML -# ================================================================================ -# 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========================================================= -### - -# Default XACML Properties File for PDP RESTful servlet -# -# Standard API Factories -# -xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory -xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory -xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory -# NOT USED SEE BELOW xacml.pipFinderFactory=org.openecomp.policy.xacml.std.pip.StdPIPFinderFactory -xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory -# -# AT&T PDP Implementation Factories -# -xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory -xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory -xacml.att.functionDefinitionFactory=com.att.research.xacmlatt.pdp.std.StdFunctionDefinitionFactory -# NOT USED SEE BELOW xacml.att.policyFinderFactory=com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory - -# -# AT&T RESTful PDP Implementation Factories -# -xacml.pipFinderFactory=org.openecomp.policy.pdp.rest.impl.XACMLPdpPIPFinderFactory -xacml.att.policyFinderFactory=org.openecomp.policy.pdp.rest.impl.XACMLPdpPolicyFinderFactory -# -# When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into -# into one PolicySet and use the given Policy Algorithm. -# -xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-deny-overrides -# -# PDP RESTful API properties -# -# Set this to the address where the XACML-PAP-REST servlet is running -# http://localhost:9090/pap/ -xacml.rest.pap.url=http://localhost:8070/pap/ -# -# Give the running PDP an ID for the PAP. The url that its running as is a good choice. -# The PAP identifies PDP's using the URL of the PDP. -# -xacml.rest.pdp.id=http://localhost:8082/pdp/ -# -# Set the directory where the PDP holds its Policy Cache and PIP Configuration -# -xacml.rest.pdp.config=config_testing - -xacml.rest.pdp.webapps=/webapps - -xacml.rest.pdp.configparams=../webapps/configparams -# -# Initialize register with PAP servlet -# -xacml.rest.pdp.register=true -# -# Sleep period in seconds between register attempts -# -xacml.rest.pdp.register.sleep=15 -# -# number of attempts to register. -1 means keep trying forever. -# -xacml.rest.pdp.register.retries=-1 -# -# max number of bytes in a POST of a XML/JSON request -# -xacml.rest.pdp.maxcontent=32767 -# -# testClient file -# -xacml.rest.pep.idfile = testclient.properties diff --git a/ECOMP-XACML/xacml.properties b/ECOMP-XACML/xacml.properties deleted file mode 100644 index 0c563028e..000000000 --- a/ECOMP-XACML/xacml.properties +++ /dev/null @@ -1,46 +0,0 @@ -### -# ============LICENSE_START======================================================= -# ECOMP-XACML -# ================================================================================ -# 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========================================================= -### - -# Default XACML Properties File -# Standard API Factories -# -xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory -xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory -xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory -xacml.pipFinderFactory=com.att.research.xacml.std.pip.StdPIPFinderFactory - -# If there is a standard set of PIPEngines: -# xacml.pip.engines=engine1,engine2,...,engineN -# engine1.classname=com.att.research.xacmlpip.OraclePIP -# engine1.prop1=foo -# engine1.prop2=bar -# ... -# engine2.classname=com.att.research.xacmlpip.ActiveDirectoryPIP -# ... - -# AT&T PDP Implementation Factories -# -xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory -xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory -xacml.att.functionDefinitionFactory=com.att.research.xacmlatt.pdp.std.StdFunctionDefinitionFactory -xacml.att.policyFinderFactory=com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory - -# If there is a standard policy for the engine: -# xacml.att.stdPolicyFinderFactory.rootPolicyFile=/etc/stdpolicyset.xml diff --git a/LogParser/parserlog.properties b/LogParser/parserlog.properties index caac6c378..4a5ecdb9c 100644 --- a/LogParser/parserlog.properties +++ b/LogParser/parserlog.properties @@ -21,7 +21,7 @@ #Health Check Values RESOURCE_NAME=logparser_pap01 javax.persistence.jdbc.driver=com.mysql.jdbc.Driver -javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/ecomp_sdk +javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/onap_sdk javax.persistence.jdbc.user=policy_user javax.persistence.jdbc.password=policy_user diff --git a/LogParser/pom.xml b/LogParser/pom.xml index 81784b8a2..44bb8fe7f 100644 --- a/LogParser/pom.xml +++ b/LogParser/pom.xml @@ -1,7 +1,7 @@ + + 4.0.0 + asdc + + org.onap.policy.engine + PolicyEngineSuite + 1.1.0-SNAPSHOT + + + + junit + junit + 4.12 + provided + + + \ No newline at end of file diff --git a/ONAP-ASDC/src/main/java/org/onap/policy/asdc/Resource.java b/ONAP-ASDC/src/main/java/org/onap/policy/asdc/Resource.java new file mode 100644 index 000000000..1c4925cd2 --- /dev/null +++ b/ONAP-ASDC/src/main/java/org/onap/policy/asdc/Resource.java @@ -0,0 +1,159 @@ +/*- + * ============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.asdc; + +import java.io.Serializable; +import java.util.UUID; + +public class Resource implements Serializable { + + private static final long serialVersionUID = -913729158733348027L; + + private UUID resourceUUID; + private UUID resourceInvariantUUID; + private String resourceName; + private String resourceVersion; + private ResourceType resourceType; + + public Resource() { + //Empty Constructor + } + + public Resource(Resource resource) { + this.resourceUUID = resource.resourceUUID; + this.resourceInvariantUUID = resource.resourceInvariantUUID; + this.resourceName = resource.resourceName; + this.resourceVersion = resource.resourceVersion; + this.resourceType = resource.resourceType; + } + + public Resource(UUID uuid) { + this.resourceUUID = uuid; + } + + public Resource(String name, ResourceType type) { + this.resourceName = name; + this.resourceType = type; + } + + public Resource(UUID uuid, UUID invariantUUID, String name, String version, ResourceType type) { + this.resourceUUID = uuid; + this.resourceInvariantUUID = invariantUUID; + this.resourceName = name; + this.resourceVersion = version; + this.resourceType = type; + } + + public UUID getResourceUUID() { + return resourceUUID; + } + + public void setResourceUUID(UUID resourceUUID) { + this.resourceUUID = resourceUUID; + } + + public UUID getResourceInvariantUUID() { + return resourceInvariantUUID; + } + + public void setResourceInvariantUUID(UUID resourceInvariantUUID) { + this.resourceInvariantUUID = resourceInvariantUUID; + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + public ResourceType getResourceType() { + return resourceType; + } + + public void setResourceType(ResourceType resourceType) { + this.resourceType = resourceType; + } + + @Override + public String toString() { + return "Resource [resourceUUID=" + resourceUUID + ", resourceInvariantUUID=" + resourceInvariantUUID + + ", resourceName=" + resourceName + ", resourceVersion=" + resourceVersion + ", resourceType=" + + resourceType + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((resourceInvariantUUID == null) ? 0 : resourceInvariantUUID.hashCode()); + result = prime * result + ((resourceName == null) ? 0 : resourceName.hashCode()); + result = prime * result + ((resourceType == null) ? 0 : resourceType.hashCode()); + result = prime * result + ((resourceUUID == null) ? 0 : resourceUUID.hashCode()); + result = prime * result + ((resourceVersion == null) ? 0 : resourceVersion.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Resource other = (Resource) obj; + if (resourceInvariantUUID == null) { + if (other.resourceInvariantUUID != null) + return false; + } else if (!resourceInvariantUUID.equals(other.resourceInvariantUUID)) + return false; + if (resourceName == null) { + if (other.resourceName != null) + return false; + } else if (!resourceName.equals(other.resourceName)) + return false; + if (resourceType == null) { + if (other.resourceType != null) + return false; + } else if (!resourceType.equals(other.resourceType)) + return false; + if (resourceUUID == null) { + if (other.resourceUUID != null) + return false; + } else if (!resourceUUID.equals(other.resourceUUID)) + return false; + if (resourceVersion == null) { + if (other.resourceVersion != null) + return false; + } else if (!resourceVersion.equals(other.resourceVersion)) + return false; + return true; + } + +} diff --git a/ONAP-ASDC/src/main/java/org/onap/policy/asdc/ResourceInstance.java b/ONAP-ASDC/src/main/java/org/onap/policy/asdc/ResourceInstance.java new file mode 100644 index 000000000..a6c31426d --- /dev/null +++ b/ONAP-ASDC/src/main/java/org/onap/policy/asdc/ResourceInstance.java @@ -0,0 +1,157 @@ +/*- + * ============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.asdc; + +import java.io.Serializable; +import java.util.UUID; + +public class ResourceInstance implements Serializable { + private static final long serialVersionUID = -5506162340393802424L; + + private String resourceInstanceName; + private String resourceName; + private UUID resourceInvariantUUID; + private String resourceVersion; + private ResourceType resourceType; + private UUID resourceUUID; + + public ResourceInstance() { + //Empty Constructor + } + + public ResourceInstance(ResourceInstance instance) { + if (instance == null) { + return; + } + this.resourceInstanceName = instance.resourceInstanceName; + this.resourceName = instance.resourceName; + this.resourceInvariantUUID = instance.resourceInvariantUUID; + this.resourceVersion = instance.resourceVersion; + this.resourceType = instance.resourceType; + this.resourceUUID = instance.resourceUUID; + } + + public String getResourceInstanceName() { + return resourceInstanceName; + } + + public void setResourceInstanceName(String resourceInstanceName) { + this.resourceInstanceName = resourceInstanceName; + } + + public String getResourceName() { + return resourceName; + } + + public void setResourceName(String resourceName) { + this.resourceName = resourceName; + } + + public UUID getResourceInvariantUUID() { + return resourceInvariantUUID; + } + + public void setResourceInvariantUUID(UUID resourceInvariantUUID) { + this.resourceInvariantUUID = resourceInvariantUUID; + } + + public String getResourceVersion() { + return resourceVersion; + } + + public void setResourceVersion(String resourceVersion) { + this.resourceVersion = resourceVersion; + } + + public ResourceType getResourceType() { + return resourceType; + } + + public void setResourceType(ResourceType resourceType) { + this.resourceType = resourceType; + } + + public UUID getResourceUUID() { + return resourceUUID; + } + + public void setResourceUUID(UUID resourceUUID) { + this.resourceUUID = resourceUUID; + } + + @Override + public String toString() { + return "ResourceInstance [resourceInstanceName=" + resourceInstanceName + ", resourceName=" + resourceName + + ", resourceInvariantUUID=" + resourceInvariantUUID + ", resourceVersion=" + resourceVersion + + ", resourceType=" + resourceType + ", resourceUUID=" + resourceUUID + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((resourceInstanceName == null) ? 0 : resourceInstanceName.hashCode()); + result = prime * result + ((resourceInvariantUUID == null) ? 0 : resourceInvariantUUID.hashCode()); + result = prime * result + ((resourceName == null) ? 0 : resourceName.hashCode()); + result = prime * result + ((resourceType == null) ? 0 : resourceType.hashCode()); + result = prime * result + ((resourceUUID == null) ? 0 : resourceUUID.hashCode()); + result = prime * result + ((resourceVersion == null) ? 0 : resourceVersion.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ResourceInstance other = (ResourceInstance) obj; + if (resourceInstanceName == null) { + if (other.resourceInstanceName != null) + return false; + } else if (!resourceInstanceName.equals(other.resourceInstanceName)) + return false; + if (resourceInvariantUUID == null) { + if (other.resourceInvariantUUID != null) + return false; + } else if (!resourceInvariantUUID.equals(other.resourceInvariantUUID)) + return false; + if (resourceName == null) { + if (other.resourceName != null) + return false; + } else if (!resourceName.equals(other.resourceName)) + return false; + if (resourceType != other.resourceType) + return false; + if (resourceUUID == null) { + if (other.resourceUUID != null) + return false; + } else if (!resourceUUID.equals(other.resourceUUID)) + return false; + if (resourceVersion == null) { + if (other.resourceVersion != null) + return false; + } else if (!resourceVersion.equals(other.resourceVersion)) + return false; + return true; + } + +} diff --git a/ONAP-ASDC/src/main/java/org/onap/policy/asdc/ResourceType.java b/ONAP-ASDC/src/main/java/org/onap/policy/asdc/ResourceType.java new file mode 100644 index 000000000..46daa7ee1 --- /dev/null +++ b/ONAP-ASDC/src/main/java/org/onap/policy/asdc/ResourceType.java @@ -0,0 +1,40 @@ +/*- + * ============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.asdc; + +public enum ResourceType { + VF("VF"), + VFC("VFC"), + VL("VL"), + CP("CP") + ; + + private String type; + + private ResourceType(String type) { + this.type = type; + } + + public String toString() { + return this.type; + } + +} diff --git a/ONAP-ASDC/src/main/java/org/onap/policy/asdc/Service.java b/ONAP-ASDC/src/main/java/org/onap/policy/asdc/Service.java new file mode 100644 index 000000000..e97a81362 --- /dev/null +++ b/ONAP-ASDC/src/main/java/org/onap/policy/asdc/Service.java @@ -0,0 +1,140 @@ +/*- + * ============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.asdc; + +import java.io.Serializable; +import java.util.UUID; + +public class Service implements Serializable { + + private static final long serialVersionUID = -1249276698549996806L; + + private UUID serviceUUID; + private UUID serviceInvariantUUID; + private String serviceName; + private String serviceVersion; + + public Service() { + //Empty Constructor + } + + public Service(UUID uuid) { + this.serviceUUID = uuid; + } + + public Service(String name) { + this.serviceName = name; + } + + public Service(UUID uuid, UUID invariantUUID, String name, String version) { + this.serviceUUID = uuid; + this.serviceInvariantUUID = invariantUUID; + this.serviceName = name; + this.serviceVersion = version; + } + + public Service(Service service) { + this.serviceUUID = service.serviceUUID; + this.serviceInvariantUUID = service.serviceInvariantUUID; + this.serviceName = service.serviceName; + this.serviceVersion = service.serviceVersion; + } + + public UUID getServiceUUID() { + return serviceUUID; + } + + public void setServiceUUID(UUID serviceUUID) { + this.serviceUUID = serviceUUID; + } + + public UUID getServiceInvariantUUID() { + return serviceInvariantUUID; + } + + public void setServiceInvariantUUID(UUID serviceInvariantUUID) { + this.serviceInvariantUUID = serviceInvariantUUID; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getServiceVersion() { + return serviceVersion; + } + + public void setServiceVersion(String serviceVersion) { + this.serviceVersion = serviceVersion; + } + + @Override + public String toString() { + return "Service [serviceUUID=" + serviceUUID + ", serviceInvariantUUID=" + serviceInvariantUUID + + ", serviceName=" + serviceName + ", serviceVersion=" + serviceVersion + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((serviceInvariantUUID == null) ? 0 : serviceInvariantUUID.hashCode()); + result = prime * result + ((serviceName == null) ? 0 : serviceName.hashCode()); + result = prime * result + ((serviceUUID == null) ? 0 : serviceUUID.hashCode()); + result = prime * result + ((serviceVersion == null) ? 0 : serviceVersion.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Service other = (Service) obj; + if (serviceInvariantUUID == null) { + if (other.serviceInvariantUUID != null) + return false; + } else if (!serviceInvariantUUID.equals(other.serviceInvariantUUID)) + return false; + if (serviceName == null) { + if (other.serviceName != null) + return false; + } else if (!serviceName.equals(other.serviceName)) + return false; + if (serviceUUID == null) { + if (other.serviceUUID != null) + return false; + } else if (!serviceUUID.equals(other.serviceUUID)) + return false; + if (serviceVersion == null) { + if (other.serviceVersion != null) + return false; + } else if (!serviceVersion.equals(other.serviceVersion)) + return false; + return true; + } + +} diff --git a/ONAP-ASDC/src/main/java/org/onap/policy/asdc/ServiceInstance.java b/ONAP-ASDC/src/main/java/org/onap/policy/asdc/ServiceInstance.java new file mode 100644 index 000000000..63a41fbf1 --- /dev/null +++ b/ONAP-ASDC/src/main/java/org/onap/policy/asdc/ServiceInstance.java @@ -0,0 +1,177 @@ +/*- + * ============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.asdc; + +import java.io.Serializable; +import java.util.UUID; + +public class ServiceInstance implements Serializable { + private static final long serialVersionUID = 6285260780966679625L; + + private UUID personaModelUUID; + private UUID serviceUUID; + private UUID serviceInstanceUUID; + private UUID widgetModelUUID; + private String widgetModelVersion; + private String serviceName; + private String serviceInstanceName; + + public ServiceInstance() { + //Empty Constructor + } + + public ServiceInstance(ServiceInstance instance) { + if (instance == null) { + return; + } + this.personaModelUUID = instance.personaModelUUID; + this.serviceUUID = instance.serviceUUID; + this.serviceInstanceUUID = instance.serviceInstanceUUID; + this.widgetModelUUID = instance.widgetModelUUID; + this.widgetModelVersion = instance.widgetModelVersion; + this.serviceName = instance.serviceName; + this.serviceInstanceName = instance.serviceInstanceName; + } + + public UUID getPersonaModelUUID() { + return personaModelUUID; + } + + public void setPersonaModelUUID(UUID personaModelUUID) { + this.personaModelUUID = personaModelUUID; + } + + public UUID getServiceUUID() { + return serviceUUID; + } + + public void setServiceUUID(UUID serviceUUID) { + this.serviceUUID = serviceUUID; + } + + public UUID getServiceInstanceUUID() { + return serviceInstanceUUID; + } + + public void setServiceInstanceUUID(UUID serviceInstanceUUID) { + this.serviceInstanceUUID = serviceInstanceUUID; + } + + public UUID getWidgetModelUUID() { + return widgetModelUUID; + } + + public void setWidgetModelUUID(UUID widgetModelUUID) { + this.widgetModelUUID = widgetModelUUID; + } + + public String getWidgetModelVersion() { + return widgetModelVersion; + } + + public void setWidgetModelVersion(String widgetModelVersion) { + this.widgetModelVersion = widgetModelVersion; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getServiceInstanceName() { + return serviceInstanceName; + } + + public void setServiceInstanceName(String serviceInstanceName) { + this.serviceInstanceName = serviceInstanceName; + } + + @Override + public String toString() { + return "ServiceInstance [personaModelUUID=" + personaModelUUID + ", serviceUUID=" + serviceUUID + + ", serviceInstanceUUID=" + serviceInstanceUUID + ", widgetModelUUID=" + widgetModelUUID + + ", widgetModelVersion=" + widgetModelVersion + ", serviceName=" + serviceName + + ", serviceInstanceName=" + serviceInstanceName + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((personaModelUUID == null) ? 0 : personaModelUUID.hashCode()); + result = prime * result + ((serviceInstanceName == null) ? 0 : serviceInstanceName.hashCode()); + result = prime * result + ((serviceInstanceUUID == null) ? 0 : serviceInstanceUUID.hashCode()); + result = prime * result + ((serviceName == null) ? 0 : serviceName.hashCode()); + result = prime * result + ((serviceUUID == null) ? 0 : serviceUUID.hashCode()); + result = prime * result + ((widgetModelUUID == null) ? 0 : widgetModelUUID.hashCode()); + result = prime * result + ((widgetModelVersion == null) ? 0 : widgetModelVersion.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ServiceInstance other = (ServiceInstance) obj; + if (personaModelUUID == null) { + if (other.personaModelUUID != null) + return false; + } else if (!personaModelUUID.equals(other.personaModelUUID)) + return false; + if (serviceInstanceName == null) { + if (other.serviceInstanceName != null) + return false; + } else if (!serviceInstanceName.equals(other.serviceInstanceName)) + return false; + if (serviceInstanceUUID == null) { + if (other.serviceInstanceUUID != null) + return false; + } else if (!serviceInstanceUUID.equals(other.serviceInstanceUUID)) + return false; + if (serviceName == null) { + if (other.serviceName != null) + return false; + } else if (!serviceName.equals(other.serviceName)) + return false; + if (serviceUUID == null) { + if (other.serviceUUID != null) + return false; + } else if (!serviceUUID.equals(other.serviceUUID)) + return false; + if (widgetModelUUID == null) { + if (other.widgetModelUUID != null) + return false; + } else if (!widgetModelUUID.equals(other.widgetModelUUID)) + return false; + if (widgetModelVersion == null) { + if (other.widgetModelVersion != null) + return false; + } else if (!widgetModelVersion.equals(other.widgetModelVersion)) + return false; + return true; + } + +} diff --git a/ECOMP-ASDC/src/main/resources/definitions.yaml b/ONAP-ASDC/src/main/resources/definitions.yaml similarity index 100% rename from ECOMP-ASDC/src/main/resources/definitions.yaml rename to ONAP-ASDC/src/main/resources/definitions.yaml diff --git a/ONAP-ControlloopPolicy/pom.xml b/ONAP-ControlloopPolicy/pom.xml new file mode 100644 index 000000000..2c973cf75 --- /dev/null +++ b/ONAP-ControlloopPolicy/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + ControlloopPolicy + + org.onap.policy.engine + PolicyEngineSuite + 1.1.0-SNAPSHOT + + + + org.onap.policy.engine + asdc + ${project.version} + + + junit + junit + 4.12 + provided + + + org.yaml + snakeyaml + 1.17 + + + org.jgrapht + jgrapht-core + 0.9.2 + + + com.google.guava + guava + 19.0 + + + org.onap.policy.common + ONAP-Logging + ${common-modules.version} + + + diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/compiler/CompilerException.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/compiler/CompilerException.java new file mode 100644 index 000000000..4a86b3bf4 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/compiler/CompilerException.java @@ -0,0 +1,47 @@ +/*- + * ============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.controlloop.compiler; + +public class CompilerException extends Exception { + + private static final long serialVersionUID = -7262217239867898601L; + + public CompilerException() { + //Empty Constructor + } + + public CompilerException(String message) { + super(message); + } + + public CompilerException(Throwable cause) { + super(cause); + } + + public CompilerException(String message, Throwable cause) { + super(message, cause); + } + + public CompilerException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java new file mode 100644 index 000000000..18f56d53f --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompiler.java @@ -0,0 +1,617 @@ +/*- + * ============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.controlloop.compiler; + +import java.io.InputStream; +import java.io.Serializable; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.jgrapht.DirectedGraph; +import org.jgrapht.graph.ClassBasedEdgeFactory; +import org.jgrapht.graph.DefaultEdge; +import org.jgrapht.graph.DirectedMultigraph; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.controlloop.policy.ControlLoop; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.FinalResult; +import org.onap.policy.controlloop.policy.Policy; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.controlloop.policy.TargetType; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +public class ControlLoopCompiler implements Serializable{ + /** + * + */ + private static final long serialVersionUID = 1L; + private static Logger LOGGER = FlexLogger.getLogger(ControlLoopCompiler.class.getName()); + + public static ControlLoopPolicy compile(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException { + // + // Ensure the control loop is sane + // + validateControlLoop(policy.getControlLoop(), callback); + // + // Validate the policies + // + validatePolicies(policy, callback); + + return policy; + } + + public static ControlLoopPolicy compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException { + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(yamlSpecification); + if (obj == null) { + throw new CompilerException("Could not parse yaml specification."); + } + if (! (obj instanceof ControlLoopPolicy)) { + throw new CompilerException("Yaml could not parse specification into required ControlLoopPolicy object"); + } + return ControlLoopCompiler.compile((ControlLoopPolicy) obj, callback); + } + + private static void validateControlLoop(ControlLoop controlLoop, ControlLoopCompilerCallback callback) throws CompilerException { + if (controlLoop == null && callback != null) { + callback.onError("controlLoop cannot be null"); + } + if (controlLoop!=null){ + if ((controlLoop.getControlLoopName() == null || controlLoop.getControlLoopName().length() < 1) && callback != null) { + callback.onError("Missing controlLoopName"); + } + if ((!controlLoop.getVersion().contentEquals(ControlLoop.getVERSION())) && callback != null) { + callback.onError("Unsupported version for this compiler"); + } + if (controlLoop.getTrigger_policy() == null || controlLoop.getTrigger_policy().length() < 1) { + throw new CompilerException("trigger_policy is not valid"); + } + } + } + + private static void validatePolicies(ControlLoopPolicy policy, ControlLoopCompilerCallback callback) throws CompilerException { + if (policy == null) { + throw new CompilerException("policy cannot be null"); + } + // + // verify controlLoop overall timeout should be no less than the sum of operational policy timeouts + // + if (policy.getPolicies() == null) { + callback.onWarning("controlLoop is an open loop."); + } + else{ + int sum = 0; + for (Policy operPolicy : policy.getPolicies()) { + sum += operPolicy.getTimeout().intValue(); + } + if (policy.getControlLoop().getTimeout().intValue() < sum && callback != null) { + callback.onError("controlLoop overall timeout is less than the sum of operational policy timeouts."); + } + // + // For this version we can use a directed multigraph, in the future we may not be able to + // + DirectedGraph graph = new DirectedMultigraph<>(new ClassBasedEdgeFactory(LabeledEdge.class)); + // + // Check to see if the trigger Event is for OpenLoop, we do so by + // attempting to create a FinalResult object from it. If its a policy id, this should + // return null. + // + FinalResult triggerResult = FinalResult.toResult(policy.getControlLoop().getTrigger_policy()); + TriggerNodeWrapper triggerNode; + // + // Did this turn into a FinalResult object? + // + if (triggerResult != null) { + // + // Ensure they didn't use some other FinalResult code + // + if (triggerResult != FinalResult.FINAL_OPENLOOP) { + throw new CompilerException("Unexpected Final Result for trigger_policy, should only be " + FinalResult.FINAL_OPENLOOP.toString() + " or a valid Policy ID"); + } + // + // They really shouldn't have any policies attached. + // + if ((policy.getPolicies() != null || policy.getPolicies().isEmpty())&& callback != null ) { + callback.onWarning("Open Loop policy contains policies. The policies will never be invoked."); + } + return; + // + } else { + // + // Ok, not a FinalResult object so let's assume that it is a Policy. Which it should be. + // + triggerNode = new TriggerNodeWrapper(policy.getControlLoop().getControlLoopName()); + } + // + // Add in the trigger node + // + graph.addVertex(triggerNode); + // + // Add in our Final Result nodes. All paths should end to these nodes. + // + FinalResultNodeWrapper finalSuccess = new FinalResultNodeWrapper(FinalResult.FINAL_SUCCESS); + FinalResultNodeWrapper finalFailure = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE); + FinalResultNodeWrapper finalFailureTimeout = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT); + FinalResultNodeWrapper finalFailureRetries = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_RETRIES); + FinalResultNodeWrapper finalFailureException = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION); + FinalResultNodeWrapper finalFailureGuard = new FinalResultNodeWrapper(FinalResult.FINAL_FAILURE_GUARD); + graph.addVertex(finalSuccess); + graph.addVertex(finalFailure); + graph.addVertex(finalFailureTimeout); + graph.addVertex(finalFailureRetries); + graph.addVertex(finalFailureException); + graph.addVertex(finalFailureGuard); + // + // Work through the policies and add them in as nodes. + // + Map mapNodes = new HashMap<>(); + for (Policy operPolicy : policy.getPolicies()) { + // + // Is it still ok to add? + // + if (!okToAdd(operPolicy, callback)) { + // + // Do not add it in + // + continue; + } + // + // Create wrapper policy node and save it into our map so we can + // easily retrieve it. + // + PolicyNodeWrapper node = new PolicyNodeWrapper(operPolicy); + mapNodes.put(operPolicy, node); + graph.addVertex(node); + // + // Is this the trigger policy? + // + if (operPolicy.getId().equals(policy.getControlLoop().getTrigger_policy())) { + // + // Yes add an edge from our trigger event node to this policy + // + graph.addEdge(triggerNode, node, new LabeledEdge(triggerNode, node, new TriggerEdgeWrapper("ONSET"))); + } + } + // + // last sweep to connect remaining edges for policy results + // + for (Policy operPolicy : policy.getPolicies()) { + PolicyNodeWrapper node = mapNodes.get(operPolicy); + // + // Just ensure this has something + // + if (node == null) { + continue; + } + if (FinalResult.isResult(operPolicy.getSuccess(), FinalResult.FINAL_SUCCESS)) { + graph.addEdge(node, finalSuccess, new LabeledEdge(node, finalSuccess, new FinalResultEdgeWrapper(FinalResult.FINAL_SUCCESS))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getSuccess()); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.getId() + " success is connected to unknown policy " + operPolicy.getSuccess()); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.SUCCESS))); + } + } + if (FinalResult.isResult(operPolicy.getFailure(), FinalResult.FINAL_FAILURE)) { + graph.addEdge(node, finalFailure, new LabeledEdge(node, finalFailure, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure()); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure is connected to unknown policy " + operPolicy.getFailure()); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE))); + } + } + if (FinalResult.isResult(operPolicy.getFailure_timeout(), FinalResult.FINAL_FAILURE_TIMEOUT)) { + graph.addEdge(node, finalFailureTimeout, new LabeledEdge(node, finalFailureTimeout, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_TIMEOUT))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_timeout()); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_timeout is connected to unknown policy " + operPolicy.getFailure_timeout()); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_TIMEOUT))); + } + } + if (FinalResult.isResult(operPolicy.getFailure_retries(), FinalResult.FINAL_FAILURE_RETRIES)) { + graph.addEdge(node, finalFailureRetries, new LabeledEdge(node, finalFailureRetries, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_RETRIES))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_retries()); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_retries is connected to unknown policy " + operPolicy.getFailure_retries()); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_RETRIES))); + } + } + if (FinalResult.isResult(operPolicy.getFailure_exception(), FinalResult.FINAL_FAILURE_EXCEPTION)) { + graph.addEdge(node, finalFailureException, new LabeledEdge(node, finalFailureException, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_EXCEPTION))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_exception()); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_exception is connected to unknown policy " + operPolicy.getFailure_exception()); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_EXCEPTION))); + } + } + if (FinalResult.isResult(operPolicy.getFailure_guard(), FinalResult.FINAL_FAILURE_GUARD)) { + graph.addEdge(node, finalFailureGuard, new LabeledEdge(node, finalFailureGuard, new FinalResultEdgeWrapper(FinalResult.FINAL_FAILURE_GUARD))); + } else { + PolicyNodeWrapper toNode = findPolicyNode(mapNodes, operPolicy.getFailure_guard()); + if (toNode == null) { + throw new CompilerException("Operation Policy " + operPolicy.getId() + " failure_guard is connected to unknown policy " + operPolicy.getFailure_guard()); + } else { + graph.addEdge(node, toNode, new LabeledEdge(node, toNode, new PolicyResultEdgeWrapper(PolicyResult.FAILURE_GUARD))); + } + } + } + // + // Now validate all the nodes/edges + // + for (NodeWrapper node : graph.vertexSet()) { + if (node instanceof TriggerNodeWrapper) { + LOGGER.info("Trigger Node " + node.toString()); + if (graph.inDegreeOf(node) > 0 ) { + // + // Really should NEVER get here unless someone messed up the code above. + // + throw new CompilerException("No inputs to event trigger"); + } + // + // Should always be 1, except in the future we may support multiple events + // + if (graph.outDegreeOf(node) > 1) { + throw new CompilerException("The event trigger should only go to ONE node"); + } + } else if (node instanceof FinalResultNodeWrapper) { + LOGGER.info("FinalResult Node " + node.toString()); + // + // FinalResult nodes should NEVER have an out edge + // + if (graph.outDegreeOf(node) > 0) { + throw new CompilerException("FinalResult nodes should never have any out edges."); + } + } else if (node instanceof PolicyNodeWrapper) { + LOGGER.info("Policy Node " + node.toString()); + // + // All Policy Nodes should have the 5 out degrees defined. + // + if (graph.outDegreeOf(node) != 6) { + throw new CompilerException("Policy node should ALWAYS have 6 out degrees."); + } + // + // All Policy Nodes should have at least 1 in degrees + // + if (graph.inDegreeOf(node) == 0 && callback != null) { + callback.onWarning("Policy " + node.getID() + " is not reachable."); + } + } + for (LabeledEdge edge : graph.outgoingEdgesOf(node)){ + LOGGER.info(edge.from.getID() + " invokes " + edge.to.getID() + " upon " + edge.edge.getID()); + } + } + } + } + + private static boolean okToAdd(Policy operPolicy, ControlLoopCompilerCallback callback) { + // + // Check the policy id and make sure its sane + // + boolean okToAdd = true; + if (operPolicy.getId() == null || operPolicy.getId().length() < 1) { + if (callback != null) { + callback.onError("Operational Policy has an bad ID"); + } + okToAdd = false; + } + // + // Check if they decided to make the ID a result object + // + if (PolicyResult.toResult(operPolicy.getId()) != null) { + if (callback != null) { + callback.onError("Policy id is set to a PolicyResult " + operPolicy.getId()); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.getId()) != null) { + if (callback != null) { + callback.onError("Policy id is set to a FinalResult " + operPolicy.getId()); + } + okToAdd = false; + } + // + // Check that the actor/recipe/target are valid + // + if (operPolicy.getActor() == null) { + if (callback != null) { + callback.onError("Policy actor is null"); + } + okToAdd = false; + } + // + // Construct a list for all valid actors + // + ImmutableList actors = ImmutableList.of("APPC", "AOTS", "MSO", "SDNO", "SDNR", "AAI"); + // + if (operPolicy.getActor() != null && (!actors.contains(operPolicy.getActor())) ) { + if (callback != null) { + callback.onError("Policy actor is invalid"); + } + okToAdd = false; + } + if (operPolicy.getRecipe() == null) { + if (callback != null) { + callback.onError("Policy recipe is null"); + } + okToAdd = false; + } + // + // NOTE: We need a way to find the acceptable recipe values (either Enum or a database that has these) + // + ImmutableMap> recipes = new ImmutableMap.Builder>() + .put("APPC", ImmutableList.of("Restart", "Rebuild", "Migrate", "ModifyConfig")) + .put("AOTS", ImmutableList.of("checkMaintenanceWindow", "checkENodeBTicketHours", "checkEquipmentStatus", "checkEimStatus", "checkEquipmentMaintenance")) + .put("MSO", ImmutableList.of("VF Module Create")) + .put("SDNO", ImmutableList.of("health-diagnostic-type", "health-diagnostic", "health-diagnostic-history", "health-diagnostic-commands", "health-diagnostic-aes")) + .put("SDNR", ImmutableList.of("Restart", "Reboot")) + .build(); + // + if (operPolicy.getRecipe() != null && (!recipes.getOrDefault(operPolicy.getActor(), Collections.emptyList()).contains(operPolicy.getRecipe()))) { + if (callback != null) { + callback.onError("Policy recipe is invalid"); + } + okToAdd = false; + } + if (operPolicy.getTarget() == null) { + if (callback != null) { + callback.onError("Policy target is null"); + } + okToAdd = false; + } + if (operPolicy.getTarget() != null && operPolicy.getTarget().getType() != TargetType.VM && operPolicy.getTarget().getType() != TargetType.VFC && operPolicy.getTarget().getType() != TargetType.PNF) { + if (callback != null) { + callback.onError("Policy target is invalid"); + } + okToAdd = false; + } + // + // Check that policy results are connected to either default final * or another policy + // + if (FinalResult.toResult(operPolicy.getSuccess()) != null && operPolicy.getSuccess() != FinalResult.FINAL_SUCCESS.toString()) { + if (callback != null) { + callback.onError("Policy success is neither another policy nor FINAL_SUCCESS"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.getFailure()) != null && operPolicy.getFailure() != FinalResult.FINAL_FAILURE.toString()) { + if (callback != null) { + callback.onError("Policy failure is neither another policy nor FINAL_FAILURE"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.getFailure_retries()) != null && operPolicy.getFailure_retries() != FinalResult.FINAL_FAILURE_RETRIES.toString()) { + if (callback != null) { + callback.onError("Policy failure retries is neither another policy nor FINAL_FAILURE_RETRIES"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.getFailure_timeout()) != null && operPolicy.getFailure_timeout() != FinalResult.FINAL_FAILURE_TIMEOUT.toString()) { + if (callback != null) { + callback.onError("Policy failure timeout is neither another policy nor FINAL_FAILURE_TIMEOUT"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.getFailure_exception()) != null && operPolicy.getFailure_exception() != FinalResult.FINAL_FAILURE_EXCEPTION.toString()) { + if (callback != null) { + callback.onError("Policy failure exception is neither another policy nor FINAL_FAILURE_EXCEPTION"); + } + okToAdd = false; + } + if (FinalResult.toResult(operPolicy.getFailure_guard()) != null && operPolicy.getFailure_guard() != FinalResult.FINAL_FAILURE_GUARD.toString()) { + if (callback != null) { + callback.onError("Policy failure guard is neither another policy nor FINAL_FAILURE_GUARD"); + } + okToAdd = false; + } + return okToAdd; + } + + private static PolicyNodeWrapper findPolicyNode(Map mapNodes, String id) { + for (Entry entry : mapNodes.entrySet()) { + if (entry.getKey().getId().equals(id)) { + return entry.getValue(); + } + } + return null; + } + + @FunctionalInterface + private interface NodeWrapper extends Serializable{ + public String getID(); + } + + private static class TriggerNodeWrapper implements NodeWrapper { + private static final long serialVersionUID = -187644087811478349L; + private String closedLoopControlName; + + public TriggerNodeWrapper(String closedLoopControlName) { + this.closedLoopControlName = closedLoopControlName; + } + + @Override + public String toString() { + return "TriggerNodeWrapper [closedLoopControlName=" + closedLoopControlName + "]"; + } + + @Override + public String getID() { + return closedLoopControlName; + } + + } + + private static class FinalResultNodeWrapper implements NodeWrapper { + private static final long serialVersionUID = 8540008796302474613L; + private FinalResult result; + + public FinalResultNodeWrapper(FinalResult result) { + this.result = result; + } + + @Override + public String toString() { + return "FinalResultNodeWrapper [result=" + result + "]"; + } + + @Override + public String getID() { + return result.toString(); + } + } + + private static class PolicyNodeWrapper implements NodeWrapper { + private static final long serialVersionUID = 8170162175653823082L; + private Policy policy; + + public PolicyNodeWrapper(Policy operPolicy) { + this.policy = operPolicy; + } + + @Override + public String toString() { + return "PolicyNodeWrapper [policy=" + policy + "]"; + } + + @Override + public String getID() { + return policy.getId(); + } + } + + @FunctionalInterface + private interface EdgeWrapper extends Serializable{ + public String getID(); + + } + + private static class TriggerEdgeWrapper implements EdgeWrapper { + private static final long serialVersionUID = 2678151552623278863L; + private String trigger; + + public TriggerEdgeWrapper(String trigger) { + this.trigger = trigger; + } + + @Override + public String getID() { + return trigger; + } + + @Override + public String toString() { + return "TriggerEdgeWrapper [trigger=" + trigger + "]"; + } + + } + + private static class PolicyResultEdgeWrapper implements EdgeWrapper { + private static final long serialVersionUID = 6078569477021558310L; + private PolicyResult policyResult; + + public PolicyResultEdgeWrapper(PolicyResult policyResult) { + super(); + this.policyResult = policyResult; + } + + @Override + public String toString() { + return "PolicyResultEdgeWrapper [policyResult=" + policyResult + "]"; + } + + @Override + public String getID() { + return policyResult.toString(); + } + + + } + + private static class FinalResultEdgeWrapper implements EdgeWrapper { + private static final long serialVersionUID = -1486381946896779840L; + private FinalResult finalResult; + public FinalResultEdgeWrapper(FinalResult result) { + this.finalResult = result; + } + + @Override + public String toString() { + return "FinalResultEdgeWrapper [finalResult=" + finalResult + "]"; + } + + @Override + public String getID() { + return finalResult.toString(); + } + } + + + private static class LabeledEdge extends DefaultEdge { + private static final long serialVersionUID = 579384429573385524L; + + private NodeWrapper from; + private NodeWrapper to; + private EdgeWrapper edge; + + public LabeledEdge(NodeWrapper from, NodeWrapper to, EdgeWrapper edge) { + this.from = from; + this.to = to; + this.edge = edge; + } + + @SuppressWarnings("unused") + public NodeWrapper from() { + return from; + } + + @SuppressWarnings("unused") + public NodeWrapper to() { + return to; + } + + @SuppressWarnings("unused") + public EdgeWrapper edge() { + return edge; + } + + @Override + public String toString() { + return "LabeledEdge [from=" + from + ", to=" + to + ", edge=" + edge + "]"; + } + } + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerCallback.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerCallback.java new file mode 100644 index 000000000..ab4bf5e1a --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerCallback.java @@ -0,0 +1,29 @@ +/*- + * ============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.controlloop.compiler; + +public interface ControlLoopCompilerCallback { + + public boolean onWarning(String message); + + public boolean onError(String message); + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java new file mode 100644 index 000000000..de5b47641 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/guard/compiler/ControlLoopGuardCompiler.java @@ -0,0 +1,133 @@ +/*- + * ============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.controlloop.guard.compiler; + + +import java.io.InputStream; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.onap.policy.controlloop.compiler.CompilerException; +import org.onap.policy.controlloop.compiler.ControlLoopCompilerCallback; +import org.onap.policy.controlloop.policy.guard.Constraint; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; +import org.onap.policy.controlloop.policy.guard.GuardPolicy; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +public class ControlLoopGuardCompiler { + + private ControlLoopGuardCompiler(){ + // Private Constructor + } + + public static ControlLoopGuard compile(ControlLoopGuard cLGuard, ControlLoopCompilerCallback callback) throws CompilerException { + // + // Ensure ControlLoopGuard has at least one guard policies + // + validateControlLoopGuard(cLGuard, callback); + // + // Ensure each guard policy has at least one constraints and all guard policies are unique + // + validateGuardPolicies(cLGuard.getGuards(), callback); + // + // Ensure constraints for each guard policy are unique + // + validateConstraints(cLGuard.getGuards(), callback); + + return cLGuard; + } + + public static ControlLoopGuard compile(InputStream yamlSpecification, ControlLoopCompilerCallback callback) throws CompilerException { + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(yamlSpecification); + if (obj == null) { + throw new CompilerException("Could not parse yaml specification."); + } + if (! (obj instanceof ControlLoopGuard)) { + throw new CompilerException("Yaml could not parse specification into required ControlLoopGuard object"); + } + return ControlLoopGuardCompiler.compile((ControlLoopGuard) obj, callback); + } + + private static void validateControlLoopGuard(ControlLoopGuard cLGuard, ControlLoopCompilerCallback callback) throws CompilerException { + if (cLGuard == null) { + if (callback != null) { + callback.onError("ControlLoop Guard cannot be null"); + } + throw new CompilerException("ControlLoop Guard cannot be null"); + } + if (cLGuard.getGuard() == null && callback != null) { + callback.onError("Guard version cannot be null"); + } + if (cLGuard.getGuards() == null) { + if (callback != null) { + callback.onError("ControlLoop Guard should have at least one guard policies"); + } + } else if (cLGuard.getGuards().isEmpty() && callback != null) { + callback.onError("ControlLoop Guard should have at least one guard policies"); + } + } + + private static void validateGuardPolicies(List policies, ControlLoopCompilerCallback callback) throws CompilerException { + if (policies == null) { + if (callback != null) { + callback.onError("Guard policies should not be null"); + } + throw new CompilerException("Guard policies should not be null"); + } + // + // Ensure all guard policies are unique + // + Set newSet = new HashSet<>(policies); + if (newSet.size() != policies.size() && callback != null) { + callback.onWarning("There are duplicate guard policies"); + } + // + // Ensure each guard policy has at least one constraints + // + for (GuardPolicy policy : policies) { + if (policy.getLimit_constraints() == null || policy.getLimit_constraints().isEmpty()) { + if (callback != null) { + callback.onError("Guard policy " + policy.getName() + " does not have any limit constraint"); + } + throw new CompilerException("Guard policy " + policy.getName() + " does not have any limit constraint"); + } + } + } + + private static void validateConstraints(List policies, ControlLoopCompilerCallback callback) throws CompilerException { + if (policies == null) { + if (callback != null) { + callback.onError("Guard policies should not be null"); + } + throw new CompilerException("Guard policies should not be null"); + } + for (GuardPolicy policy : policies) { + Set newSet = new HashSet<>(policy.getLimit_constraints()); + if (newSet.size() != policy.getLimit_constraints().size() && callback != null) { + callback.onWarning("Guard policy " + policy.getName() + " has duplicate limit constraints"); + } + } + } + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java new file mode 100644 index 000000000..3d45c21ba --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/ControlLoop.java @@ -0,0 +1,189 @@ +/*- + * ============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.controlloop.policy; + +import java.util.LinkedList; +import java.util.List; + +import org.onap.policy.asdc.Resource; +import org.onap.policy.asdc.Service; + +public class ControlLoop { + + private static String VERSION = "2.0.0"; + + private String controlLoopName; + private String version = VERSION; + private List services; + private List resources; + private String trigger_policy = FinalResult.FINAL_OPENLOOP.toString(); + private Integer timeout; + private Boolean abatement = false; + + public ControlLoop() { + // Empty Constructor. + } + + public static String getVERSION(){ + return ControlLoop.VERSION; + } + + public String getControlLoopName() { + return controlLoopName; + } + + public void setControlLoopName(String controlLoopName) { + this.controlLoopName = controlLoopName; + } + + public List getServices() { + return services; + } + + public void setServices(List services) { + this.services = services; + } + + public List getResources() { + return resources; + } + + public void setResources(List resources) { + this.resources = resources; + } + + public String getTrigger_policy() { + return trigger_policy; + } + + public void setTrigger_policy(String trigger_policy) { + this.trigger_policy = trigger_policy; + } + + public Integer getTimeout() { + return timeout; + } + + public void setTimeout(Integer timeout) { + this.timeout = timeout; + } + + public Boolean getAbatement() { + return abatement; + } + + public void setAbatement(Boolean abatement) { + this.abatement = abatement; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version){ + this.version = version; + } + + public ControlLoop(ControlLoop controlLoop) { + this.controlLoopName = controlLoop.controlLoopName; + this.services = new LinkedList<>(); + if (controlLoop.services != null) { + for (Service service : controlLoop.services) { + this.services.add(service); + } + } + this.resources = new LinkedList<>(); + if (controlLoop.resources != null) { + for (Resource resource: controlLoop.resources) { + this.resources.add(resource); + } + } + this.trigger_policy = controlLoop.trigger_policy; + this.timeout = controlLoop.timeout; + this.abatement = controlLoop.abatement; + } + @Override + public String toString() { + return "ControlLoop [controlLoopName=" + controlLoopName + ", version=" + version + ", services=" + services + + ", resources=" + resources + ", trigger_policy=" + trigger_policy + ", timeout=" + + timeout + ", abatement=" + abatement + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((controlLoopName == null) ? 0 : controlLoopName.hashCode()); + result = prime * result + ((resources == null) ? 0 : resources.hashCode()); + result = prime * result + ((services == null) ? 0 : services.hashCode()); + result = prime * result + ((timeout == null) ? 0 : timeout.hashCode()); + result = prime * result + ((trigger_policy == null) ? 0 : trigger_policy.hashCode()); + result = prime * result + ((version == null) ? 0 : version.hashCode()); + result = prime * result + ((abatement == null) ? 0 : abatement.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ControlLoop other = (ControlLoop) obj; + if (controlLoopName == null) { + if (other.controlLoopName != null) + return false; + } else if (!controlLoopName.equals(other.controlLoopName)) + return false; + if (resources == null) { + if (other.resources != null) + return false; + } else if (!resources.equals(other.resources)) + return false; + if (services == null) { + if (other.services != null) + return false; + } else if (!services.equals(other.services)) + return false; + if (timeout == null) { + if (other.timeout != null) + return false; + } else if (!timeout.equals(other.timeout)) + return false; + if (trigger_policy == null) { + if (other.trigger_policy != null) + return false; + } else if (!trigger_policy.equals(other.trigger_policy)) + return false; + if (version == null) { + if (other.version != null) + return false; + } else if (!version.equals(other.version)) + return false; + if (abatement == null) { + if (other.abatement != null) + return false; + } else if (!abatement.equals(other.abatement)) + return false; + return true; + } + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java new file mode 100644 index 000000000..712a441c7 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/ControlLoopPolicy.java @@ -0,0 +1,83 @@ +/*- + * ============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.controlloop.policy; + +import java.util.List; + +public class ControlLoopPolicy { + + private ControlLoop controlLoop; + + private List policies; + + public ControlLoop getControlLoop() { + return controlLoop; + } + + public void setControlLoop(ControlLoop controlLoop) { + this.controlLoop = controlLoop; + } + + public List getPolicies() { + return policies; + } + + public void setPolicies(List policies) { + this.policies = policies; + } + + @Override + public String toString() { + return "ControlLoopPolicy [controlLoop=" + controlLoop + ", policies=" + policies + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((controlLoop == null) ? 0 : controlLoop.hashCode()); + result = prime * result + ((policies == null) ? 0 : policies.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ControlLoopPolicy other = (ControlLoopPolicy) obj; + if (controlLoop == null) { + if (other.controlLoop != null) + return false; + } else if (!controlLoop.equals(other.controlLoop)) + return false; + if (policies == null) { + if (other.policies != null) + return false; + } else if (!policies.equals(other.policies)) + return false; + return true; + } + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/FinalResult.java new file mode 100644 index 000000000..cad99452d --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/FinalResult.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.controlloop.policy; + +public enum FinalResult { + /** + * The Control Loop Policy successfully completed its Operations. + */ + FINAL_SUCCESS("Final_Success"), + /** + * The Control Loop Policy was an Open Loop and is finished. + */ + FINAL_OPENLOOP("Final_OpenLoop"), + /** + * The Control Loop Policy failed in its last Operation Policy. NOTE: Previous Operation Policies may have been successful. + */ + FINAL_FAILURE("Final_Failure"), + /** + * The Control Loop Policy failed because the overall timeout was met. + */ + FINAL_FAILURE_TIMEOUT("Final_Failure_Timeout"), + /** + * The Control Loop Policy failed because an Operation Policy met its retry limit. + */ + FINAL_FAILURE_RETRIES("Final_Failure_Retries"), + /** + * The Control Loop Policy failed due to an exception. + */ + FINAL_FAILURE_EXCEPTION("Final_Failure_Exception"), + /** + * The Control Loop Policy failed due to guard denied + */ + FINAL_FAILURE_GUARD("Final_Failure_Guard") + ; + + String result; + + private FinalResult(String result) { + this.result = result; + } + + public static FinalResult toResult(String result) { + if (result.equalsIgnoreCase(FINAL_SUCCESS.toString())) { + return FINAL_SUCCESS; + } + if (result.equalsIgnoreCase(FINAL_OPENLOOP.toString())) { + return FINAL_OPENLOOP; + } + if (result.equalsIgnoreCase(FINAL_FAILURE.toString())) { + return FINAL_FAILURE; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_TIMEOUT.toString())) { + return FINAL_FAILURE_TIMEOUT; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_RETRIES.toString())) { + return FINAL_FAILURE_RETRIES; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_EXCEPTION.toString())) { + return FINAL_FAILURE_EXCEPTION; + } + if (result.equalsIgnoreCase(FINAL_FAILURE_GUARD.toString())) { + return FINAL_FAILURE_GUARD; + } + return null; + } + + public static boolean isResult(String result, FinalResult finalResult) { + FinalResult toResult = FinalResult.toResult(result); + if (toResult == null) { + return false; + } + return toResult.equals(finalResult); + } + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.java new file mode 100644 index 000000000..b27d72ed6 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/OperationsAccumulateParams.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.controlloop.policy; + +import java.io.Serializable; + +public class OperationsAccumulateParams implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -3597358159130168247L; + + private String period; + private Integer limit; + + public OperationsAccumulateParams() { + // Does Nothing + } + + public OperationsAccumulateParams(OperationsAccumulateParams ops) { + this.period = ops.period; + this.limit = ops.limit; + } + + public OperationsAccumulateParams(String period, Integer limit) { + this.period = period; + this.limit = limit; + } + + public String getPeriod() { + return period; + } + + public void setPeriod(String period) { + this.period = period; + } + + public Integer getLimit() { + return limit; + } + + public void setLimit(Integer limit) { + this.limit = limit; + } + + @Override + public String toString() { + return "OperationsAccumulateParams [period=" + period + ", limit=" + limit + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((period == null) ? 0 : period.hashCode()); + result = prime * result + ((limit == null) ? 0 : limit.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OperationsAccumulateParams other = (OperationsAccumulateParams) obj; + if (period == null) { + if (other.period != null) + return false; + } else if (!period.equals(other.period)) + return false; + if (limit == null) { + if (other.limit != null) + return false; + } else if (!limit.equals(other.limit)) + return false; + return true; + } + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/Policy.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/Policy.java new file mode 100644 index 000000000..96799e964 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/Policy.java @@ -0,0 +1,353 @@ +/*- + * ============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.controlloop.policy; + +import java.util.Collections; +import java.util.Map; +import java.util.UUID; + +public class Policy { + + private String id = UUID.randomUUID().toString(); + private String name; + private String description; + private String actor; + private String recipe; + private Map payload; + private Target target; + private OperationsAccumulateParams operationsAccumulateParams; + private Integer retry = 0; + private Integer timeout = 300; + private String success = FinalResult.FINAL_SUCCESS.toString(); + private String failure = FinalResult.FINAL_FAILURE.toString(); + private String failure_retries = FinalResult.FINAL_FAILURE_RETRIES.toString(); + private String failure_timeout = FinalResult.FINAL_FAILURE_TIMEOUT.toString(); + private String failure_exception = FinalResult.FINAL_FAILURE_EXCEPTION.toString(); + private String failure_guard = FinalResult.FINAL_FAILURE_GUARD.toString(); + + + public Policy() { + //Does Nothing Empty Constructor + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + 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; + } + + public String getActor() { + return actor; + } + + public void setActor(String actor) { + this.actor = actor; + } + + public String getRecipe() { + return recipe; + } + + public void setRecipe(String recipe) { + this.recipe = recipe; + } + + public Map getPayload() { + return payload; + } + + public void setPayload(Map payload) { + this.payload = payload; + } + + public Target getTarget() { + return target; + } + + public void setTarget(Target target) { + this.target = target; + } + + public OperationsAccumulateParams getOperationsAccumulateParams() { + return operationsAccumulateParams; + } + + public void setOperationsAccumulateParams(OperationsAccumulateParams operationsAccumulateParams) { + this.operationsAccumulateParams = operationsAccumulateParams; + } + + public Integer getRetry() { + return retry; + } + + public void setRetry(Integer retry) { + this.retry = retry; + } + + public Integer getTimeout() { + return timeout; + } + + public void setTimeout(Integer timeout) { + this.timeout = timeout; + } + + public String getSuccess() { + return success; + } + + public void setSuccess(String success) { + this.success = success; + } + + public String getFailure() { + return failure; + } + + public void setFailure(String failure) { + this.failure = failure; + } + + public String getFailure_retries() { + return failure_retries; + } + + public void setFailure_retries(String failure_retries) { + this.failure_retries = failure_retries; + } + + public String getFailure_timeout() { + return failure_timeout; + } + + public void setFailure_timeout(String failure_timeout) { + this.failure_timeout = failure_timeout; + } + + public String getFailure_exception() { + return failure_exception; + } + + public void setFailure_exception(String failure_exception) { + this.failure_exception = failure_exception; + } + + public String getFailure_guard() { + return failure_guard; + } + + public void setFailure_guard(String failure_guard) { + this.failure_guard = failure_guard; + } + + public Policy(String id) { + this.id = id; + } + + public Policy(String name, String actor, String recipe, Map payload, Target target) { + this.name = name; + this.actor = actor; + this.recipe = recipe; + this.target = target; + if (payload != null) { + this.payload = Collections.unmodifiableMap(payload); + } + } + + public Policy(String name, String actor, String recipe, Map payload, Target target, Integer retries, Integer timeout) { + this(name, actor, recipe, payload, target); + this.retry = retries; + this.timeout = timeout; + } + + public Policy(String id, String name, String description, String actor, Map payload, Target target, String recipe, Integer retries, Integer timeout) { + this(name, actor, recipe, payload, target, retries, timeout); + this.id = id; + this.description = description; + } + + public Policy(Policy policy) { + this.id = policy.id; + this.name = policy.name; + this.description = policy.description; + this.actor = policy.actor; + this.recipe = policy.recipe; + if (policy.payload != null) { + this.payload = Collections.unmodifiableMap(policy.payload); + } + this.target = policy.target; + this.operationsAccumulateParams = policy.operationsAccumulateParams; + this.retry = policy.retry; + this.timeout = policy.timeout; + this.success = policy.success; + this.failure = policy.failure; + this.failure_exception = policy.failure_exception; + this.failure_guard = policy.failure_guard; + this.failure_retries = policy.failure_retries; + this.failure_timeout = policy.failure_timeout; + } + + public boolean isValid() { + if(id==null || name==null || actor==null|| recipe==null || target==null){ + return false; + } + return true; + } + + @Override + public String toString() { + return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", actor=" + actor + ", recipe=" + + recipe + ", payload=" + payload + ", target=" + target + ", operationsAccumulateParams=" + operationsAccumulateParams + ", retry=" + retry + ", timeout=" + timeout + + ", success=" + success + ", failure=" + failure + ", failure_retries=" + failure_retries + + ", failure_timeout=" + failure_timeout + ", failure_exception=" + failure_exception + ", failure_guard=" + failure_guard + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((actor == null) ? 0 : actor.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((failure == null) ? 0 : failure.hashCode()); + result = prime * result + ((failure_exception == null) ? 0 : failure_exception.hashCode()); + result = prime * result + ((failure_guard == null) ? 0 : failure_guard.hashCode()); + result = prime * result + ((failure_retries == null) ? 0 : failure_retries.hashCode()); + result = prime * result + ((failure_timeout == null) ? 0 : failure_timeout.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((payload == null) ? 0 : payload.hashCode()); + result = prime * result + ((recipe == null) ? 0 : recipe.hashCode()); + result = prime * result + ((retry == null) ? 0 : retry.hashCode()); + result = prime * result + ((success == null) ? 0 : success.hashCode()); + result = prime * result + ((target == null) ? 0 : target.hashCode()); + result = prime * result + ((operationsAccumulateParams == null) ? 0 : operationsAccumulateParams.hashCode()); + result = prime * result + ((timeout == null) ? 0 : timeout.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Policy other = (Policy) obj; + if (actor != other.actor) + return false; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (failure == null) { + if (other.failure != null) + return false; + } else if (!failure.equals(other.failure)) + return false; + if (failure_exception == null) { + if (other.failure_exception != null) + return false; + } else if (!failure_exception.equals(other.failure_exception)) + return false; + if (failure_guard == null) { + if (other.failure_guard != null) + return false; + } else if (!failure_guard.equals(other.failure_guard)) + return false; + if (failure_retries == null) { + if (other.failure_retries != null) + return false; + } else if (!failure_retries.equals(other.failure_retries)) + return false; + if (failure_timeout == null) { + if (other.failure_timeout != null) + return false; + } else if (!failure_timeout.equals(other.failure_timeout)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (payload == null) { + if (other.payload != null) + return false; + } else if (!payload.equals(other.payload)) + return false; + if (recipe == null) { + if (other.recipe != null) + return false; + } else if (!recipe.equals(other.recipe)) + return false; + if (retry == null) { + if (other.retry != null) + return false; + } else if (!retry.equals(other.retry)) + return false; + if (success == null) { + if (other.success != null) + return false; + } else if (!success.equals(other.success)) + return false; + if (operationsAccumulateParams == null) { + if (other.operationsAccumulateParams != null) + return false; + } else if (!operationsAccumulateParams.equals(other.operationsAccumulateParams)) + return false; + if (target == null) { + if (other.target != null) + return false; + } else if (!target.equals(other.target)) + return false; + if (timeout == null) { + if (other.timeout != null) + return false; + } else if (!timeout.equals(other.timeout)) + return false; + return true; + } + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java new file mode 100644 index 000000000..5ff2d684a --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/PolicyResult.java @@ -0,0 +1,82 @@ +/*- + * ============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.controlloop.policy; + +public enum PolicyResult { + /** + * Operation was successful. + */ + SUCCESS("Success"), + /** + * Operation failed. + */ + FAILURE("Failure"), + /** + * Operation failed due to maximum retries being met. + */ + FAILURE_RETRIES("Failure_Retries"), + /** + * Operation failed due to timeout occurring. + */ + FAILURE_TIMEOUT("Failure_Timeout"), + /** + * Operation failed due to an exception. + */ + FAILURE_EXCEPTION("Failure_Exception"), + /** + * Operation failed since Guard did not permit. + */ + FAILURE_GUARD("Failure_Guard") + ; + + private String result; + + private PolicyResult(String result) { + this.result = result; + } + + @Override + public String toString() { + return this.result; + } + + public static PolicyResult toResult(String result) { + if (result.equalsIgnoreCase(SUCCESS.toString())) { + return SUCCESS; + } + if (result.equalsIgnoreCase(FAILURE.toString())) { + return FAILURE; + } + if (result.equalsIgnoreCase(FAILURE_RETRIES.toString())) { + return FAILURE_RETRIES; + } + if (result.equalsIgnoreCase(FAILURE_TIMEOUT.toString())) { + return FAILURE_TIMEOUT; + } + if (result.equalsIgnoreCase(FAILURE_EXCEPTION.toString())) { + return FAILURE_EXCEPTION; + } + if (result.equalsIgnoreCase(FAILURE_GUARD.toString())) { + return FAILURE_GUARD; + } + return null; + } + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/Target.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/Target.java new file mode 100644 index 000000000..2a8817d10 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/Target.java @@ -0,0 +1,106 @@ +/*- + * ============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.controlloop.policy; + +import java.io.Serializable; + +public class Target implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 2180988443264988319L; + + private String resourceID; + private TargetType type; + + public Target() { + //Does Nothing Empty Constructor + } + + public String getResourceID() { + return resourceID; + } + + public void setResourceID(String resourceID) { + this.resourceID = resourceID; + } + + public TargetType getType() { + return type; + } + + public void setType(TargetType type) { + this.type = type; + } + + public Target(TargetType type) { + this.type = type; + } + + public Target(String resourceID) { + this.resourceID = resourceID; + } + + public Target(TargetType type, String resourceID) { + this.type = type; + this.resourceID = resourceID; + } + + public Target(Target target) { + this.type = target.type; + this.resourceID = target.resourceID; + } + + @Override + public String toString() { + return "Target [type=" + type + ", resourceID=" + resourceID + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((type == null) ? 0 : type.hashCode()); + result = prime * result + ((resourceID == null) ? 0 : resourceID.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Target other = (Target) obj; + if (type == null) { + if (other.type != null) + return false; + } else if (!type.equals(other.type)) + return false; + if (resourceID == null) { + if (other.resourceID != null) + return false; + } else if (!resourceID.equals(other.resourceID)) + return false; + return true; + } +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/TargetType.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/TargetType.java new file mode 100644 index 000000000..875ca2e1e --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/TargetType.java @@ -0,0 +1,39 @@ +/*- + * ============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.controlloop.policy; + +public enum TargetType { + VM("VM"), + PNF("PNF"), + VFC("VFC") + ; + + private String target; + + private TargetType(String targetType) { + this.target = targetType; + } + + @Override + public String toString() { + return this.target; + } + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/BuilderException.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/BuilderException.java new file mode 100644 index 000000000..7cf2f4900 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/BuilderException.java @@ -0,0 +1,31 @@ +/*- + * ============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.controlloop.policy.builder; + +public class BuilderException extends Exception { + + private static final long serialVersionUID = 610064813684337895L; + + public BuilderException(String string) { + super(string); + } + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java new file mode 100644 index 000000000..93ecbc62e --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/ControlLoopPolicyBuilder.java @@ -0,0 +1,287 @@ +/*- + * ============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.controlloop.policy.builder; + +import java.util.Map; + +import org.onap.policy.asdc.Resource; +import org.onap.policy.asdc.Service; +import org.onap.policy.controlloop.policy.ControlLoop; +import org.onap.policy.controlloop.policy.OperationsAccumulateParams; +import org.onap.policy.controlloop.policy.Policy; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.controlloop.policy.Target; +import org.onap.policy.controlloop.policy.builder.impl.ControlLoopPolicyBuilderImpl; + +public interface ControlLoopPolicyBuilder { + + /** + * Adds one or more services to the ControlLoop + * + * + * @param service + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException; + + /** + * @param services + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException; + + /** + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder removeAllServices() throws BuilderException; + + /** + * Adds one or more resources to the ControlLoop + * + * + * @param resource + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException; + + /** + * @param resources + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException; + + /** + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder removeAllResources() throws BuilderException; + + /** + * @param abatement + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException; + + + /** + * Sets the overall timeout value for the Control Loop. If any operational policies have retries and timeouts, + * then this overall timeout value should exceed all those values. + * + * @param timeout + * @return + * @throws BuilderException + */ + public ControlLoopPolicyBuilder setTimeout(Integer timeout) throws BuilderException; + + /** + * Scans the operational policies and calculate an minimum overall timeout for the Control Loop. + * + * + * @return Integer + */ + public Integer calculateTimeout(); + + /** + * Sets the initial trigger policy when a DCAE Closed Loop Event arrives in the ONAP Policy Platform. + * + * + * @param name + * @param description + * @param actor + * @param target + * @param recipe + * @param retries + * @param timeout + * @return Policy + * @throws BuilderException + */ + public Policy setTriggerPolicy(String name, String description, String actor, Target target, String recipe, Map payload, Integer retries, Integer timeout) throws BuilderException; + + /** + * + * Changes the trigger policy to point to another existing Policy. + * + * + * @param id + * @return ControlLoop + * @throws BuilderException + */ + public ControlLoop setTriggerPolicy(String id) throws BuilderException; + + /** + * @return + */ + public boolean isOpenLoop(); + + /** + * @return + * @throws BuilderException + */ + public Policy getTriggerPolicy() throws BuilderException; + + /** + * Simply returns a copy of the ControlLoop information. + * + * + * @return ControlLoop + */ + public ControlLoop getControlLoop(); + + /** + * Creates a policy that is chained to the result of another Policy. + * + * + * @param name + * @param description + * @param actor + * @param target + * @param recipe + * @param retries + * @param timeout + * @param policyID + * @param results + * @return + * @throws BuilderException + */ + public Policy setPolicyForPolicyResult(String name, String description, String actor, + Target target, String recipe, Map payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) throws BuilderException; + + + /** + * Sets the policy result(s) to an existing Operational Policy. + * + * + * @param policyResultID + * @param policyID + * @param results + * @return + * @throws BuilderException + */ + public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results) throws BuilderException; + + /** + * Removes an Operational Policy. Be mindful that if any other Operational Policies have results that point to this policy, any + * policies that have results pointing to this policy will have their result reset to the appropriate default FINAL_* result. + * + * + * @param policyID + * @return + * @throws BuilderException + */ + public boolean removePolicy(String policyID) throws BuilderException; + + /** + * Resets a policy's results to defualt FINAL_* codes. + * + * + * @return Policy + * @throws BuilderException - Policy does not exist + */ + public Policy resetPolicyResults(String policyID) throws BuilderException; + + /** + * Removes all existing Operational Policies and reverts back to an Open Loop. + * + * @return + */ + public ControlLoopPolicyBuilder removeAllPolicies(); + + /** + * Adds an operationsAccumulateParams to an existing operational policy + * + * @return Policy + * @throws BuilderException - Policy does not exist + */ + public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException; + + /** + * This will compile and build the YAML specification for the Control Loop Policy. Please iterate the Results object for details. + * The Results object will contains warnings and errors. If the specification compiled successfully, you will be able to retrieve the + * YAML. + * + * @return Results + */ + public Results buildSpecification(); + + /** + * The Factory is used to build a ControlLoopPolicyBuilder implementation. + * + * @author pameladragosh + * + */ + public static class Factory { + private Factory(){ + // Private Constructor. + } + + /** + * Builds a basic Control Loop with an overall timeout. Use this method if you wish to create an OpenLoop, or if you + * want to interactively build a Closed Loop. + * + * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. + * @param timeout - Overall timeout for the Closed Loop to execute. + * @return ControlLoopPolicyBuilder object + * @throws BuilderException + */ + public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout) throws BuilderException { + return new ControlLoopPolicyBuilderImpl(controlLoopName, timeout); + } + + /** + * Build a Control Loop for a resource and services associated with the resource. + * + * @param controlLoopName - Per Closed Loop AID v1.0, unique string for the closed loop. + * @param timeout - Overall timeout for the Closed Loop to execute. + * @param resource - Resource this closed loop is for. Should come from ASDC, but if not available use resourceName to distinguish. + * @param services - Zero or more services associated with this resource. Should come from ASDC, but if not available use serviceName to distinguish. + * @return ControlLoopPolicyBuilder object + * @throws BuilderException + */ + public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout, Resource resource, Service... services) throws BuilderException { + + ControlLoopPolicyBuilder builder = new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, resource, services); + + return builder; + } + + /** + * @param controlLoopName + * @param timeout + * @param service + * @param resources + * @return + * @throws BuilderException + */ + public static ControlLoopPolicyBuilder buildControlLoop (String controlLoopName, Integer timeout, Service service, Resource... resources) throws BuilderException { + + ControlLoopPolicyBuilder builder = new ControlLoopPolicyBuilderImpl(controlLoopName, timeout, service, resources); + + return builder; + } + } + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/Message.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/Message.java new file mode 100644 index 000000000..4bf2665b3 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/Message.java @@ -0,0 +1,29 @@ +/*- + * ============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.controlloop.policy.builder; + +public interface Message { + + public String getMessage(); + + public MessageLevel getLevel(); + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/MessageLevel.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/MessageLevel.java new file mode 100644 index 000000000..37ecfa17c --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/MessageLevel.java @@ -0,0 +1,29 @@ +/*- + * ============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.controlloop.policy.builder; + +public enum MessageLevel { + INFO, + WARNING, + ERROR, + EXCEPTION + ; + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/Results.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/Results.java new file mode 100644 index 000000000..37bd93215 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/Results.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.controlloop.policy.builder; + +import java.util.List; + +public interface Results { + + public List getMessages(); + + public String getSpecification(); + + public boolean isValid(); + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java new file mode 100644 index 000000000..dae56f32c --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ControlLoopPolicyBuilderImpl.java @@ -0,0 +1,496 @@ +/*- + * ============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.controlloop.policy.builder.impl; + +import java.util.LinkedList; +import java.util.Map; +import java.util.UUID; + +import org.onap.policy.asdc.Resource; +import org.onap.policy.asdc.Service; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.controlloop.compiler.CompilerException; +import org.onap.policy.controlloop.compiler.ControlLoopCompiler; +import org.onap.policy.controlloop.compiler.ControlLoopCompilerCallback; +import org.onap.policy.controlloop.policy.ControlLoop; +import org.onap.policy.controlloop.policy.ControlLoopPolicy; +import org.onap.policy.controlloop.policy.FinalResult; +import org.onap.policy.controlloop.policy.OperationsAccumulateParams; +import org.onap.policy.controlloop.policy.Policy; +import org.onap.policy.controlloop.policy.PolicyResult; +import org.onap.policy.controlloop.policy.Target; +import org.onap.policy.controlloop.policy.builder.BuilderException; +import org.onap.policy.controlloop.policy.builder.ControlLoopPolicyBuilder; +import org.onap.policy.controlloop.policy.builder.MessageLevel; +import org.onap.policy.controlloop.policy.builder.Results; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.Yaml; + +public class ControlLoopPolicyBuilderImpl implements ControlLoopPolicyBuilder { + private static Logger logger = FlexLogger.getLogger(ControlLoopPolicyBuilderImpl.class.getName()); + private ControlLoopPolicy policy; + + public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout) throws BuilderException { + policy = new ControlLoopPolicy(); + ControlLoop controlLoop = new ControlLoop(); + controlLoop.setControlLoopName(controlLoopName); + controlLoop.setTimeout(timeout); + policy.setControlLoop(controlLoop); + } + + public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Resource resource, Service... services) throws BuilderException { + this(controlLoopName, timeout); + this.addResource(resource); + this.addService(services); + } + + public ControlLoopPolicyBuilderImpl(String controlLoopName, Integer timeout, Service service, Resource[] resources) throws BuilderException { + this(controlLoopName, timeout); + this.addService(service); + this.addResource(resources); + } + + @Override + public ControlLoopPolicyBuilder addService(Service... services) throws BuilderException { + if (services == null) { + throw new BuilderException("Service must not be null"); + } + for (Service service : services) { + if (service.getServiceUUID() == null) { + if (service.getServiceName() == null || service.getServiceName().length() < 1) { + throw new BuilderException("Invalid service - need either a serviceUUID or serviceName"); + } + if(policy.getControlLoop().getServices()==null){ + policy.getControlLoop().setServices(new LinkedList<>()); + } + policy.getControlLoop().getServices().add(service); + } + } + return this; + } + + @Override + public ControlLoopPolicyBuilder removeService(Service... services) throws BuilderException { + if (services == null) { + throw new BuilderException("Service must not be null"); + } + if (policy.getControlLoop().getServices() == null) { + throw new BuilderException("No existing services to remove"); + } + for (Service service : services) { + if (service.getServiceUUID() == null) { + if (service.getServiceName() == null || service.getServiceName().length() < 1) { + throw new BuilderException("Invalid service - need either a serviceUUID or serviceName"); + } + } + boolean removed = policy.getControlLoop().getServices().remove(service); + if (!removed) { + throw new BuilderException("Unknown service " + service.getServiceName()); + } + } + return this; + } + + @Override + public ControlLoopPolicyBuilder removeAllServices() throws BuilderException { + policy.getControlLoop().getServices().clear(); + return this; + } + + + @Override + public ControlLoopPolicyBuilder addResource(Resource... resources) throws BuilderException { + if (resources == null) { + throw new BuilderException("resources must not be null"); + } + for (Resource resource : resources) { + if (resource.getResourceUUID() == null) { + if (resource.getResourceName() == null || resource.getResourceName().length() <= 0) { + throw new BuilderException("Invalid resource - need either resourceUUID or resourceName"); + } + } + if(policy.getControlLoop().getResources()==null){ + policy.getControlLoop().setResources(new LinkedList<>()); + } + policy.getControlLoop().getResources().add(resource); + } + return this; + } + + @Override + public ControlLoopPolicyBuilder setAbatement(Boolean abatement) throws BuilderException{ + if (abatement == null) { + throw new BuilderException("abatement must not be null"); + } + policy.getControlLoop().setAbatement(abatement); + return this; + } + + @Override + public ControlLoopPolicyBuilder setTimeout(Integer timeout) { + policy.getControlLoop().setTimeout(timeout); + return this; + } + + @Override + public Policy setTriggerPolicy(String name, String description, String actor, Target target, String recipe, + Map payload, Integer retries, Integer timeout) throws BuilderException { + + Policy trigger = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout); + + policy.getControlLoop().setTrigger_policy(trigger.getId()); + + this.addNewPolicy(trigger); + // + // Return a copy of the policy + // + return new Policy(trigger); + } + + @Override + public Policy setPolicyForPolicyResult(String name, String description, String actor, + Target target, String recipe, Map payload, Integer retries, Integer timeout, String policyID, PolicyResult... results) throws BuilderException { + // + // Find the existing policy + // + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException("Unknown policy " + policyID); + } + // + // Create the new Policy + // + Policy newPolicy = new Policy(UUID.randomUUID().toString(), name, description, actor, payload, target, recipe, retries, timeout); + // + // Connect the results + // + for (PolicyResult result : results) { + switch (result) { + case FAILURE: + existingPolicy.setFailure(newPolicy.getId()); + break; + case FAILURE_EXCEPTION: + existingPolicy.setFailure_exception(newPolicy.getId()); + break; + case FAILURE_RETRIES: + existingPolicy.setFailure_retries(newPolicy.getId()); + break; + case FAILURE_TIMEOUT: + existingPolicy.setFailure_timeout(newPolicy.getId()); + break; + case FAILURE_GUARD: + existingPolicy.setFailure_guard(newPolicy.getId()); + break; + case SUCCESS: + existingPolicy.setSuccess(newPolicy.getId()); + break; + default: + throw new BuilderException("Invalid PolicyResult " + result); + } + } + // + // Add it to our list + // + this.policy.getPolicies().add(newPolicy); + // + // Return a policy to them + // + return new Policy(newPolicy); + } + + private class BuilderCompilerCallback implements ControlLoopCompilerCallback { + + private ResultsImpl results = new ResultsImpl(); + + @Override + public boolean onWarning(String message) { + results.addMessage(new MessageImpl(message, MessageLevel.WARNING)); + return false; + } + + @Override + public boolean onError(String message) { + results.addMessage(new MessageImpl(message, MessageLevel.ERROR)); + return false; + } + } + + @Override + public Results buildSpecification() { + // + // Dump the specification + // + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + options.setPrettyFlow(true); + Yaml yaml = new Yaml(options); + String dumpedYaml = yaml.dump(policy); + // + // This is our callback class for our compiler + // + BuilderCompilerCallback callback = new BuilderCompilerCallback(); + // + // Compile it + // + try { + ControlLoopCompiler.compile(policy, callback); + } catch (CompilerException e) { + logger.error(e.getMessage() + e); + callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION)); + } + // + // Save the spec + // + callback.results.setSpecification(dumpedYaml); + return callback.results; + } + + private void addNewPolicy(Policy policy) { + if (this.policy.getPolicies() == null) { + this.policy.setPolicies(new LinkedList<>()); + } + this.policy.getPolicies().add(policy); + } + + private Policy findPolicy(String id) { + for (Policy policy : this.policy.getPolicies()) { + if (policy.getId().equals(id)) { + return policy; + } + } + return null; + } + + @Override + public ControlLoopPolicyBuilder removeResource(Resource... resources) throws BuilderException { + if (resources == null) { + throw new BuilderException("Resource must not be null"); + } + if (policy.getControlLoop().getResources() == null) { + throw new BuilderException("No existing resources to remove"); + } + for (Resource resource : resources) { + if (resource.getResourceUUID() == null) { + if (resource.getResourceName() == null || resource.getResourceName().length() < 1) { + throw new BuilderException("Invalid resource - need either a resourceUUID or resourceName"); + } + } + boolean removed = policy.getControlLoop().getResources().remove(resource); + if (!removed) { + throw new BuilderException("Unknown resource " + resource.getResourceName()); + } + } + return this; + } + + @Override + public ControlLoopPolicyBuilder removeAllResources() throws BuilderException { + policy.getControlLoop().getResources().clear(); + return this; + } + + @Override + public Integer calculateTimeout() { + int sum = 0; + for (Policy policy : this.policy.getPolicies()) { + sum += policy.getTimeout().intValue(); + } + return new Integer(sum); + } + + @Override + public ControlLoop setTriggerPolicy(String id) throws BuilderException { + if (id == null) { + throw new BuilderException("Id must not be null"); + } + Policy trigger = this.findPolicy(id); + if (trigger == null) { + throw new BuilderException("Unknown policy " + id); + } + else { + this.policy.getControlLoop().setTrigger_policy(id); + } + return new ControlLoop(this.policy.getControlLoop()); + } + + @Override + public boolean isOpenLoop() { + if (this.policy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())) { + return true; + } + else { + return false; + } + } + + @Override + public Policy getTriggerPolicy() throws BuilderException { + if (this.policy.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())) { + return null; + } + else { + Policy trigger = new Policy(this.findPolicy(this.policy.getControlLoop().getTrigger_policy())); + return trigger; + } + } + + @Override + public ControlLoop getControlLoop() { + ControlLoop loop = new ControlLoop(this.policy.getControlLoop()); + return loop; + } + + @Override + public Policy setPolicyForPolicyResult(String policyResultID, String policyID, PolicyResult... results) + throws BuilderException { + // + // Find the existing policy + // + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException(policyID + " does not exist"); + } + if (this.findPolicy(policyResultID) == null) { + throw new BuilderException("Operational policy " + policyResultID + " does not exist"); + } + // + // Connect the results + // + for (PolicyResult result : results) { + switch (result) { + case FAILURE: + existingPolicy.setFailure(policyResultID); + break; + case FAILURE_EXCEPTION: + existingPolicy.setFailure_exception(policyResultID); + break; + case FAILURE_RETRIES: + existingPolicy.setFailure_retries(policyResultID); + break; + case FAILURE_TIMEOUT: + existingPolicy.setFailure_timeout(policyResultID); + break; + case FAILURE_GUARD: + existingPolicy.setFailure_guard(policyResultID); + break; + case SUCCESS: + existingPolicy.setSuccess(policyResultID); + break; + default: + throw new BuilderException("Invalid PolicyResult " + result); + } + } + return new Policy(this.findPolicy(policyResultID)); + } + + @Override + public boolean removePolicy(String policyID) throws BuilderException { + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException("Unknown policy " + policyID); + } + // + // Check if the policy to remove is trigger_policy + // + if (this.policy.getControlLoop().getTrigger_policy().equals(policyID)) { + this.policy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString()); + } + else { + // + // Update policies + // + for (Policy policy : this.policy.getPolicies()) { + int index = this.policy.getPolicies().indexOf(policy); + if (policy.getSuccess().equals(policyID)) { + policy.setSuccess(FinalResult.FINAL_SUCCESS.toString()); + } + if (policy.getFailure().equals(policyID)) { + policy.setFailure(FinalResult.FINAL_FAILURE.toString()); + } + if (policy.getFailure_retries().equals(policyID)) { + policy.setFailure_retries(FinalResult.FINAL_FAILURE_RETRIES.toString()); + } + if (policy.getFailure_timeout().equals(policyID)) { + policy.setFailure_timeout(FinalResult.FINAL_FAILURE_TIMEOUT.toString()); + } + if (policy.getFailure_exception().equals(policyID)) { + policy.setFailure_exception(FinalResult.FINAL_FAILURE_EXCEPTION.toString()); + } + if (policy.getFailure_guard().equals(policyID)) { + policy.setFailure_guard(FinalResult.FINAL_FAILURE_GUARD.toString()); + } + this.policy.getPolicies().set(index, policy); + } + } + // + // remove the policy + // + boolean removed = this.policy.getPolicies().remove(existingPolicy); + return removed; + } + + @Override + public Policy resetPolicyResults(String policyID) throws BuilderException { + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException("Unknown policy " + policyID); + } + // + // reset policy results + // + existingPolicy.setSuccess(FinalResult.FINAL_SUCCESS.toString()); + existingPolicy.setFailure(FinalResult.FINAL_FAILURE.toString()); + existingPolicy.setFailure_retries(FinalResult.FINAL_FAILURE_RETRIES.toString()); + existingPolicy.setFailure_timeout(FinalResult.FINAL_FAILURE_TIMEOUT.toString()); + existingPolicy.setFailure_exception(FinalResult.FINAL_FAILURE_EXCEPTION.toString()); + existingPolicy.setFailure_guard(FinalResult.FINAL_FAILURE_GUARD.toString()); + return new Policy(existingPolicy); + } + + @Override + public ControlLoopPolicyBuilder removeAllPolicies() { + // + // Remove all existing operational policies + // + this.policy.getPolicies().clear(); + // + // Revert controlLoop back to an open loop + // + this.policy.getControlLoop().setTrigger_policy(FinalResult.FINAL_OPENLOOP.toString()); + return this; + } + + @Override + public Policy addOperationsAccumulateParams(String policyID, OperationsAccumulateParams operationsAccumulateParams) throws BuilderException { + Policy existingPolicy = this.findPolicy(policyID); + if (existingPolicy == null) { + throw new BuilderException("Unknown policy " + policyID); + } + // + // Add operationsAccumulateParams to existingPolicy + // + existingPolicy.setOperationsAccumulateParams(operationsAccumulateParams); + return new Policy(existingPolicy); + } + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/impl/MessageImpl.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/impl/MessageImpl.java new file mode 100644 index 000000000..4d3aa7091 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/impl/MessageImpl.java @@ -0,0 +1,46 @@ +/*- + * ============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.controlloop.policy.builder.impl; + +import org.onap.policy.controlloop.policy.builder.Message; +import org.onap.policy.controlloop.policy.builder.MessageLevel; + +public class MessageImpl implements Message { + + private String message; + private MessageLevel level; + + public MessageImpl(String message, MessageLevel level) { + this.message = message; + this.level = level; + } + + @Override + public String getMessage() { + return message; + } + + @Override + public MessageLevel getLevel() { + return level; + } + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ResultsImpl.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ResultsImpl.java new file mode 100644 index 000000000..18732f414 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/builder/impl/ResultsImpl.java @@ -0,0 +1,55 @@ +/*- + * ============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.controlloop.policy.builder.impl; + +import java.util.LinkedList; +import java.util.List; + +import org.onap.policy.controlloop.policy.builder.Message; +import org.onap.policy.controlloop.policy.builder.Results; + +public class ResultsImpl implements Results { + + private String specification; + private List messages = new LinkedList<>(); + + @Override + public List getMessages() { + return messages; + } + + @Override + public String getSpecification() { + return specification; + } + + @Override + public boolean isValid() { + return this.specification != null; + } + + public void addMessage(Message message) { + this.messages.add(message); + } + + public void setSpecification(String spec) { + this.specification = spec; + } +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java new file mode 100644 index 000000000..ac3dbb03f --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/Constraint.java @@ -0,0 +1,171 @@ +/*- + * ============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.controlloop.policy.guard; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +public class Constraint { + + private Integer freq_limit_per_target; + private Map time_window; + private Map active_time_range; + + private List blacklist; + + public Constraint() { + // Do Nothing empty constructor. + } + + public Integer getFreq_limit_per_target() { + return freq_limit_per_target; + } + + + public void setFreq_limit_per_target(Integer freq_limit_per_target) { + this.freq_limit_per_target = freq_limit_per_target; + } + + + public Map getTime_window() { + return time_window; + } + + + public void setTime_window(Map time_window) { + this.time_window = time_window; + } + + + public Map getActive_time_range() { + return active_time_range; + } + + + public void setActive_time_range(Map active_time_range) { + this.active_time_range = active_time_range; + } + + + public List getBlacklist() { + return blacklist; + } + + public void setBlacklist(List blacklist) { + this.blacklist = blacklist; + } + + public Constraint(Integer freq_limit_per_target, Map time_window) { + this.freq_limit_per_target = freq_limit_per_target; + if(time_window!=null){ + this.time_window = Collections.unmodifiableMap(time_window); + } + } + + public Constraint(List blacklist) { + this.blacklist = new LinkedList<>(blacklist); + } + + public Constraint(Integer freq_limit_per_target, Map time_window, List blacklist) { + this.freq_limit_per_target = freq_limit_per_target; + this.time_window = Collections.unmodifiableMap(time_window); + this.blacklist = new LinkedList<>(blacklist); + } + + public Constraint(Integer freq_limit_per_target, Map time_window, Map active_time_range) { + this(freq_limit_per_target, time_window); + if (active_time_range != null) { + this.active_time_range = Collections.unmodifiableMap(active_time_range); + } + } + + public Constraint(Integer freq_limit_per_target, Map time_window, Map active_time_range, List blacklist) { + this(freq_limit_per_target, time_window); + if (active_time_range != null) { + this.active_time_range = Collections.unmodifiableMap(active_time_range); + } + if(blacklist!=null){ + this.blacklist = new LinkedList<>(blacklist); + } + } + + public Constraint(Constraint constraint) { + this.freq_limit_per_target = constraint.freq_limit_per_target; + this.time_window = constraint.time_window; + if (constraint.active_time_range != null) { + this.active_time_range = Collections.unmodifiableMap(constraint.active_time_range); + } + this.blacklist = new LinkedList<>(constraint.blacklist); + } + + public boolean isValid() { + return ((freq_limit_per_target == null && time_window != null)|| (time_window == null && freq_limit_per_target != null))? false : true; + } + + @Override + public String toString() { + return "Constraint [freq_limit_per_target=" + freq_limit_per_target + ", time_window=" + time_window + ", active_time_range=" + active_time_range + ", blacklist=" + blacklist + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((freq_limit_per_target == null) ? 0 : freq_limit_per_target.hashCode()); + result = prime * result + ((time_window == null) ? 0 : time_window.hashCode()); + result = prime * result + ((active_time_range == null) ? 0 : active_time_range.hashCode()); + result = prime * result + ((blacklist == null) ? 0 : blacklist.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Constraint other = (Constraint) obj; + if (freq_limit_per_target == null) { + if (other.freq_limit_per_target != null) + return false; + } else if (!freq_limit_per_target.equals(other.freq_limit_per_target)) + return false; + if (time_window == null) { + if (other.time_window != null) + return false; + } else if (!time_window.equals(other.time_window)) + return false; + if (active_time_range == null) { + if (other.active_time_range != null) + return false; + } else if (!active_time_range.equals(other.active_time_range)) + return false; + if (blacklist == null) { + if (other.blacklist != null) + return false; + } else if (!blacklist.equals(other.blacklist)) + return false; + return true; + } +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java new file mode 100644 index 000000000..5d832140c --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuard.java @@ -0,0 +1,92 @@ +/*- + * ============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.controlloop.policy.guard; + +import java.util.LinkedList; + +public class ControlLoopGuard { + + private Guard guard; + + private LinkedList guards; + + public ControlLoopGuard() { + //DO Nothing Empty Constructor + } + + public Guard getGuard() { + return guard; + } + + public void setGuard(Guard guard) { + this.guard = guard; + } + + public LinkedList getGuards() { + return guards; + } + + public void setGuards(LinkedList guards) { + this.guards = guards; + } + + public ControlLoopGuard(ControlLoopGuard cLGuard) { + this.guard = new Guard(); + this.guards = new LinkedList<>(cLGuard.guards); + } + + @Override + public String toString() { + return "Guard [guard=" + guard + ", GuardPolicies=" + guards + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((guard == null) ? 0 : guard.hashCode()); + result = prime * result + ((guards == null) ? 0 : guards.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ControlLoopGuard other = (ControlLoopGuard) obj; + if (guard == null) { + if (other.guard != null) + return false; + } else if (!guard.equals(other.guard)) + return false; + if (guards == null) { + if (other.guards != null) + return false; + } else if (!guards.equals(other.guards)) + return false; + return true; + } + + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopParameter.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopParameter.java new file mode 100644 index 000000000..dafa95094 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/ControlLoopParameter.java @@ -0,0 +1,89 @@ +/*- + * ============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.controlloop.policy.guard; + +public class ControlLoopParameter { + private String controlLoopName; + private String version; + + public String getControlLoopName() { + return controlLoopName; + } + + public void setControlLoopName(String controlLoopName) { + this.controlLoopName = controlLoopName; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public ControlLoopParameter(String controlLoopName, String version) { + super(); + this.controlLoopName = controlLoopName; + this.version = version; + } + + public ControlLoopParameter(ControlLoopParameter cl) { + + this.controlLoopName = cl.controlLoopName; + this.version = cl.version; + } + + @Override + public String toString() { + return "ControlLoopParameter [controlLoopName=" + controlLoopName + ", version=" + version + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((controlLoopName == null) ? 0 : controlLoopName.hashCode()); + result = prime * result + ((version == null) ? 0 : version.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ControlLoopParameter other = (ControlLoopParameter) obj; + if (controlLoopName == null) { + if (other.controlLoopName != null) + return false; + } else if (!controlLoopName.equals(other.controlLoopName)) + return false; + if (version == null) { + if (other.version != null) + return false; + } else if (!version.equals(other.version)) + return false; + return true; + } +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java new file mode 100644 index 000000000..453466989 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/Guard.java @@ -0,0 +1,67 @@ +/*- + * ============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.controlloop.policy.guard; + +public class Guard { + + private static final String DEFAULTVERSION = "2.0.0"; + + private String version = DEFAULTVERSION; + + public Guard() { + //DO Nothing empty Constructor. + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + @Override + public String toString() { + return "Guard [version=" + version + "]"; + } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((version == null) ? 0 : version.hashCode()); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Guard other = (Guard) obj; + if (version == null) { + if (other.version != null) + return false; + } else if (!version.equals(other.version)) + return false; + return true; + } +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.java new file mode 100644 index 000000000..2068a46da --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/GuardPolicy.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.controlloop.policy.guard; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.UUID; + +public class GuardPolicy { + + private String id = UUID.randomUUID().toString(); + private String name; + private String description; + private MatchParameters match_parameters; + private LinkedList limit_constraints; + + public GuardPolicy() { + //Do Nothing Empty Constructor. + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + 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; + } + + public MatchParameters getMatch_parameters() { + return match_parameters; + } + + public void setMatch_parameters(MatchParameters match_parameters) { + this.match_parameters = match_parameters; + } + + public LinkedList getLimit_constraints() { + return limit_constraints; + } + + public void setLimit_constraints(LinkedList limit_constraints) { + this.limit_constraints = limit_constraints; + } + + public GuardPolicy(String id) { + this.id = id; + } + + public GuardPolicy(String name, MatchParameters matchParameters) { + this.name = name; + this.match_parameters = matchParameters; + } + + public GuardPolicy(String id, String name, String description, MatchParameters matchParameters) { + this(name, matchParameters); + this.id = id; + this.description = description; + } + + public GuardPolicy(String name, MatchParameters matchParameters, List limitConstraints) { + this(name, matchParameters); + if (limit_constraints != null) { + this.limit_constraints = (LinkedList) Collections.unmodifiableList(limitConstraints); + } + } + + public GuardPolicy(String name, String description, MatchParameters matchParameters, List limitConstraints) { + this(name, matchParameters, limitConstraints); + this.description = description; + } + + public GuardPolicy(String id, String name, String description, MatchParameters matchParameters, List limitConstraints) { + this(name, description, matchParameters, limitConstraints); + this.id = id; + } + + public GuardPolicy(GuardPolicy policy) { + this.id = policy.id; + this.name = policy.name; + this.description = policy.description; + this.match_parameters = new MatchParameters(policy.match_parameters); + if (policy.limit_constraints != null) { + this.limit_constraints = (LinkedList) Collections.unmodifiableList(policy.limit_constraints); + } + } + + public boolean isValid() { + return (id==null || name ==null)? false : true; + } + + @Override + public String toString() { + return "Policy [id=" + id + ", name=" + name + ", description=" + description + ", match_parameters=" + +match_parameters + ", limitConstraints=" + limit_constraints + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((limit_constraints == null) ? 0 : limit_constraints.hashCode()); + result = prime * result + ((match_parameters == null) ? 0 : match_parameters.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + GuardPolicy other = (GuardPolicy) obj; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (limit_constraints == null) { + if (other.limit_constraints != null) + return false; + } else if (!limit_constraints.equals(other.limit_constraints)) + return false; + if (match_parameters==null){ + if(other.match_parameters !=null) + return false; + } else if(!match_parameters.equals(other.match_parameters)) + return false; + return true; + } + + +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java new file mode 100644 index 000000000..da64cfcaa --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/MatchParameters.java @@ -0,0 +1,142 @@ +/*- + * ============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.controlloop.policy.guard; + +import java.util.LinkedList; +import java.util.List; + +public class MatchParameters { + private String controlLoopName; + private String actor; + private String recipe; + private List targets; + + public MatchParameters() { + // Do Nothing Empty Constructor. + } + + public String getControlLoopName() { + return controlLoopName; + } + + public void setControlLoopName(String controlLoopName) { + this.controlLoopName = controlLoopName; + } + + public String getActor() { + return actor; + } + + public void setActor(String actor) { + this.actor = actor; + } + + public String getRecipe() { + return recipe; + } + + public void setRecipe(String recipe) { + this.recipe = recipe; + } + + public List getTargets() { + return targets; + } + + public void setTargets(List targets) { + this.targets = targets; + } + + public MatchParameters(String actor, String recipe) { + this.actor = actor; + this.recipe = recipe; + } + + public MatchParameters(String actor, String recipe, List targets) { + this(actor, recipe); + if (targets != null) { + this.targets = new LinkedList<>(targets); + } + } + + public MatchParameters(String controlLoopName, String actor, String recipe, List targets) { + this(actor, recipe, targets); + this.controlLoopName = controlLoopName; + } + + public MatchParameters(MatchParameters matchParameters) { + + this.controlLoopName = matchParameters.controlLoopName; + this.actor = matchParameters.actor; + this.recipe = matchParameters.recipe; + if (matchParameters.targets != null) { + this.targets = new LinkedList<>(matchParameters.targets); + } + } + + @Override + public String toString() { + return "MatchParameters [controlLoopName=" + controlLoopName + ", actor=" + actor + ", recipe=" + recipe + + ", targets=" + targets + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((actor == null) ? 0 : actor.hashCode()); + result = prime * result + ((controlLoopName == null) ? 0 : controlLoopName.hashCode()); + result = prime * result + ((recipe == null) ? 0 : recipe.hashCode()); + result = prime * result + ((targets == null) ? 0 : targets.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + MatchParameters other = (MatchParameters) obj; + if (actor == null) { + if (other.actor != null) + return false; + } else if (!actor.equals(other.actor)) + return false; + if (controlLoopName == null) { + if (other.controlLoopName != null) + return false; + } else if (!controlLoopName.equals(other.controlLoopName)) + return false; + if (recipe == null) { + if (other.recipe != null) + return false; + } else if (!recipe.equals(other.recipe)) + return false; + if (targets == null) { + if (other.targets != null) + return false; + } else if (!targets.equals(other.targets)) + return false; + return true; + } +} \ No newline at end of file diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java new file mode 100644 index 000000000..e0e240db7 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/builder/ControlLoopGuardBuilder.java @@ -0,0 +1,130 @@ +/*- + * ============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.controlloop.policy.guard.builder; + +import org.onap.policy.controlloop.policy.builder.BuilderException; +import org.onap.policy.controlloop.policy.builder.Results; +import org.onap.policy.controlloop.policy.guard.Constraint; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; +import org.onap.policy.controlloop.policy.guard.Guard; +import org.onap.policy.controlloop.policy.guard.GuardPolicy; +import org.onap.policy.controlloop.policy.guard.builder.impl.ControlLoopGuardBuilderImpl; + +public interface ControlLoopGuardBuilder { + + /** + * Adds one or more guard policies to the Control Loop Guard + * + * + * @param policies + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder addGuardPolicy(GuardPolicy... policies) throws BuilderException; + + /** + * Removes one or more guard policies from the Control Loop Guard + * + * + * @param policies + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeGuardPolicy(GuardPolicy... policies) throws BuilderException; + + /** + * Removes all guard policies from the Control Loop Guard + * + * + * @param + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeAllGuardPolicies() throws BuilderException; + + /** + * Adds one or more time limit constraints to the guard policy + * + * + * @param id (guard policy id) + * @param constraints + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder addLimitConstraint(String id, Constraint... constraints) throws BuilderException; + + /** + * Removes one or more time limit constraints from the guard policy + * + * + * @param id (guard policy id) + * @param constraints + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeLimitConstraint(String id, Constraint... constraints) throws BuilderException; + + /** + * Removes all time limit constraints from the guard policy + * + * + * @param id (guard policy id) + * @return + * @throws BuilderException + */ + public ControlLoopGuardBuilder removeAllLimitConstraints(String id) throws BuilderException; + + /** + * Simply return a copy of control loop guard + * + * @return ControlLoopGuard + */ + public ControlLoopGuard getControlLoopGuard(); + + /** + * This will compile and build the YAML specification for the Control Loop Guard. Please iterate the Results object for details. + * The Results object will contains warnings and errors. If the specification compiled successfully, you will be able to retrieve the + * YAML. + * + * @return Results + */ + public Results buildSpecification(); + + /** + * The Factory is used to build a ControlLoopGuardBuilder implementation. + * + */ + public static class Factory { + + private Factory(){ + //Do Nothing Private Constructor. + } + /** + * @param guard + * @return ControlLoopGuardBuilder object + * @throws BuilderException + */ + public static ControlLoopGuardBuilder buildControlLoopGuard (Guard guard) throws BuilderException { + + return new ControlLoopGuardBuilderImpl(guard); + + } + } +} diff --git a/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java new file mode 100644 index 000000000..6152a4d08 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/main/java/org/onap/policy/controlloop/policy/guard/builder/impl/ControlLoopGuardBuilderImpl.java @@ -0,0 +1,244 @@ +/*- + * ============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.controlloop.policy.guard.builder.impl; + +import java.util.LinkedList; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.controlloop.compiler.CompilerException; +import org.onap.policy.controlloop.compiler.ControlLoopCompilerCallback; +import org.onap.policy.controlloop.guard.compiler.ControlLoopGuardCompiler; +import org.onap.policy.controlloop.policy.builder.BuilderException; +import org.onap.policy.controlloop.policy.builder.MessageLevel; +import org.onap.policy.controlloop.policy.builder.Results; +import org.onap.policy.controlloop.policy.builder.impl.MessageImpl; +import org.onap.policy.controlloop.policy.builder.impl.ResultsImpl; +import org.onap.policy.controlloop.policy.guard.Constraint; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; +import org.onap.policy.controlloop.policy.guard.Guard; +import org.onap.policy.controlloop.policy.guard.GuardPolicy; +import org.onap.policy.controlloop.policy.guard.builder.ControlLoopGuardBuilder; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.Yaml; + +public class ControlLoopGuardBuilderImpl implements ControlLoopGuardBuilder { + private static Logger logger = FlexLogger.getLogger(ControlLoopGuardBuilderImpl.class.getName()); + private ControlLoopGuard cLGuard; + + public ControlLoopGuardBuilderImpl(Guard guard) { + cLGuard = new ControlLoopGuard(); + cLGuard.setGuard(guard); + } + + @Override + public ControlLoopGuardBuilder addGuardPolicy(GuardPolicy... policies) throws BuilderException { + if (policies == null) { + throw new BuilderException("GuardPolicy must not be null"); + } + for (GuardPolicy policy : policies) { + if (!policy.isValid()) { + throw new BuilderException("Invalid guard policy - some required fields are missing"); + } + if (cLGuard.getGuards() == null) { + cLGuard.setGuards(new LinkedList<>()); + } + cLGuard.getGuards().add(policy); + } + return this; + } + + @Override + public ControlLoopGuardBuilder removeGuardPolicy(GuardPolicy... policies) throws BuilderException { + if (policies == null) { + throw new BuilderException("GuardPolicy must not be null"); + } + if (cLGuard.getGuards() == null) { + throw new BuilderException("No existing guard policies to remove"); + } + for (GuardPolicy policy : policies) { + if (!policy.isValid()) { + throw new BuilderException("Invalid guard policy - some required fields are missing"); + } + boolean removed = cLGuard.getGuards().remove(policy); + if (!removed) { + throw new BuilderException("Unknown guard policy: " + policy.getName()); + } + } + return this; + } + + @Override + public ControlLoopGuardBuilder removeAllGuardPolicies() throws BuilderException { + cLGuard.getGuards().clear(); + return this; + } + + @Override + public ControlLoopGuardBuilder addLimitConstraint(String id, Constraint... constraints) throws BuilderException { + if (id == null) { + throw new BuilderException("The id of target guard policy must not be null"); + } + if (constraints == null) { + throw new BuilderException("Constraint much not be null"); + } + if (!addLimitConstraints(id,constraints)) { + throw new BuilderException("No existing guard policy matching the id: " + id); + } + return this; + } + + private boolean addLimitConstraints(String id, Constraint... constraints) throws BuilderException { + boolean exist = false; + for (GuardPolicy policy: cLGuard.getGuards()) { + // + // We could have only one guard policy matching the id + // + if (policy.getId().equals(id)) { + exist = true; + for (Constraint cons: constraints) { + if (!cons.isValid()) { + throw new BuilderException("Invalid guard constraint - some required fields are missing"); + } + if (policy.getLimit_constraints() == null) { + policy.setLimit_constraints(new LinkedList<>()); + } + policy.getLimit_constraints().add(cons); + } + break; + } + } + return exist; + } + + @Override + public ControlLoopGuardBuilder removeLimitConstraint(String id, Constraint... constraints) throws BuilderException { + if (id == null) { + throw new BuilderException("The id of target guard policy must not be null"); + } + if (constraints == null) { + throw new BuilderException("Constraint much not be null"); + } + if (!removeConstraints(id, constraints)) { + throw new BuilderException("No existing guard policy matching the id: " + id); + } + return this; + } + + private boolean removeConstraints(String id, Constraint... constraints) throws BuilderException { + boolean exist = false; + for (GuardPolicy policy: cLGuard.getGuards()) { + // + // We could have only one guard policy matching the id + // + if (policy.getId().equals(id)) { + exist = true; + for (Constraint cons: constraints) { + if (!cons.isValid()) { + throw new BuilderException("Invalid guard constraint - some required fields are missing"); + } + boolean removed = policy.getLimit_constraints().remove(cons); + if (!removed) { + throw new BuilderException("Unknown guard constraint: " + cons); + } + } + break; + } + } + return exist; + } + + @Override + public ControlLoopGuardBuilder removeAllLimitConstraints(String id) throws BuilderException { + if (cLGuard.getGuards() == null || cLGuard.getGuards().isEmpty()) { + throw new BuilderException("No guard policies exist"); + } + if (id == null) { + throw new BuilderException("The id of target guard policy must not be null"); + } + boolean exist = false; + for (GuardPolicy policy: cLGuard.getGuards()) { + if (policy.getId().equals(id)) { + exist = true; + policy.getLimit_constraints().clear(); + } + } + if (!exist) { + throw new BuilderException("No existing guard policy matching the id: " + id); + } + return this; + } + + + private class BuilderCompilerCallback implements ControlLoopCompilerCallback { + + private ResultsImpl results = new ResultsImpl(); + + @Override + public boolean onWarning(String message) { + results.addMessage(new MessageImpl(message, MessageLevel.WARNING)); + return false; + } + + @Override + public boolean onError(String message) { + results.addMessage(new MessageImpl(message, MessageLevel.ERROR)); + return false; + } + } + + @Override + public ControlLoopGuard getControlLoopGuard() { + return new ControlLoopGuard(this.cLGuard); + } + + + @Override + public Results buildSpecification() { + // + // Dump the specification + // + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + options.setPrettyFlow(true); + Yaml yaml = new Yaml(options); + String dumpedYaml = yaml.dump(cLGuard); + // + // This is our callback class for our compiler + // + BuilderCompilerCallback callback = new BuilderCompilerCallback(); + // + // Compile it + // + try { + ControlLoopGuardCompiler.compile(cLGuard, callback); + } catch (CompilerException e) { + logger.error(e.getMessage() + e); + callback.results.addMessage(new MessageImpl(e.getMessage(), MessageLevel.EXCEPTION)); + } + // + // Save the spec + // + callback.results.setSpecification(dumpedYaml); + return callback.results; + } + +} diff --git a/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java b/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java new file mode 100644 index 000000000..40111ca48 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopCompilerTest.java @@ -0,0 +1,80 @@ +/*- + * ============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.controlloop.compiler; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import org.junit.Test; + +public class ControlLoopCompilerTest { + + @Test + public void testTest() { + try { + this.test("src/test/resources/v1.0.0/test.yaml"); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testBad1() { + try { + this.test("src/test/resources/v1.0.0/bad_trigger_1.yaml"); + } catch (Exception e) { + e.printStackTrace(); + } + } + @Test + public void testBad2() { + try { + this.test("src/test/resources/v1.0.0/bad_trigger_2.yaml"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testBad() { + try { + this.test("src/test/resources/v1.0.0/bad_policies_1.yaml"); + } catch (Exception e) { + } + } + + public void test(String testFile) throws Exception { + try (InputStream is = new FileInputStream(new File(testFile))) { + ControlLoopCompiler.compile(is, null); + } catch (FileNotFoundException e) { + fail(e.getMessage()); + } catch (IOException e) { + fail(e.getMessage()); + } catch (Exception e) { + throw e; + } + } + +} diff --git a/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java b/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java new file mode 100644 index 000000000..5a834aad3 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/compiler/ControlLoopGuardCompilerTest.java @@ -0,0 +1,101 @@ +/*- + * ============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.controlloop.compiler; + +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import org.junit.Test; +import org.onap.policy.controlloop.guard.compiler.ControlLoopGuardCompiler; + +public class ControlLoopGuardCompilerTest { + + @Test + public void testTest1() { + try { + this.test("src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml"); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testTest2() { + try { + this.test("src/test/resources/v2.0.0-guard/policy_guard_1707_appc.yaml"); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testBad1() { + try { + this.test("src/test/resources/v2.0.0-guard/no_guard_policy.yaml"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testBad2() { + try { + this.test("src/test/resources/v2.0.0-guard/duplicate_guard_policy.yaml"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testBad3() { + try { + this.test("src/test/resources/v2.0.0-guard/no_guard_constraint.yaml"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void testBad4() { + try { + this.test("src/test/resources/v2.0.0-guard/duplicate_guard_constraint.yaml"); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public void test(String testFile) throws Exception { + try (InputStream is = new FileInputStream(new File(testFile))) { + ControlLoopGuardCompiler.compile(is, null); + } catch (FileNotFoundException e) { + fail(e.getMessage()); + } catch (IOException e) { + fail(e.getMessage()); + } catch (Exception e) { + throw e; + } + } + +} diff --git a/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java b/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java new file mode 100644 index 000000000..c9338409c --- /dev/null +++ b/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyBuilderTest.java @@ -0,0 +1,516 @@ +/*- + * ============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.controlloop.policy; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.UUID; + +import org.junit.Test; +import org.onap.policy.asdc.Resource; +import org.onap.policy.asdc.ResourceType; +import org.onap.policy.asdc.Service; +import org.onap.policy.controlloop.policy.builder.BuilderException; +import org.onap.policy.controlloop.policy.builder.ControlLoopPolicyBuilder; +import org.onap.policy.controlloop.policy.builder.Message; +import org.onap.policy.controlloop.policy.builder.MessageLevel; +import org.onap.policy.controlloop.policy.builder.Results; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.error.YAMLException; + + +public class ControlLoopPolicyBuilderTest { + + @Test + public void testControlLoop() { + try { + // + // Create a builder for our policy + // + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + // + // Test add services + // + Service vSCP = new Service("vSCP"); + Service vUSP = new Service("vUSP"); + Service vTrinity = new Service("Trinity"); + builder = builder.addService(vSCP, vUSP, vTrinity); + assertTrue(builder.getControlLoop().getServices().size() == 3); + // + // Test remove services + // + builder = builder.removeService(vSCP); + assertTrue(builder.getControlLoop().getServices().size() == 2); + builder = builder.removeAllServices(); + assertTrue(builder.getControlLoop().getServices().size() == 0); + // + // Test add resources + // + Resource vCTS = new Resource("vCTS", ResourceType.VF); + Resource vCOM = new Resource("vCTS", ResourceType.VF); + Resource vRAR = new Resource("vCTS", ResourceType.VF); + builder = builder.addResource(vCTS, vCOM, vRAR); + assertTrue(builder.getControlLoop().getResources().size() == 3); + // + // Test remove resources + // + builder = builder.removeResource(vCTS); + assertTrue(builder.getControlLoop().getResources().size() == 2); + builder = builder.removeAllResources(); + assertTrue(builder.getControlLoop().getResources().size() == 0); + // + // Test set abatement + // + assertFalse(builder.getControlLoop().getAbatement()); + builder = builder.setAbatement(true); + assertTrue(builder.getControlLoop().getAbatement()); + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + @Test + public void testTimeout() { + try { + // + // Create a builder for our policy + // + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + // + // Test setTimeout + // + assertTrue(builder.getControlLoop().getTimeout() == 2400); + builder = builder.setTimeout(800); + assertTrue(builder.getControlLoop().getTimeout() == 800); + // + // Test calculateTimeout + // + Policy trigger = builder.setTriggerPolicy( + "Restart the VM", + "Upon getting the trigger event, restart the VM", + "APPC", + new Target(TargetType.VM), + "Restart", + null, + 2, + 300); + @SuppressWarnings("unused") + Policy onRestartFailurePolicy = builder.setPolicyForPolicyResult( + "Rebuild VM", + "If the restart fails, rebuild it", + "APPC", + new Target(TargetType.VM), + "Rebuild", + null, + 1, + 600, + trigger.getId(), + PolicyResult.FAILURE, + PolicyResult.FAILURE_RETRIES, + PolicyResult.FAILURE_TIMEOUT); + assertTrue(builder.calculateTimeout().equals(new Integer(300 + 600))); + // + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + @Test + public void testTriggerPolicyMethods() { + try { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + // + // Test isOpenLoop + // + assertTrue(builder.isOpenLoop()); + // + // Test set initial trigger policy + // + Policy triggerPolicy1 = builder.setTriggerPolicy( + "Restart the VM", + "Upon getting the trigger event, restart the VM", + "APPC", + new Target(TargetType.VM), + "Restart", + null, + 2, + 300); + assertTrue(builder.isOpenLoop() == false); + assertTrue(builder.getControlLoop().getTrigger_policy().equals(triggerPolicy1.getId())); + // + // Set trigger policy to a new policy + // + @SuppressWarnings("unused") + Policy triggerPolicy2 = builder.setTriggerPolicy( + "Rebuild the VM", + "Upon getting the trigger event, rebuild the VM", + "APPC", + new Target(TargetType.VM), + "Rebuild", + null, + 2, + 300); + // + // Test set trigger policy to another existing policy + // + @SuppressWarnings("unused") + ControlLoop cl = builder.setTriggerPolicy(triggerPolicy1.getId()); + assertTrue(builder.getControlLoop().getTrigger_policy().equals(triggerPolicy1.getId())); + // + // Test get trigger policy + // + assertTrue(builder.getTriggerPolicy().equals(triggerPolicy1)); + // + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + @Test + public void testAddRemovePolicies() { + try { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + Policy triggerPolicy = builder.setTriggerPolicy( + "Restart the VM", + "Upon getting the trigger event, restart the VM", + "APPC", + new Target(TargetType.VM), + "Restart", + null, + 2, + 300); + // + // Test create a policy and chain it to the results of trigger policy + // + Policy onRestartFailurePolicy1 = builder.setPolicyForPolicyResult( + "Rebuild VM", + "If the restart fails, rebuild it.", + "APPC", + new Target(TargetType.VM), + "Rebuild", + null, + 1, + 600, + triggerPolicy.getId(), + PolicyResult.FAILURE, + PolicyResult.FAILURE_RETRIES, + PolicyResult.FAILURE_TIMEOUT, + PolicyResult.FAILURE_GUARD); + // + assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy1.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy1.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy1.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(onRestartFailurePolicy1.getId())); + // + // Test remove policy + // + boolean removed = builder.removePolicy(onRestartFailurePolicy1.getId()); + assertTrue(removed); + assertTrue(builder.getTriggerPolicy().getFailure().equals(FinalResult.FINAL_FAILURE.toString())); + assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(FinalResult.FINAL_FAILURE_RETRIES.toString())); + assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())); + assertTrue(builder.getTriggerPolicy().getFailure_guard().equals(FinalResult.FINAL_FAILURE_GUARD.toString())); + // + // Create another policy and chain it to the results of trigger policy + // + Policy onRestartFailurePolicy2 = builder.setPolicyForPolicyResult( + "Rebuild VM", + "If the restart fails, rebuild it.", + "APPC", + new Target(TargetType.VM), + "Rebuild", + null, + 2, + 600, + triggerPolicy.getId(), + PolicyResult.FAILURE, + PolicyResult.FAILURE_RETRIES, + PolicyResult.FAILURE_TIMEOUT); + // + // Test reset policy results + // + triggerPolicy = builder.resetPolicyResults(triggerPolicy.getId()); + assertTrue(builder.getTriggerPolicy().getFailure().equals(FinalResult.FINAL_FAILURE.toString())); + assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(FinalResult.FINAL_FAILURE_RETRIES.toString())); + assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(FinalResult.FINAL_FAILURE_TIMEOUT.toString())); + // + // Test set the policy results to an existing operational policy + // + onRestartFailurePolicy2 = builder.setPolicyForPolicyResult( + onRestartFailurePolicy2.getId(), + triggerPolicy.getId(), + PolicyResult.FAILURE, + PolicyResult.FAILURE_RETRIES, + PolicyResult.FAILURE_TIMEOUT); + assertTrue(builder.getTriggerPolicy().getFailure().equals(onRestartFailurePolicy2.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_retries().equals(onRestartFailurePolicy2.getId())); + assertTrue(builder.getTriggerPolicy().getFailure_timeout().equals(onRestartFailurePolicy2.getId())); + + // + // Test remove all existing operational policies + // + builder = builder.removeAllPolicies(); + assertTrue(builder.getControlLoop().getTrigger_policy().equals(FinalResult.FINAL_OPENLOOP.toString())); + // + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + @Test + public void testAddOperationsAccumulateParams() { + try { + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 2400); + Policy triggerPolicy = builder.setTriggerPolicy( + "Restart the eNodeB", + "Upon getting the trigger event, restart the eNodeB", + "SDNR", + new Target(TargetType.PNF), + "Restart", + null, + 2, + 300); + // + // Add the operationsAccumulateParams + // + triggerPolicy = builder.addOperationsAccumulateParams(triggerPolicy.getId(), new OperationsAccumulateParams("15m", 5)); + assertNotNull(builder.getTriggerPolicy().getOperationsAccumulateParams()); + assertTrue(builder.getTriggerPolicy().getOperationsAccumulateParams().getPeriod().equals("15m")); + assertTrue(builder.getTriggerPolicy().getOperationsAccumulateParams().getLimit() == 5); + // + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + + @Test + public void testBuildSpecification() { + try { + // + // Create the builder + // + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(UUID.randomUUID().toString(), 800); + // + // Set the first invalid trigger policy + // + Policy policy1 = builder.setTriggerPolicy( + "Restart the VM", + "Upon getting the trigger event, restart the VM", + null, + null, + "Instantiate", + null, + 2, + 300); + Results results = builder.buildSpecification(); + // + // Check that ERRORs are in results for invalid policy arguments + // + boolean invalid_actor = false; + boolean invalid_recipe = false; + boolean invalid_target = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("Policy actor is null") && m.getLevel() == MessageLevel.ERROR) { + invalid_actor = true; + } + if (m.getMessage().equals("Policy recipe is invalid") && m.getLevel() == MessageLevel.ERROR) { + invalid_recipe = true; + } + if (m.getMessage().equals("Policy target is null") && m.getLevel() == MessageLevel.ERROR) { + invalid_target = true; + } + } + // + assertTrue(invalid_actor); + assertTrue(invalid_recipe); + assertTrue(invalid_target); + // + // Remove the invalid policy + // + //@SuppressWarnings("unused") + boolean removed = builder.removePolicy(policy1.getId()); + assertTrue(removed); + assertTrue(builder.getTriggerPolicy() == null); + // + // Set a valid trigger policy + // + policy1 = builder.setTriggerPolicy( + "Rebuild VM", + "If the restart fails, rebuild it.", + "APPC", + new Target(TargetType.VM), + "Rebuild", + null, + 1, + 600); + // + // Set a second valid trigger policy + // + Policy policy2 = builder.setTriggerPolicy( + "Restart the VM", + "Upon getting the trigger event, restart the VM", + "APPC", + new Target(TargetType.VM), + "Restart", + null, + 2, + 300); + // + // Now, we have policy1 unreachable + // + results = builder.buildSpecification(); + boolean unreachable = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("Policy " + policy1.getId() + " is not reachable.") && m.getLevel() == MessageLevel.WARNING) { + unreachable = true; + break; + } + } + assertTrue(unreachable); + // + // Set policy1 for the failure results of policy2 + // + policy1 = builder.setPolicyForPolicyResult( + policy1.getId(), + policy2.getId(), + PolicyResult.FAILURE, + PolicyResult.FAILURE_RETRIES, + PolicyResult.FAILURE_TIMEOUT); + results = builder.buildSpecification(); + boolean invalid_timeout = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("controlLoop overall timeout is less than the sum of operational policy timeouts.") && m.getLevel() == MessageLevel.ERROR) { + invalid_timeout = true; + break; + } + } + assertTrue(invalid_timeout); + // + // Remove policy2 (revert controlLoop back to open loop) + // + removed = builder.removePolicy(policy2.getId()); + // + // ControlLoop is open loop now, but it still has policies (policy1) + // + results = builder.buildSpecification(); + unreachable = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("Open Loop policy contains policies. The policies will never be invoked.") && m.getLevel() == MessageLevel.WARNING) { + unreachable = true; + break; + } + } + assertTrue(unreachable); + // + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + + @Test + public void test() { + this.test("src/test/resources/v1.0.0/policy_Test.yaml"); + } + + @Test + public void testEvilYaml() { + try (InputStream is = new FileInputStream(new File("src/test/resources/v1.0.0/test_evil.yaml"))) { + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + yaml.load(is); + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } catch (YAMLException e) { + // + // Should have this + // + } + } + + public void test(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(is); + assertNotNull(obj); + assertTrue(obj instanceof ControlLoopPolicy); + ControlLoopPolicy policyTobuild = (ControlLoopPolicy) obj; + // + // Now we're going to try to use the builder to build this. + // + ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop( + policyTobuild.getControlLoop().getControlLoopName(), + policyTobuild.getControlLoop().getTimeout()); + // + // Add services + // + if (policyTobuild.getControlLoop().getServices() != null) { + builder = builder.addService(policyTobuild.getControlLoop().getServices().toArray(new Service[policyTobuild.getControlLoop().getServices().size()])); + } + // + // Add resources + // + if (policyTobuild.getControlLoop().getResources() != null) { + builder = builder.addResource(policyTobuild.getControlLoop().getResources().toArray(new Resource[policyTobuild.getControlLoop().getResources().size()])); + } + // + // Add the policies and be sure to set the trigger policy + // + if (policyTobuild.getPolicies() != null) { + for (Policy policy : policyTobuild.getPolicies()) { + if (policy.getId() == policyTobuild.getControlLoop().getTrigger_policy()) { + builder.setTriggerPolicy(policy.getName(), policy.getDescription(), policy.getActor(), policy.getTarget(), policy.getRecipe(), null, policy.getRetry(), policy.getTimeout()); + } + } + } + + // Question : how to change policy ID and results by using builder ?? + + @SuppressWarnings("unused") + Results results = builder.buildSpecification(); + + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } catch (BuilderException e) { + fail(e.getLocalizedMessage()); + } + + } + +} diff --git a/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyTest.java b/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyTest.java new file mode 100644 index 000000000..a7cb668d6 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/ControlLoopPolicyTest.java @@ -0,0 +1,101 @@ +/*- + * ============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.controlloop.policy; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import org.junit.Test; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + + +public class ControlLoopPolicyTest { + + @Test + public void test() { + this.test("src/test/resources/v1.0.0/policy_Test.yaml"); + } + + @Test + public void testMultipleService() { + this.test("src/test/resources/v1.0.0/policy_Test_MultipleService.yaml"); + } + + @Test + public void testOpenLoop() { + this.test("src/test/resources/v1.0.0/policy_OpenLoop_1610.yaml"); + } + + @Test + public void testONAPvDNS() { + this.test("src/test/resources/v2.0.0/policy_ONAP_demo_vDNS.yaml"); + } + + public void test(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopPolicy.class)); + Object obj = yaml.load(is); + assertNotNull(obj); + assertTrue(obj instanceof ControlLoopPolicy); + dump(obj); + // + // Now dump it to a yaml string + // + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + options.setPrettyFlow(true); + yaml = new Yaml(options); + String dumpedYaml = yaml.dump(obj); + System.out.println(dumpedYaml); + // + // Read that string back into our java object + // + Object newObject = yaml.load(dumpedYaml); + dump(newObject); + assertNotNull(newObject); + assertTrue(newObject instanceof ControlLoopPolicy); + // + // Have to comment it out tentatively since it causes junit to fail. + // Seems we cannot use assertEquals here. Need advice. + // + //assertEquals(newObject, obj); + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + } + + public void dump(Object obj) { + System.out.println("Dumping " + obj.getClass().getCanonicalName()); + System.out.println(obj.toString()); + } +} diff --git a/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java b/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java new file mode 100644 index 000000000..0dfb1ccb3 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardBuilderTest.java @@ -0,0 +1,202 @@ +/*- + * ============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.controlloop.policy.guard; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.onap.policy.controlloop.policy.builder.BuilderException; +import org.onap.policy.controlloop.policy.builder.Message; +import org.onap.policy.controlloop.policy.builder.MessageLevel; +import org.onap.policy.controlloop.policy.builder.Results; +import org.onap.policy.controlloop.policy.guard.builder.ControlLoopGuardBuilder; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +public class ControlLoopGuardBuilderTest { + + @Test + public void testControlLoopGuard() { + try { + // + // Create a builder + // + ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard()); + // + // Assert there is no guard policies yet + // + Results results = builder.buildSpecification(); + boolean no_guard_policies = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("ControlLoop Guard should have at least one guard policies") && m.getLevel() == MessageLevel.ERROR) { + no_guard_policies = true; + break; + } + } + assertTrue(no_guard_policies); + // + // Add a guard policy without limit constraint + // + String clname = "CL_vUSP123"; + LinkedList targets = new LinkedList(); + targets.add("s1"); + targets.add("s2"); + targets.add("s3"); + MatchParameters matchParameters = new MatchParameters(clname, "APPC", "Restart", targets); + GuardPolicy policy1 = new GuardPolicy("id123", "guardpolicy1", "description aaa", matchParameters); + builder = builder.addGuardPolicy(policy1); + // + // Assert there is no limit constraint associated with the only guard policy + // + results = builder.buildSpecification(); + boolean no_constraint = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("Guard policy guardpolicy1 does not have any limit constraint") && m.getLevel() == MessageLevel.ERROR) { + no_constraint = true; + break; + } + } + assertTrue(no_constraint); + // + // Add a constraint to policy1 + // + Map active_time_range = new HashMap(); + active_time_range.put("start", "00:00:00-05:00"); + active_time_range.put("end", "23:59:59-05:00"); + List blacklist = new LinkedList(); + blacklist.add("eNodeB_common_id1"); + blacklist.add("eNodeB_common_id2"); + Map time_window = new HashMap(); + time_window.put("value", "10"); + time_window.put("units", "minute"); + Constraint cons = new Constraint(5, time_window, active_time_range, blacklist); + builder = builder.addLimitConstraint(policy1.getId(), cons); + // + // Add a duplicate constraint to policy1 + // + builder = builder.addLimitConstraint(policy1.getId(), cons); + // + // Assert there are duplicate constraints associated with the only guard policy + // + results = builder.buildSpecification(); + boolean duplicate_constraint = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("Guard policy guardpolicy1 has duplicate limit constraints") && m.getLevel() == MessageLevel.WARNING) { + duplicate_constraint = true; + break; + } + } + assertTrue(duplicate_constraint); + // + // Remove the duplicate constraint + // + builder = builder.removeLimitConstraint(policy1.getId(), cons); + // + // Add a duplicate guard policy + // + builder = builder.addGuardPolicy(policy1); + builder = builder.addLimitConstraint(policy1.getId(), cons); + // + // Assert there are duplicate guard policies + // + results = builder.buildSpecification(); + boolean duplicate_guard_policy = false; + for (Message m : results.getMessages()) { + if (m.getMessage().equals("There are duplicate guard policies") && m.getLevel() == MessageLevel.WARNING) { + duplicate_guard_policy = true; + break; + } + } + assertTrue(duplicate_guard_policy); + // + // Remove the duplicate guard policy + // + builder = builder.removeGuardPolicy(policy1); + // + // Assert there are no Error/Warning message + // + results = builder.buildSpecification(); + assertTrue(results.getMessages().size() == 1); + // + } catch (BuilderException e) { + fail(e.getMessage()); + } + } + + @Test + public void test1() { + this.test("src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml"); + } + + @Test + public void test2() { + this.test("src/test/resources/v2.0.0-guard/policy_guard_1707_appc.yaml"); + } + + public void test(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(is); + assertNotNull(obj); + assertTrue(obj instanceof ControlLoopGuard); + ControlLoopGuard guardTobuild = (ControlLoopGuard) obj; + // + // Now we're going to try to use the builder to build this. + // + ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(guardTobuild.getGuard()); + // + // Add guard policy + // + if (guardTobuild.getGuards() != null) { + builder = builder.addGuardPolicy(guardTobuild.getGuards().toArray(new GuardPolicy[guardTobuild.getGuards().size()])); + } + // + // Build the specification + // + Results results = builder.buildSpecification(); + // + // Print out the specification + // + System.out.println(results.getSpecification()); + // + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } catch (BuilderException e) { + fail(e.getLocalizedMessage()); + } + } +} diff --git a/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java b/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.java new file mode 100644 index 000000000..5cb0007a7 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/test/java/org/onap/policy/controlloop/policy/guard/ControlLoopGuardTest.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.controlloop.policy.guard; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import org.junit.Test; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.DumperOptions.FlowStyle; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + + +public class ControlLoopGuardTest { + + @Test + public void testGuardvDNS() { + this.test("src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml"); + } + + @Test + public void testGuardvUSP() { + this.test("src/test/resources/v2.0.0-guard/policy_guard_1707_appc.yaml"); + } + + public void test(String testFile) { + try (InputStream is = new FileInputStream(new File(testFile))) { + // + // Read the yaml into our Java Object + // + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(is); + assertNotNull(obj); + assertTrue(obj instanceof ControlLoopGuard); + dump(obj); + // + // Now dump it to a yaml string + // + DumperOptions options = new DumperOptions(); + options.setDefaultFlowStyle(FlowStyle.BLOCK); + options.setPrettyFlow(true); + yaml = new Yaml(options); + String dumpedYaml = yaml.dump(obj); + System.out.println(dumpedYaml); + // + // Read that string back into our java object + // + Object newObject = yaml.load(dumpedYaml); + dump(newObject); + assertNotNull(newObject); + assertTrue(newObject instanceof ControlLoopGuard); + // + // Have to comment it out tentatively since it causes junit to fail. + // Seems we cannot use assertEquals here. Need advice. + // + //assertEquals(newObject, obj); + } catch (FileNotFoundException e) { + fail(e.getLocalizedMessage()); + } catch (IOException e) { + fail(e.getLocalizedMessage()); + } + } + + public void dump(Object obj) { + System.out.println("Dumping " + obj.getClass().getCanonicalName()); + System.out.println(obj.toString()); + } +} diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/bad_policies_1.yaml b/ONAP-ControlloopPolicy/src/test/resources/v1.0.0/bad_policies_1.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/bad_policies_1.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v1.0.0/bad_policies_1.yaml diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/bad_trigger_1.yaml b/ONAP-ControlloopPolicy/src/test/resources/v1.0.0/bad_trigger_1.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/bad_trigger_1.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v1.0.0/bad_trigger_1.yaml diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/bad_trigger_2.yaml b/ONAP-ControlloopPolicy/src/test/resources/v1.0.0/bad_trigger_2.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/bad_trigger_2.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v1.0.0/bad_trigger_2.yaml diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/policy_OpenLoop_1610.yaml b/ONAP-ControlloopPolicy/src/test/resources/v1.0.0/policy_OpenLoop_1610.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/policy_OpenLoop_1610.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v1.0.0/policy_OpenLoop_1610.yaml diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/policy_Test.yaml b/ONAP-ControlloopPolicy/src/test/resources/v1.0.0/policy_Test.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/policy_Test.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v1.0.0/policy_Test.yaml diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/policy_Test_MultipleService.yaml b/ONAP-ControlloopPolicy/src/test/resources/v1.0.0/policy_Test_MultipleService.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/policy_Test_MultipleService.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v1.0.0/policy_Test_MultipleService.yaml diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/test.yaml b/ONAP-ControlloopPolicy/src/test/resources/v1.0.0/test.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/test.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v1.0.0/test.yaml diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/test_evil.yaml b/ONAP-ControlloopPolicy/src/test/resources/v1.0.0/test_evil.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v1.0.0/test_evil.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v1.0.0/test_evil.yaml diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0-guard/duplicate_guard_constraint.yaml b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0-guard/duplicate_guard_constraint.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v2.0.0-guard/duplicate_guard_constraint.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v2.0.0-guard/duplicate_guard_constraint.yaml diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0-guard/duplicate_guard_policy.yaml b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0-guard/duplicate_guard_policy.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v2.0.0-guard/duplicate_guard_policy.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v2.0.0-guard/duplicate_guard_policy.yaml diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0-guard/no_guard_constraint.yaml b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0-guard/no_guard_constraint.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v2.0.0-guard/no_guard_constraint.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v2.0.0-guard/no_guard_constraint.yaml diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0-guard/no_guard_policy.yaml b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0-guard/no_guard_policy.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v2.0.0-guard/no_guard_policy.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v2.0.0-guard/no_guard_policy.yaml diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0-guard/policy_guard_1707_appc.yaml b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0-guard/policy_guard_1707_appc.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v2.0.0-guard/policy_guard_1707_appc.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v2.0.0-guard/policy_guard_1707_appc.yaml diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v2.0.0-guard/policy_guard_OpenECOMP_demo_vDNS.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v2.0.0-guard/policy_guard_ONAP_demo_vDNS.yaml diff --git a/ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-59a2ee3fB58045feB5a1-template.yml b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-59a2ee3fB58045feB5a1-template.yml new file mode 100644 index 000000000..4b501953c --- /dev/null +++ b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-59a2ee3fB58045feB5a1-template.yml @@ -0,0 +1,1698 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 +metadata: + invariantUUID: 4b8d4018-068b-4c33-b9bb-d980798e52c2 + UUID: d7d28881-b24d-4512-bfee-1e2eb335591f + name: 59a2ee3f-b580-45fe-b5a1 + description: vendor software product + type: VF + category: Generic + subcategory: Abstract + resourceVendor: 185c637a-3885-463e-8fd0 + resourceVendorRelease: '1.0' +imports: +- NeutronNet: + file: resource-Neutronnet-template.yml +- NeutronPort: + file: resource-Neutronport-template.yml +- 59a2ee3fB58045feB5a1.nodes.heat.vlb: + file: resource-59a2ee3fb58045feb5a1NodesHeatVlb-template.yml +- 59a2ee3fB58045feB5a1.nodes.heat.vdns: + file: resource-59a2ee3fb58045feb5a1NodesHeatVdns-template.yml +topology_template: + inputs: + vf_module_id: + type: string + description: The vLoadBalancer Module ID is provided by ONAP + onap_private_subnet_id: + type: string + description: Private sub-network that connects ONAP component and the VNF + repo_url_blob: + type: string + description: URL of the repository that hosts the demo packages + vlb_private_net_cidr: + type: string + description: The CIDR of the vLoadBalancer private network + vlb_private_net_id: + type: string + description: Private network that connects vLoadBalancer with vDNSs + public_net_id: + type: string + default: 00000000-0000-0000-0000-000000000000 + description: Public network that enables remote connection to VNF + demo_artifacts_version: + type: string + description: Artifacts (jar, tar.gz) version used in demo vnfs + onap_private_net_id: + type: string + description: Private network that connects ONAP component and the VNF + pub_key: + type: string + description: Public key to be installed on the compute instance + vlb_private_ip_1: + type: string + description: Private IP address that is assigned to the vLoadBalancer to communicate with ONAP components + key_name: + type: string + description: Public/Private key pair name + vdns_name_0: + type: string + description: Name of the vDNS + repo_url_artifacts: + type: string + description: URL of the repository that hosts the demo packages + vlb_name_0: + type: string + description: Name of the vLoadBalancer + vdns_private_ip_0: + type: string + description: Private IP address that is assigned to the vDNS to communicate with the vLoadBalancer + vnf_id: + type: string + description: The VNF ID is provided by ONAP + dcae_collector_ip: + type: string + description: IP address of the DCAE collector + vdns_private_ip_1: + type: string + description: Private IP address that is assigned to the vDNS to communicate with ONAP components + dcae_collector_port: + type: string + description: Port of the DCAE collector + vlb_image_name: + type: string + default: Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM) + description: Image to be used for compute instance + vlb_flavor_name: + type: string + default: 4 GB General Purpose v1 + description: Type of instance (flavor) to be used + vlb_private_ip_0: + type: string + description: Private IP address that is assigned to the vLoadBalancer to communicate with the vDNSs + onap_private_net_cidr: + type: string + description: The CIDR of the protected private network + node_templates: + vdns_private_1_port: + type: org.onap.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: + get_input: onap_private_subnet_id + ip_address: + get_input: vdns_private_ip_1 + network: + get_input: onap_private_net_id + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: vdns_0 + relationship: tosca.relationships.network.BindsTo + vlb_private_network: + type: org.onap.resource.vl.nodes.heat.network.neutron.Net + metadata: + invariantUUID: 2870cc3a-d6cd-4423-b7f6-2d63619b0eeb + UUID: b7e764ba-17f9-4f0a-ad29-29877766ef21 + version: '1.0' + name: NeutronNet + description: Represents a network service with optional subnets and advanced configurations. + type: VL + category: Generic + subcategory: Network Elements + properties: + network_name: + get_input: vlb_private_net_id + subnets: + vlb_private_subnet: + name: + get_input: vlb_private_net_id + cidr: + get_input: vlb_private_net_cidr + vlb_private_1_port: + type: org.onap.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: + get_input: onap_private_subnet_id + ip_address: + get_input: vlb_private_ip_1 + network: + get_input: onap_private_net_id + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: vlb_0 + relationship: tosca.relationships.network.BindsTo + vdns_0: + type: org.onap.resource.vfc.59a2ee3fB58045feB5a1.abstact.nodes.heat.vdns + metadata: + invariantUUID: ee585c30-127b-492e-b2c1-871dc61d1dde + UUID: d816cb01-b5d0-4bbb-b614-f7c3e230ab19 + version: '1.0' + name: 59a2ee3fB58045feB5a1.nodes.heat.vdns + description: Not reusable inner VFC + type: VFC + category: Generic + subcategory: Abstract + properties: + key_name: UNSUPPORTED_RESOURCE_my_keypair + flavor: + get_input: vlb_flavor_name + image: + get_input: vlb_image_name + metadata: + vf_module_id: + get_input: vf_module_id + vnf_id: + get_input: vnf_id + user_data_format: RAW + name: + get_input: vdns_name_0 + vlb_private_0_port: + type: org.onap.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: vlb_private_network + ip_address: + get_input: vlb_private_ip_0 + network: vlb_private_network + requirements: + - link: + capability: tosca.capabilities.network.Linkable + node: vlb_private_network + relationship: tosca.relationships.network.LinksTo + - binding: + capability: tosca.capabilities.network.Bindable + node: vlb_0 + relationship: tosca.relationships.network.BindsTo + vdns_private_0_port: + type: org.onap.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: + get_input: vlb_private_net_id + ip_address: + get_input: vdns_private_ip_0 + network: + get_input: vlb_private_net_id + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: vdns_0 + relationship: tosca.relationships.network.BindsTo + vlb_0: + type: org.onap.resource.vfc.59a2ee3fB58045feB5a1.abstact.nodes.heat.vlb + metadata: + invariantUUID: f7f1d745-cfb1-4aa9-83fc-31280d0ce513 + UUID: 1821f13e-411f-4b29-87a5-ae935897b2e1 + version: '1.0' + name: 59a2ee3fB58045feB5a1.nodes.heat.vlb + description: Not reusable inner VFC + type: VFC + category: Generic + subcategory: Abstract + properties: + key_name: UNSUPPORTED_RESOURCE_my_keypair + flavor: + get_input: vlb_flavor_name + image: + get_input: vlb_image_name + metadata: + vf_module_id: + get_input: vf_module_id + vnf_id: + get_input: vnf_id + user_data_format: RAW + name: + get_input: vlb_name_0 + groups: + base_vlb: + type: org.onap.groups.heat.HeatStack + members: + - vdns_private_1_port + - vlb_private_network + - vlb_private_1_port + - vdns_0 + - vlb_private_0_port + - vdns_private_0_port + - vlb_0 + metadata: + invariantUUID: 097f71b3-90a1-4064-bc83-f76bf30195fe + UUID: 4daf7600-0a06-4515-859a-c45ec11abd29 + version: '1' + name: base_vlb + 59a2ee3fB58045feB5a1..dnsscaling..module-1: + type: org.onap.groups.VfModule + members: + - vdns_private_1_port + - vdns_0 + - vdns_private_0_port + metadata: + vfModuleModelName: 59a2ee3fB58045feB5a1..dnsscaling..module-1 + vfModuleModelInvariantUUID: 395d61a9-309b-4c0f-a442-ca47903e231e + vfModuleModelUUID: 40846490-abf4-4e1d-8f1a-2286968fa231 + vfModuleModelVersion: '1' + properties: + vf_module_type: Expansion + vf_module_description: + volume_group: false + 59a2ee3fB58045feB5a1..base_vlb..module-0: + type: org.onap.groups.VfModule + members: + - vdns_private_1_port + - vlb_private_network + - vlb_private_1_port + - vdns_0 + - vlb_private_0_port + - vdns_private_0_port + - vlb_0 + metadata: + vfModuleModelName: 59a2ee3fB58045feB5a1..base_vlb..module-0 + vfModuleModelInvariantUUID: 5ae76f74-6324-4835-a86c-0c96d16afd38 + vfModuleModelUUID: 17c4f752-a3da-4f3d-9cc5-1c4d28e5442d + vfModuleModelVersion: '1' + properties: + vf_module_type: Base + vf_module_description: + volume_group: false + dnsscaling: + type: org.onap.groups.heat.HeatStack + members: + - vdns_private_1_port + - vdns_0 + - vdns_private_0_port + metadata: + invariantUUID: 7c2971fa-9369-4fed-a449-a5e21c022f97 + UUID: ae8c3b79-77d3-425a-8bab-6558007f8392 + version: '1' + name: dnsscaling + substitution_mappings: + node_type: org.onap.resource.vf.59a2ee3fB58045feB5a1 + capabilities: + vdns_0.memory: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM allocated to the instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.memory.resident: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance on the physical machine + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.resident + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.cpu: + type: org.onap.capabilities.metric.Ceilometer + description: CPU time used + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Cumulative + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vdns_private_0_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vdns_0.host: + type: tosca.capabilities.Container + occurrences: + - 1 + - UNBOUNDED + valid_source_types: + - tosca.nodes.SoftwareComponent + properties: + num_cpus: + type: integer + required: false + disk_size: + type: scalar-unit.size + required: false + cpu_frequency: + type: scalar-unit.frequency + required: false + mem_size: + type: scalar-unit.size + required: false + vdns_0.endpoint: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + properties: + port_name: + type: string + required: false + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + secure: + type: boolean + default: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + url_path: + type: string + required: false + vlb_private_1_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vlb_0.memory: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM allocated to the instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_private_1_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vlb_0.scalable: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + properties: + max_instances: + type: integer + default: 1 + min_instances: + type: integer + default: 1 + default_instances: + type: integer + vlb_0.binding: + type: tosca.capabilities.network.Bindable + occurrences: + - 0 + - UNBOUNDED + vlb_0.vcpus: + type: org.onap.capabilities.metric.Ceilometer + description: Average disk latency + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ms + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: vcpus + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_0.instance: + type: org.onap.capabilities.metric.Ceilometer + description: Existence of instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.os: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + properties: + distribution: + type: string + required: false + type: + type: string + required: false + version: + type: version + required: false + architecture: + type: string + required: false + vlb_private_0_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vlb_private_1_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vlb_0.cpu: + type: org.onap.capabilities.metric.Ceilometer + description: CPU time used + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Cumulative + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.cpu.delta: + type: org.onap.capabilities.metric.Ceilometer + description: CPU time used since previous datapoint + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Delta + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu.delta + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_0.memory.resident: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance on the physical machine + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.resident + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.vcpus: + type: org.onap.capabilities.metric.Ceilometer + description: Average disk latency + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ms + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: vcpus + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.memory.usage: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance from the amount of its allocated memory + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.usage + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_0.cpu.delta: + type: org.onap.capabilities.metric.Ceilometer + description: CPU time used since previous datapoint + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Delta + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu.delta + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.instance:type: + type: org.onap.capabilities.metric.Ceilometer + description: Existence of instance (OpenStack types) + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance:type + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_0.os: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + properties: + distribution: + type: string + required: false + type: + type: string + required: false + version: + type: version + required: false + architecture: + type: string + required: false + vlb_private_0_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vlb_0.host: + type: tosca.capabilities.Container + occurrences: + - 1 + - UNBOUNDED + valid_source_types: + - tosca.nodes.SoftwareComponent + properties: + num_cpus: + type: integer + required: false + disk_size: + type: scalar-unit.size + required: false + cpu_frequency: + type: scalar-unit.frequency + required: false + mem_size: + type: scalar-unit.size + required: false + vlb_0.instance:type: + type: org.onap.capabilities.metric.Ceilometer + description: Existence of instance (OpenStack types) + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance:type + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_private_network.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vdns_0.binding: + type: tosca.capabilities.network.Bindable + occurrences: + - 0 + - UNBOUNDED + vlb_private_network.link: + type: tosca.capabilities.network.Linkable + occurrences: + - 0 + - UNBOUNDED + vlb_0.cpu_util: + type: org.onap.capabilities.metric.Ceilometer + description: Average CPU utilization + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: '%' + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu_util + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_0.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vdns_private_0_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vdns_0.cpu_util: + type: org.onap.capabilities.metric.Ceilometer + description: Average CPU utilization + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: '%' + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu_util + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vdns_0.instance: + type: org.onap.capabilities.metric.Ceilometer + description: Existence of instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_private_network.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vdns_0.scalable: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + properties: + max_instances: + type: integer + default: 1 + min_instances: + type: integer + default: 1 + default_instances: + type: integer + vdns_private_1_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vlb_0.memory.usage: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance from the amount of its allocated memory + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.usage + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vlb_0.endpoint: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + properties: + port_name: + type: string + required: false + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + secure: + type: boolean + default: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + url_path: + type: string + required: false + requirements: + vdns_0.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vlb_private_1_port.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + vlb_private_0_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vdns_private_0_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vlb_0.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vdns_private_0_port.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + vdns_0.local_storage: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + vlb_private_1_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vlb_private_network.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vlb_0.local_storage: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + vdns_private_1_port.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + vdns_private_1_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn diff --git a/ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-Eace933104d443b496b8-template.yml b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-Eace933104d443b496b8-template.yml new file mode 100644 index 000000000..38e6b01eb --- /dev/null +++ b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/resource-Eace933104d443b496b8-template.yml @@ -0,0 +1,2525 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 +metadata: + invariantUUID: 06fe411e-d006-4ac3-8b0e-fb4f13cd78d3 + UUID: 172ce7c5-c2e4-4f8d-b66c-edb49e8e548a + name: eace9331-04d4-43b4-96b8 + description: vendor software product + type: VF + category: Generic + subcategory: Abstract + resourceVendor: 31125954-23a0-4d41-95e5 + resourceVendorRelease: '1.0' +imports: +- NeutronPort: + file: resource-Neutronport-template.yml +- Eace933104d443b496b8.nodes.heat.vfw: + file: resource-Eace933104d443b496b8NodesHeatVfw-template.yml +- Eace933104d443b496b8.nodes.heat.vpg: + file: resource-Eace933104d443b496b8NodesHeatVpg-template.yml +- NeutronNet: + file: resource-Neutronnet-template.yml +- Eace933104d443b496b8.nodes.heat.vsn: + file: resource-Eace933104d443b496b8NodesHeatVsn-template.yml +topology_template: + inputs: + vf_module_id: + type: string + description: The vFirewall Module ID is provided by ONAP + repo_url_blob: + type: string + description: URL of the repository that hosts the demo packages + public_net_id: + type: string + default: 00000000-0000-0000-0000-000000000000 + description: Public network that enables remote connection to VNF + vfw_private_ip_1: + type: string + description: Private IP address that is assigned to the vFirewall to communicate with the vSink + vfw_private_ip_0: + type: string + description: Private IP address that is assigned to the vFirewall to communicate with the vPacketGenerator + vfw_private_ip_2: + type: string + description: Private IP address that is assigned to the vFirewall to communicate with ONAP components + vfw_name_0: + type: string + description: Name of the vFirewall + vnf_id: + type: string + description: The VNF ID is provided by ONAP + dcae_collector_ip: + type: string + description: IP address of the DCAE collector + dcae_collector_port: + type: string + description: Port of the DCAE collector + vpg_private_ip_1: + type: string + description: Private IP address that is assigned to the vPacketGenerator to communicate with ONAP components + vsn_private_ip_0: + type: string + description: Private IP address that is assigned to the vSink to communicate with the vFirewall + vpg_name_0: + type: string + description: Name of the vPacketGenerator + vpg_private_ip_0: + type: string + description: Private IP address that is assigned to the vPacketGenerator to communicate with the vFirewall + vsn_private_ip_1: + type: string + description: Private IP address that is assigned to the vSink to communicate with ONAP components + protected_private_net_cidr: + type: string + description: The CIDR of the protected private network + onap_private_net_cidr: + type: string + description: The CIDR of the protected private network + unprotected_private_net_cidr: + type: string + description: The CIDR of the unprotected private network + onap_private_subnet_id: + type: string + description: Private sub-network that connects ONAP component and the VNF + vsn_name_0: + type: string + description: Name of the vSink + unprotected_private_net_id: + type: string + description: Private network that connects vPacketGenerator with vFirewall + vfw_flavor_name: + type: string + default: 4 GB General Purpose v1 + description: Type of instance (flavor) to be used + demo_artifacts_version: + type: string + description: Artifacts (jar, tar.gz) version used in demo vnfs + onap_private_net_id: + type: string + description: Private network that connects ONAP component and the VNF + pub_key: + type: string + description: Public key to be installed on the compute instance + key_name: + type: string + description: Public/Private key pair name + repo_url_artifacts: + type: string + description: URL of the repository that hosts the demo packages + vfw_image_name: + type: string + default: Ubuntu 14.04 LTS (Trusty Tahr) (PVHVM) + description: Image to be used for compute instance + protected_private_net_id: + type: string + description: Private network that connects vFirewall with vSink + node_templates: + vfw_private_0_port: + type: org.onap.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: unprotected_private_network + ip_address: + get_input: vfw_private_ip_0 + network: unprotected_private_network + requirements: + - link: + capability: tosca.capabilities.network.Linkable + node: unprotected_private_network + relationship: tosca.relationships.network.LinksTo + - binding: + capability: tosca.capabilities.network.Bindable + node: vfw_0 + relationship: tosca.relationships.network.BindsTo + vsn_private_1_port: + type: org.onap.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: + get_input: onap_private_subnet_id + ip_address: + get_input: vsn_private_ip_1 + network: + get_input: onap_private_net_id + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: vsn_0 + relationship: tosca.relationships.network.BindsTo + unprotected_private_network: + type: org.onap.resource.vl.nodes.heat.network.neutron.Net + metadata: + invariantUUID: 2870cc3a-d6cd-4423-b7f6-2d63619b0eeb + UUID: b7e764ba-17f9-4f0a-ad29-29877766ef21 + version: '1.0' + name: NeutronNet + description: Represents a network service with optional subnets and advanced configurations. + type: VL + category: Generic + subcategory: Network Elements + properties: + network_name: + get_input: unprotected_private_net_id + subnets: + unprotected_private_subnet: + cidr: + get_input: unprotected_private_net_cidr + vpg_private_1_port: + type: org.onap.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: + get_input: onap_private_subnet_id + ip_address: + get_input: vpg_private_ip_1 + network: + get_input: onap_private_net_id + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: vpg_0 + relationship: tosca.relationships.network.BindsTo + vfw_0: + type: org.onap.resource.vfc.Eace933104d443b496b8.abstact.nodes.heat.vfw + metadata: + invariantUUID: 0129e34c-d9fa-442d-bb2c-f925d018000a + UUID: 7fa1f6c7-c6bd-4444-8db2-63334a5aed1b + version: '1.0' + name: Eace933104d443b496b8.nodes.heat.vfw + description: Not reusable inner VFC + type: VFC + category: Generic + subcategory: Abstract + properties: + key_name: UNSUPPORTED_RESOURCE_my_keypair + flavor: + get_input: vfw_flavor_name + image: + get_input: vfw_image_name + metadata: + vf_module_id: + get_input: vf_module_id + vnf_id: + get_input: vnf_id + user_data_format: RAW + name: + get_input: vfw_name_0 + vsn_0: + type: org.onap.resource.vfc.Eace933104d443b496b8.abstact.nodes.heat.vsn + metadata: + invariantUUID: b19f6643-3db0-4d73-b280-94d6f21caa71 + UUID: 6dca6eb9-330c-4090-a542-7aca5f446e21 + version: '1.0' + name: Eace933104d443b496b8.nodes.heat.vsn + description: Not reusable inner VFC + type: VFC + category: Generic + subcategory: Abstract + properties: + key_name: UNSUPPORTED_RESOURCE_my_keypair + flavor: + get_input: vfw_flavor_name + image: + get_input: vfw_image_name + metadata: + vf_module_id: + get_input: vf_module_id + vnf_id: + get_input: vnf_id + user_data_format: RAW + name: + get_input: vsn_name_0 + vpg_private_0_port: + type: org.onap.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: unprotected_private_network + ip_address: + get_input: vpg_private_ip_0 + network: unprotected_private_network + requirements: + - link: + capability: tosca.capabilities.network.Linkable + node: unprotected_private_network + relationship: tosca.relationships.network.LinksTo + - binding: + capability: tosca.capabilities.network.Bindable + node: vpg_0 + relationship: tosca.relationships.network.BindsTo + vsn_private_0_port: + type: org.onap.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: protected_private_network + ip_address: + get_input: vsn_private_ip_0 + network: protected_private_network + requirements: + - link: + capability: tosca.capabilities.network.Linkable + node: protected_private_network + relationship: tosca.relationships.network.LinksTo + - binding: + capability: tosca.capabilities.network.Bindable + node: vsn_0 + relationship: tosca.relationships.network.BindsTo + vfw_private_1_port: + type: org.onap.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: protected_private_network + ip_address: + get_input: vfw_private_ip_1 + network: protected_private_network + requirements: + - link: + capability: tosca.capabilities.network.Linkable + node: protected_private_network + relationship: tosca.relationships.network.LinksTo + - binding: + capability: tosca.capabilities.network.Bindable + node: vfw_0 + relationship: tosca.relationships.network.BindsTo + vfw_private_2_port: + type: org.onap.resource.cp.nodes.heat.network.neutron.Port + metadata: + invariantUUID: 7feb77d3-dcc5-4826-8a78-0c9089814a45 + UUID: 06bc8ea7-0f6a-489a-9f8f-c7253653b457 + version: '1.0' + name: NeutronPort + description: Represents a logical entity that associates between Compute and Network normative types. + type: CP + category: Generic + subcategory: Network Elements + properties: + fixed_ips: + - subnet: + get_input: onap_private_subnet_id + ip_address: + get_input: vfw_private_ip_2 + network: + get_input: onap_private_net_id + requirements: + - binding: + capability: tosca.capabilities.network.Bindable + node: vfw_0 + relationship: tosca.relationships.network.BindsTo + vpg_0: + type: org.onap.resource.vfc.Eace933104d443b496b8.abstact.nodes.heat.vpg + metadata: + invariantUUID: 7654ae14-4e98-45bc-a8c0-2c43e1805bb4 + UUID: 5267d6dd-f676-4f98-abec-6387ce6beaf2 + version: '1.0' + name: Eace933104d443b496b8.nodes.heat.vpg + description: Not reusable inner VFC + type: VFC + category: Generic + subcategory: Abstract + properties: + key_name: UNSUPPORTED_RESOURCE_my_keypair + flavor: + get_input: vfw_flavor_name + image: + get_input: vfw_image_name + metadata: + vf_module_id: + get_input: vf_module_id + vnf_id: + get_input: vnf_id + user_data_format: RAW + name: + get_input: vpg_name_0 + protected_private_network: + type: org.onap.resource.vl.nodes.heat.network.neutron.Net + metadata: + invariantUUID: 2870cc3a-d6cd-4423-b7f6-2d63619b0eeb + UUID: b7e764ba-17f9-4f0a-ad29-29877766ef21 + version: '1.0' + name: NeutronNet + description: Represents a network service with optional subnets and advanced configurations. + type: VL + category: Generic + subcategory: Network Elements + properties: + network_name: + get_input: protected_private_net_id + subnets: + protected_private_subnet: + cidr: + get_input: protected_private_net_cidr + groups: + base_vfw: + type: org.onap.groups.heat.HeatStack + members: + - vfw_private_0_port + - vsn_private_1_port + - unprotected_private_network + - vpg_private_1_port + - vfw_0 + - vsn_0 + - vpg_private_0_port + - vsn_private_0_port + - vfw_private_1_port + - vfw_private_2_port + - vpg_0 + - protected_private_network + metadata: + invariantUUID: 44b0c172-7b61-49b5-a68a-810042087e1f + UUID: 24cb02f0-1d72-441f-a327-22d80180deaa + version: '1' + name: base_vfw + Eace933104d443b496b8..base_vfw..module-0: + type: org.onap.groups.VfModule + members: + - vfw_private_0_port + - vsn_private_1_port + - unprotected_private_network + - vpg_private_1_port + - vfw_0 + - vsn_0 + - vpg_private_0_port + - vsn_private_0_port + - vfw_private_1_port + - vfw_private_2_port + - vpg_0 + - protected_private_network + metadata: + vfModuleModelName: Eace933104d443b496b8..base_vfw..module-0 + vfModuleModelInvariantUUID: 58c105fd-9c12-4fb7-8a3e-a5ec280183fb + vfModuleModelUUID: ab251d24-4001-4926-aa5c-c01736b36c68 + vfModuleModelVersion: '1' + properties: + vf_module_type: Base + vf_module_description: + volume_group: false + substitution_mappings: + node_type: org.onap.resource.vf.Eace933104d443b496b8 + capabilities: + vfw_0.instance: + type: org.onap.capabilities.metric.Ceilometer + description: Existence of instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vfw_0.scalable: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + properties: + max_instances: + type: integer + default: 1 + min_instances: + type: integer + default: 1 + default_instances: + type: integer + vfw_0.instance:type: + type: org.onap.capabilities.metric.Ceilometer + description: Existence of instance (OpenStack types) + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance:type + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + protected_private_network.link: + type: tosca.capabilities.network.Linkable + occurrences: + - 0 + - UNBOUNDED + vsn_0.cpu: + type: org.onap.capabilities.metric.Ceilometer + description: CPU time used + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Cumulative + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.instance:type: + type: org.onap.capabilities.metric.Ceilometer + description: Existence of instance (OpenStack types) + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance:type + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + unprotected_private_network.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vfw_0.memory: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM allocated to the instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.cpu_util: + type: org.onap.capabilities.metric.Ceilometer + description: Average CPU utilization + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: '%' + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu_util + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.endpoint: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + properties: + port_name: + type: string + required: false + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + secure: + type: boolean + default: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + url_path: + type: string + required: false + vpg_private_0_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vfw_private_1_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vfw_private_0_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vpg_0.cpu: + type: org.onap.capabilities.metric.Ceilometer + description: CPU time used + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Cumulative + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_private_1_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vsn_0.vcpus: + type: org.onap.capabilities.metric.Ceilometer + description: Average disk latency + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ms + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: vcpus + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.cpu.delta: + type: org.onap.capabilities.metric.Ceilometer + description: CPU time used since previous datapoint + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Delta + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu.delta + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vsn_private_1_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vsn_0.cpu_util: + type: org.onap.capabilities.metric.Ceilometer + description: Average CPU utilization + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: '%' + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu_util + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.instance: + type: org.onap.capabilities.metric.Ceilometer + description: Existence of instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vpg_0.scalable: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + properties: + max_instances: + type: integer + default: 1 + min_instances: + type: integer + default: 1 + default_instances: + type: integer + vpg_0.memory: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM allocated to the instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vfw_private_2_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vsn_0.os: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + properties: + distribution: + type: string + required: false + type: + type: string + required: false + version: + type: version + required: false + architecture: + type: string + required: false + vfw_0.memory.resident: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance on the physical machine + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.resident + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vsn_0.scalable: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + properties: + max_instances: + type: integer + default: 1 + min_instances: + type: integer + default: 1 + default_instances: + type: integer + vsn_0.instance: + type: org.onap.capabilities.metric.Ceilometer + description: Existence of instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vfw_0.endpoint: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + properties: + port_name: + type: string + required: false + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + secure: + type: boolean + default: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + url_path: + type: string + required: false + vsn_0.cpu.delta: + type: org.onap.capabilities.metric.Ceilometer + description: CPU time used since previous datapoint + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Delta + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu.delta + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vfw_0.os: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + properties: + distribution: + type: string + required: false + type: + type: string + required: false + version: + type: version + required: false + architecture: + type: string + required: false + vsn_private_1_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vsn_private_0_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vfw_0.memory.usage: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance from the amount of its allocated memory + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.usage + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vsn_0.host: + type: tosca.capabilities.Container + occurrences: + - 1 + - UNBOUNDED + valid_source_types: + - tosca.nodes.SoftwareComponent + properties: + num_cpus: + type: integer + required: false + disk_size: + type: scalar-unit.size + required: false + cpu_frequency: + type: scalar-unit.frequency + required: false + mem_size: + type: scalar-unit.size + required: false + vsn_0.memory: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM allocated to the instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + unprotected_private_network.link: + type: tosca.capabilities.network.Linkable + occurrences: + - 0 + - UNBOUNDED + vfw_0.host: + type: tosca.capabilities.Container + occurrences: + - 1 + - UNBOUNDED + valid_source_types: + - tosca.nodes.SoftwareComponent + properties: + num_cpus: + type: integer + required: false + disk_size: + type: scalar-unit.size + required: false + cpu_frequency: + type: scalar-unit.frequency + required: false + mem_size: + type: scalar-unit.size + required: false + vsn_private_0_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vfw_private_2_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + unprotected_private_network.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vpg_0.vcpus: + type: org.onap.capabilities.metric.Ceilometer + description: Average disk latency + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ms + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: vcpus + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.binding: + type: tosca.capabilities.network.Bindable + occurrences: + - 0 + - UNBOUNDED + vpg_0.host: + type: tosca.capabilities.Container + occurrences: + - 1 + - UNBOUNDED + valid_source_types: + - tosca.nodes.SoftwareComponent + properties: + num_cpus: + type: integer + required: false + disk_size: + type: scalar-unit.size + required: false + cpu_frequency: + type: scalar-unit.frequency + required: false + mem_size: + type: scalar-unit.size + required: false + vsn_0.binding: + type: tosca.capabilities.network.Bindable + occurrences: + - 0 + - UNBOUNDED + protected_private_network.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vfw_0.binding: + type: tosca.capabilities.network.Bindable + occurrences: + - 0 + - UNBOUNDED + vpg_0.memory.usage: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance from the amount of its allocated memory + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.usage + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vfw_private_0_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vsn_0.endpoint: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + properties: + port_name: + type: string + required: false + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + secure: + type: boolean + default: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + url_path: + type: string + required: false + vfw_0.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + protected_private_network.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vfw_0.cpu: + type: org.onap.capabilities.metric.Ceilometer + description: CPU time used + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Cumulative + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vsn_0.instance:type: + type: org.onap.capabilities.metric.Ceilometer + description: Existence of instance (OpenStack types) + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance:type + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.os: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + properties: + distribution: + type: string + required: false + type: + type: string + required: false + version: + type: version + required: false + architecture: + type: string + required: false + vsn_0.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vfw_0.vcpus: + type: org.onap.capabilities.metric.Ceilometer + description: Average disk latency + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ms + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: vcpus + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vfw_0.cpu.delta: + type: org.onap.capabilities.metric.Ceilometer + description: CPU time used since previous datapoint + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Delta + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu.delta + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vsn_0.memory.resident: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance on the physical machine + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.resident + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vsn_0.memory.usage: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance from the amount of its allocated memory + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.usage + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vfw_private_1_port.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + vfw_0.cpu_util: + type: org.onap.capabilities.metric.Ceilometer + description: Average CPU utilization + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: '%' + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu_util + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_0.memory.resident: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance on the physical machine + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.resident + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + vpg_private_0_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + vpg_private_1_port.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + requirements: + vsn_private_1_port.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + vfw_0.local_storage: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + vfw_private_1_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vpg_private_1_port.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + vsn_0.local_storage: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + protected_private_network.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vfw_private_2_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vfw_private_2_port.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo + unprotected_private_network.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vsn_private_0_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vpg_0.local_storage: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + vsn_private_1_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vfw_0.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vpg_0.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vpg_private_1_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vsn_0.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vpg_private_0_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + vfw_private_0_port.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn diff --git a/ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-57e66ea70ed645c7970f-template.yml b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-57e66ea70ed645c7970f-template.yml new file mode 100644 index 000000000..4bfd629e9 --- /dev/null +++ b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-57e66ea70ed645c7970f-template.yml @@ -0,0 +1,677 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 +metadata: + invariantUUID: 5cfe6f4a-41bc-4247-8674-ebd4b98e35cc + UUID: 0f40bba5-986e-4b3c-803f-ddd1b7b25f24 + name: 57e66ea7-0ed6-45c7-970f + description: catalog service description + type: Service + category: Network L1-3 + serviceOnapNaming: false + serviceHoming: false +imports: +- eace9331-04d4-43b4-96b8: + file: resource-Eace933104d443b496b8-template.yml +topology_template: + node_templates: + eace9331-04d4-43b4-96b8 1: + type: org.onap.resource.vf.Eace933104d443b496b8 + metadata: + invariantUUID: 06fe411e-d006-4ac3-8b0e-fb4f13cd78d3 + UUID: 172ce7c5-c2e4-4f8d-b66c-edb49e8e548a + version: '1.0' + name: eace9331-04d4-43b4-96b8 + description: vendor software product + type: VF + category: Generic + subcategory: Abstract + substitution_mappings: + node_type: org.onap.service.57e66ea70ed645c7970f + capabilities: + eace9331-04d4-43b4-96b8 1.memory.resident: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance on the physical machine + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.resident + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.os: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + properties: + distribution: + type: string + required: false + type: + type: string + required: false + version: + type: version + required: false + architecture: + type: string + required: false + eace9331-04d4-43b4-96b8 1.binding: + type: tosca.capabilities.network.Bindable + occurrences: + - 0 + - UNBOUNDED + eace9331-04d4-43b4-96b8 1.host: + type: tosca.capabilities.Container + occurrences: + - 1 + - UNBOUNDED + valid_source_types: + - tosca.nodes.SoftwareComponent + properties: + num_cpus: + type: integer + required: false + disk_size: + type: scalar-unit.size + required: false + cpu_frequency: + type: scalar-unit.frequency + required: false + mem_size: + type: scalar-unit.size + required: false + eace9331-04d4-43b4-96b8 1.instance: + type: org.onap.capabilities.metric.Ceilometer + description: Existence of instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.scalable: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + properties: + max_instances: + type: integer + default: 1 + min_instances: + type: integer + default: 1 + default_instances: + type: integer + eace9331-04d4-43b4-96b8 1.memory: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM allocated to the instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + eace9331-04d4-43b4-96b8 1.vcpus: + type: org.onap.capabilities.metric.Ceilometer + description: Average disk latency + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ms + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: vcpus + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.cpu_util: + type: org.onap.capabilities.metric.Ceilometer + description: Average CPU utilization + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: '%' + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu_util + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.cpu.delta: + type: org.onap.capabilities.metric.Ceilometer + description: CPU time used since previous datapoint + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Delta + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu.delta + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + eace9331-04d4-43b4-96b8 1.cpu: + type: org.onap.capabilities.metric.Ceilometer + description: CPU time used + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Cumulative + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.instance:type: + type: org.onap.capabilities.metric.Ceilometer + description: Existence of instance (OpenStack types) + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance:type + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.link: + type: tosca.capabilities.network.Linkable + occurrences: + - 0 + - UNBOUNDED + eace9331-04d4-43b4-96b8 1.memory.usage: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance from the amount of its allocated memory + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.usage + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + eace9331-04d4-43b4-96b8 1.endpoint: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + properties: + port_name: + type: string + required: false + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + secure: + type: boolean + default: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + url_path: + type: string + required: false + requirements: + eace9331-04d4-43b4-96b8 1.local_storage: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + eace9331-04d4-43b4-96b8 1.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + eace9331-04d4-43b4-96b8 1.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo diff --git a/ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-D473899264974dca9db9-template.yml b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-D473899264974dca9db9-template.yml new file mode 100644 index 000000000..2293b3aca --- /dev/null +++ b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0/Demo-1.0.0-HeatTemplates/service-D473899264974dca9db9-template.yml @@ -0,0 +1,677 @@ +tosca_definitions_version: tosca_simple_yaml_1_0 +metadata: + invariantUUID: dc112d6e-7e73-4777-9c6f-1a7fb5fd1b6f + UUID: 2eea06c6-e1d3-4c3a-b9c4-478c506eeedf + name: d4738992-6497-4dca-9db9 + description: catalog service description + type: Service + category: Network L1-3 + serviceOnapNaming: false + serviceHoming: false +imports: +- 59a2ee3f-b580-45fe-b5a1: + file: resource-59a2ee3fB58045feB5a1-template.yml +topology_template: + node_templates: + 59a2ee3f-b580-45fe-b5a1 1: + type: org.onap.resource.vf.59a2ee3fB58045feB5a1 + metadata: + invariantUUID: 4b8d4018-068b-4c33-b9bb-d980798e52c2 + UUID: d7d28881-b24d-4512-bfee-1e2eb335591f + version: '1.0' + name: 59a2ee3f-b580-45fe-b5a1 + description: vendor software product + type: VF + category: Generic + subcategory: Abstract + substitution_mappings: + node_type: org.onap.service.D473899264974dca9db9 + capabilities: + 59a2ee3f-b580-45fe-b5a1 1.memory.resident: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance on the physical machine + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.resident + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.endpoint: + type: tosca.capabilities.Endpoint.Admin + occurrences: + - 1 + - UNBOUNDED + properties: + port_name: + type: string + required: false + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + secure: + type: boolean + default: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.attachment: + type: tosca.capabilities.Attachment + occurrences: + - 1 + - UNBOUNDED + 59a2ee3f-b580-45fe-b5a1 1.feature: + type: tosca.capabilities.Node + occurrences: + - 1 + - UNBOUNDED + 59a2ee3f-b580-45fe-b5a1 1.binding: + type: tosca.capabilities.network.Bindable + occurrences: + - 0 + - UNBOUNDED + 59a2ee3f-b580-45fe-b5a1 1.vcpus: + type: org.onap.capabilities.metric.Ceilometer + description: Average disk latency + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ms + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: vcpus + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.host: + type: tosca.capabilities.Container + occurrences: + - 1 + - UNBOUNDED + valid_source_types: + - tosca.nodes.SoftwareComponent + properties: + num_cpus: + type: integer + required: false + disk_size: + type: scalar-unit.size + required: false + cpu_frequency: + type: scalar-unit.frequency + required: false + mem_size: + type: scalar-unit.size + required: false + 59a2ee3f-b580-45fe-b5a1 1.memory.usage: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM used by the instance from the amount of its allocated memory + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory.usage + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.instance: + type: org.onap.capabilities.metric.Ceilometer + description: Existence of instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.scalable: + type: tosca.capabilities.Scalable + occurrences: + - 1 + - UNBOUNDED + properties: + max_instances: + type: integer + default: 1 + min_instances: + type: integer + default: 1 + default_instances: + type: integer + 59a2ee3f-b580-45fe-b5a1 1.cpu_util: + type: org.onap.capabilities.metric.Ceilometer + description: Average CPU utilization + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: '%' + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu_util + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.instance:type: + type: org.onap.capabilities.metric.Ceilometer + description: Existence of instance (OpenStack types) + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: instance + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: instance:type + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.cpu.delta: + type: org.onap.capabilities.metric.Ceilometer + description: CPU time used since previous datapoint + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Delta + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu.delta + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.memory: + type: org.onap.capabilities.metric.Ceilometer + description: Volume of RAM allocated to the instance + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Gauge + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: MB + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: memory + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.link: + type: tosca.capabilities.network.Linkable + occurrences: + - 0 + - UNBOUNDED + 59a2ee3f-b580-45fe-b5a1 1.cpu: + type: org.onap.capabilities.metric.Ceilometer + description: CPU time used + occurrences: + - 1 + - UNBOUNDED + properties: + initiator: + type: string + default: source + network_name: + type: string + default: PRIVATE + required: false + description: + type: string + description: Description of the metric + required: false + type: + type: string + default: Cumulative + description: Type of the metric value, for an example, Cumulative, Delta, Gauge and etc. + required: true + ports: + type: map + required: false + entry_schema: + type: PortSpec + secure: + type: boolean + default: false + port_name: + type: string + required: false + unit: + type: string + default: ns + description: Unit of the metric value + required: true + protocol: + type: string + default: tcp + port: + type: PortDef + required: false + name: + type: string + default: cpu + description: Ceilometer metric type name to monitor. (The name ceilometer is using) + required: true + category: + type: string + default: compute + description: Category of the metric, for an example, compute, disk, network, storage and etc. + required: false + url_path: + type: string + required: false + 59a2ee3f-b580-45fe-b5a1 1.os: + type: tosca.capabilities.OperatingSystem + occurrences: + - 1 + - UNBOUNDED + properties: + distribution: + type: string + required: false + type: + type: string + required: false + version: + type: version + required: false + architecture: + type: string + required: false + requirements: + 59a2ee3f-b580-45fe-b5a1 1.local_storage: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Attachment + node: tosca.nodes.BlockStorage + relationship: tosca.relationships.AttachesTo + 59a2ee3f-b580-45fe-b5a1 1.dependency: + occurrences: + - 0 + - UNBOUNDED + capability: tosca.capabilities.Node + node: tosca.nodes.Root + relationship: tosca.relationships.DependsOn + 59a2ee3f-b580-45fe-b5a1 1.link: + occurrences: + - 1 + - 1 + capability: tosca.capabilities.network.Linkable + relationship: tosca.relationships.network.LinksTo diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/pgstreams.json b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0/pgstreams.json similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/pgstreams.json rename to ONAP-ControlloopPolicy/src/test/resources/v2.0.0/pgstreams.json diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/policy_OpenECOMP_demo_vDNS.yaml b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0/policy_ONAP_demo_vDNS.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/policy_OpenECOMP_demo_vDNS.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v2.0.0/policy_ONAP_demo_vDNS.yaml diff --git a/ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/policy_OpenECOMP_demo_vFirewall.yaml b/ONAP-ControlloopPolicy/src/test/resources/v2.0.0/policy_ONAP_demo_vFirewall.yaml similarity index 100% rename from ECOMP-ControlloopPolicy/src/test/resources/v2.0.0/policy_OpenECOMP_demo_vFirewall.yaml rename to ONAP-ControlloopPolicy/src/test/resources/v2.0.0/policy_ONAP_demo_vFirewall.yaml diff --git a/ECOMP-PAP-REST/.gitignore b/ONAP-PAP-REST/.gitignore similarity index 100% rename from ECOMP-PAP-REST/.gitignore rename to ONAP-PAP-REST/.gitignore diff --git a/ECOMP-PAP-REST/WebContent/META-INF/MANIFEST.MF b/ONAP-PAP-REST/WebContent/META-INF/MANIFEST.MF similarity index 100% rename from ECOMP-PAP-REST/WebContent/META-INF/MANIFEST.MF rename to ONAP-PAP-REST/WebContent/META-INF/MANIFEST.MF diff --git a/ECOMP-PAP-REST/WebContent/README.txt b/ONAP-PAP-REST/WebContent/README.txt similarity index 100% rename from ECOMP-PAP-REST/WebContent/README.txt rename to ONAP-PAP-REST/WebContent/README.txt diff --git a/ONAP-PAP-REST/autopush.properties b/ONAP-PAP-REST/autopush.properties new file mode 100644 index 000000000..e7428d8ee --- /dev/null +++ b/ONAP-PAP-REST/autopush.properties @@ -0,0 +1,22 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PAP-REST +# ================================================================================ +# 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========================================================= +### + +default.policyType= +default.policyScope= diff --git a/ONAP-PAP-REST/dictionaryItemsAPI.json b/ONAP-PAP-REST/dictionaryItemsAPI.json new file mode 100644 index 000000000..cb259f387 --- /dev/null +++ b/ONAP-PAP-REST/dictionaryItemsAPI.json @@ -0,0 +1,52 @@ +{ + "dictionary": [{ + "type": "commmon", + "dictionaries": [{ + "name": "attribute", + "table": "Attribute", + "fields": [{ + "name": "xacmlId" + }, { + "name": "description" + }, { + "name": "categoryBean" + }, { + "name": "datatypeBean" + }, { + "name": "priority" + }, { + "name": "attributeValue" + }] + }, { + "name": "onapname", + "table": "OnapName", + "fields": [{ + "name": "onapName" + }, { + "name": "description" + }] + }] + }, { + "type": "action", + "dictionaries": [{ + "name": "action", + "table": "ActionPolicyDict", + "fields": [{ + "name": "type" + }, { + "name": "url" + }, { + "name": "method" + }, { + "name": "header" + }, { + "name": "body" + }, { + "name": "attributeName" + }, { + "name": "description" + }] + }] + }] + +} diff --git a/ONAP-PAP-REST/pip.properties b/ONAP-PAP-REST/pip.properties new file mode 100644 index 000000000..b5d46af57 --- /dev/null +++ b/ONAP-PAP-REST/pip.properties @@ -0,0 +1,15 @@ +# +# Default PIP Configuration from Policy. +# +xacml.pip.engines=AAF,historydb + +### AAF PIP Configuration. +AAF.description=AAFEngine to communicate with AAF to take decisions +AAF.classname=org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine +AAF.name=AAFEngine + +# PIP Engine Definition +# +historydb.classname=org.onap.policy.xacml.std.pip.engines.OperationHistoryEngine +historydb.issuer=org:onap:xacml:guard:historydb +historydb.name=operationHistoryDB \ No newline at end of file diff --git a/ONAP-PAP-REST/policyLogger.properties b/ONAP-PAP-REST/policyLogger.properties new file mode 100644 index 000000000..fc882b06b --- /dev/null +++ b/ONAP-PAP-REST/policyLogger.properties @@ -0,0 +1,44 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PAP-REST +# ================================================================================ +# 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========================================================= +### + +################################### Set concurrentHashMap and timer info ####################### +#Timer initial delay and the delay between in milliseconds before task is to be execute. +timer.delay.time=1000 +#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. +check.interval= 30000 +#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. +event.expired.time=86400 +#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed +#to remove all expired records from this concurrentHashMap. +concurrentHashMap.limit=5000 +#Size of the concurrentHashMap - when its size drops to this point, stop the Timer +stop.check.point=2500 +################################### Set logging format ############################################# +# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println +logger.type=EELF +#################################### Set level for EELF or SYSTEMOUT logging ################################## +# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all +debugLogger.level=INFO +# Set level for metrics file. Set OFF to disable; set ON to enable +metricsLogger.level=ON +# Set level for error file. Set OFF to disable; set ON to enable +error.level=ON +# Set level for audit file. Set OFF to disable; set ON to enable +audit.level=ON diff --git a/ONAP-PAP-REST/policyelk.properties b/ONAP-PAP-REST/policyelk.properties new file mode 100644 index 000000000..386008ce5 --- /dev/null +++ b/ONAP-PAP-REST/policyelk.properties @@ -0,0 +1,30 @@ +### +# ============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========================================================= +### + + +#Elk database url +policy.elk.url=http://localhost:9200 + + +#Policy Database properties +policy.database.driver=com.mysql.jdbc.Driver +policy.database.url=jdbc:mysql://localhost:3306/onap_sdk?autoReconnect=true&useSSL=false +policy.database.username=policy_user +policy.database.password=policy_user \ No newline at end of file diff --git a/ONAP-PAP-REST/pom.xml b/ONAP-PAP-REST/pom.xml new file mode 100644 index 000000000..fa20a6be5 --- /dev/null +++ b/ONAP-PAP-REST/pom.xml @@ -0,0 +1,344 @@ + + + + + + 4.0.0 + ONAP-PAP-REST + ONAP-PAP-REST + war + + org.onap.policy.engine + PolicyEngineSuite + 1.1.0-SNAPSHOT + + + + + maven-war-plugin + 2.1 + + true + + + src/main/java/ + WEB-INF/classes/ + + hibernate.cfg.xml + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.8 + 1.8 + + + + + + + + org.onap.policy.engine + PolicyEngineUtils + ${project.version} + + + com.att.aft + dme2 + + + org.json + json + + + com.att.nsa + dmaapClient + + + com.att.nsa + cambriaClient + + + com.att.cadi + cadi-aaf + + + + + org.apache.commons + commons-lang3 + 3.4 + + + org.onap.policy.engine + ONAP-PDP + ${project.version} + + + org.json + json + + + + + org.onap.policy.common + ONAP-Logging + ${common-modules.version} + + + org.powermock + powermock-module-junit4 + + + org.powermock + powermock-api-mockito + + + + + javax.servlet + javax.servlet-api + 3.1.0 + + + commons-logging + commons-logging + 1.1.3 + + + javax.servlet + servlet-api + + + + + org.apache.commons + commons-compress + 1.8 + + + commons-fileupload + commons-fileupload + 1.3.1 + + + org.apache.logging.log4j + log4j-core + 2.8.2 + + + log4j + apache-log4j-extras + 1.2.17 + + + commons-io + commons-io + 2.4 + + + io.netty + netty + 3.5.0.Final + + + com.google.guava + guava + 14.0.1 + + + org.eclipse.jgit + org.eclipse.jgit + 3.2.0.201312181205-r + + + junit + junit + 4.11 + test + + + org.apache.tomcat + tomcat-jdbc + 8.0.24 + + + com.h2database + h2 + [1.4.186,) + + + com.github.fge + json-patch + 1.9 + + + org.eclipse.persistence + javax.persistence + 2.1.0 + + + org.eclipse.persistence + eclipselink + 2.6.0 + + + + mysql + mysql-connector-java + 5.1.30 + + + org.springframework + spring-mock + 2.0.8 + + + org.onap.policy.engine + ControlloopPolicy + ${project.version} + + + com.mockrunner + mockrunner + 0.3.1 + + + + org.springframework + spring-core + ${springframework.version} + + + org.springframework + spring-web + ${springframework.version} + + + org.springframework + spring-webmvc + ${springframework.version} + + + org.springframework + spring-tx + ${springframework.version} + + + org.springframework + spring-context-support + ${springframework.version} + + + org.springframework + spring-orm + ${springframework.version} + + + + org.hibernate + hibernate-core + ${hibernate.version} + + + org.hibernate + hibernate-validator + 5.1.3.Final + + + + org.json + json + 20160810 + + + com.fasterxml.jackson.core + jackson-annotations + 2.6.3 + + + com.fasterxml.jackson.core + jackson-core + 2.6.3 + + + com.fasterxml.jackson.core + jackson-databind + 2.6.3 + + + com.fasterxml.jackson.module + jackson-module-jaxb-annotations + ${jackson.version} + + + com.fasterxml.jackson.module + jackson-module-jsonSchema + ${jackson.version} + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + ${jackson.version} + + + org.elasticsearch + elasticsearch + 5.1.2 + + + io.searchbox + jest + 2.0.4 + + + commons-logging + commons-logging + + + + + args4j + args4j + 2.32 + + + + org.apache.tomcat + tomcat-dbcp + 8.5.9 + + + + + 4.2.0.RELEASE + 4.3.10.Final + 2.0.2 + 2.6.0 + + diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java new file mode 100644 index 000000000..fee4ed2cb --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java @@ -0,0 +1,145 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import javax.annotation.PostConstruct; +import javax.sql.DataSource; + +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +import org.hibernate.SessionFactory; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; +import org.springframework.transaction.annotation.EnableTransactionManagement; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +@Configuration +@EnableWebMvc +@EnableTransactionManagement +@ComponentScan(basePackages = { "org.onap.*", "com.*" }) +public class PAPRestConfig extends WebMvcConfigurerAdapter { + private static final Logger LOGGER = FlexLogger.getLogger(PAPRestConfig.class); + + private static String dbDriver = null; + private static String dbUrl = null; + private static String dbUserName = null; + private static String dbPassword = null; + + @PostConstruct + public void init(){ + Properties prop = new Properties(); + InputStream input = null; + try { + input = new FileInputStream("xacml.pap.properties"); + // load a properties file + prop.load(input); + setDbDriver(prop.getProperty("javax.persistence.jdbc.driver")); + setDbUrl(prop.getProperty("javax.persistence.jdbc.url")); + setDbUserName(prop.getProperty("javax.persistence.jdbc.user")); + setDbPassword(prop.getProperty("javax.persistence.jdbc.password")); + }catch(Exception e){ + LOGGER.error("Exception Occured while loading properties file"+e); + }finally{ + if(input != null){ + try { + input.close(); + } catch (IOException e) { + LOGGER.error("Exception Occured while clsoing the stream"+e); + } + } + } + } + + @Bean(name = "dataSource") + public DataSource getDataSource() { + BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName(PAPRestConfig.getDbDriver()); + dataSource.setUrl(PAPRestConfig.getDbUrl()); + dataSource.setUsername(PAPRestConfig.getDbUserName()); + dataSource.setPassword(PAPRestConfig.getDbPassword()); + return dataSource; + } + + @Autowired + @Bean(name = "sessionFactory") + public SessionFactory getSessionFactory(DataSource dataSource) { + LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource); + sessionBuilder.scanPackages("org.onap.*", "com.*"); + sessionBuilder.addProperties(getHibernateProperties()); + return sessionBuilder.buildSessionFactory(); + } + + private Properties getHibernateProperties() { + Properties properties = new Properties(); + properties.put("hibernate.show_sql", "true"); + properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); + return properties; + } + + @Autowired + @Bean(name = "transactionManager") + public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) { + return new HibernateTransactionManager(sessionFactory); + } + + public static String getDbDriver() { + return dbDriver; + } + + public static void setDbDriver(String dbDriver) { + PAPRestConfig.dbDriver = dbDriver; + } + + public static String getDbUrl() { + return dbUrl; + } + + public static void setDbUrl(String dbUrl) { + PAPRestConfig.dbUrl = dbUrl; + } + + public static String getDbUserName() { + return dbUserName; + } + + public static void setDbUserName(String dbUserName) { + PAPRestConfig.dbUserName = dbUserName; + } + + public static String getDbPassword() { + return dbPassword; + } + + public static void setDbPassword(String dbPassword) { + PAPRestConfig.dbPassword = dbPassword; + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/WebConfig.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/WebConfig.java new file mode 100644 index 000000000..89ab8bc8a --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/WebConfig.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest; + +import javax.servlet.ServletContext; +import javax.servlet.ServletRegistration; + +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +public class WebConfig implements WebApplicationInitializer { + + @Override + public void onStartup(ServletContext container) { + AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); + ctx.register(PAPRestConfig.class); + ctx.setServletContext(container); + ctx.refresh(); + ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(ctx)); + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/onap/*"); + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java new file mode 100644 index 000000000..45f803f5a --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java @@ -0,0 +1,2617 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest; + +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.ConnectException; +import java.net.HttpURLConnection; +import java.net.InetAddress; +import java.net.MalformedURLException; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.net.URLDecoder; +import java.net.UnknownHostException; +import java.nio.file.Files; +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.Iterator; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; + +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.PersistenceException; +import javax.servlet.Servlet; +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.io.IOUtils; +import org.onap.policy.common.ia.IntegrityAudit; +import org.onap.policy.common.im.AdministrativeStateException; +import org.onap.policy.common.im.ForwardProgressException; +import org.onap.policy.common.im.IntegrityMonitor; +import org.onap.policy.common.im.IntegrityMonitorProperties; +import org.onap.policy.common.im.StandbyStatusException; +import org.onap.policy.common.logging.ONAPLoggingContext; +import org.onap.policy.common.logging.ONAPLoggingUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.components.AutoPushPolicy; +import org.onap.policy.pap.xacml.rest.components.PolicyDBDao; +import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; +import org.onap.policy.pap.xacml.rest.handler.APIRequestHandler; +import org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler; +import org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler; +import org.onap.policy.pap.xacml.restAuth.CheckPDP; +import org.onap.policy.rest.XACMLRest; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory; +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.StdItemSetChangeListener; +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.FactoryException; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Splitter; + +/** + * Servlet implementation class XacmlPapServlet + */ +@WebServlet( + description = "Implements the XACML PAP RESTful API.", + urlPatterns = { "/" }, + loadOnStartup=1, + initParams = { + @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", description = "The location of the properties file holding configuration information.") + }) +public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable { + private static final long serialVersionUID = 1L; + private static final Logger LOGGER = FlexLogger.getLogger(XACMLPapServlet.class); + // audit (transaction) LOGGER + private static final Logger auditLogger = FlexLogger.getLogger("auditLogger"); + //Persistence Unit for JPA + private static final String PERSISTENCE_UNIT = "XACML-PAP-REST"; + private static final String AUDIT_PAP_PERSISTENCE_UNIT = "auditPapPU"; + // Client Headers. + private static final String ENVIRONMENT_HEADER = "Environment"; + /* + * List of Admin Console URLs. + * Used to send notifications when configuration changes. + * + * The CopyOnWriteArrayList *should* protect from concurrency errors. + * This list is seldom changed but often read, so the costs of this approach make sense. + */ + private static final CopyOnWriteArrayList adminConsoleURLStringList = new CopyOnWriteArrayList(); + + private static String CONFIG_HOME; + private static String ACTION_HOME; + /* + * This PAP instance's own URL. + * Need this when creating URLs to send to the PDPs so they can GET the Policy files from this process. + */ + private static String papURL = null; + // The heartbeat thread. + private static Heartbeat heartbeat = null; + private static Thread heartbeatThread = null; + //The entity manager factory for JPA access + private static EntityManagerFactory emf; + private static PolicyDBDao policyDBDao; + /* + * papEngine - This is our engine workhorse that manages the PDP Groups and Nodes. + */ + private static PAPPolicyEngine papEngine = null; + /* + * These are the parameters needed for DB access from the PAP + */ + private static int papIntegrityAuditPeriodSeconds = -1; + private static String papDbDriver = null; + private static String papDbUrl = null; + private static String papDbUser = null; + private static String papDbPassword = null; + private static Integer papTransWait = null; + private static Integer papTransTimeout = null; + private static Integer papAuditTimeout = null; + private static Boolean papAuditFlag = null; + private static Boolean papFileSystemAudit = null; + private static Boolean autoPushFlag = false; + private static String papResourceName = null; + private static Integer fpMonitorInterval = null; + private static Integer failedCounterThreshold = null; + private static Integer testTransInterval = null; + private static Integer writeFpcInterval = null; + private static String papSiteName=null; + private static String papNodeType=null; + private static String papDependencyGroups = null; + private static String[] papDependencyGroupsFlatArray = null; + private static String environment = null; + private static String pdpFile = null; + + private String storedRequestId = null; + private IntegrityMonitor im; + private IntegrityAudit ia; + + //MicroService Model Properties + private static String msOnapName; + private static String msPolicyName; + /* + * This thread may be invoked upon startup to initiate sending PDP policy/pip configuration when + * this servlet starts. Its configurable by the admin. + */ + private Thread initiateThread = null; + private ONAPLoggingContext baseLoggingContext = null; + private AutoPushPolicy autoPushPolicy; + + /** + * @see HttpServlet#HttpServlet() + */ + public XACMLPapServlet() { + super(); + } + + /** + * @see Servlet#init(ServletConfig) + */ + public void init(ServletConfig config) throws ServletException { + try { + // Logging + baseLoggingContext = new ONAPLoggingContext(); + // fixed data that will be the same in all logging output goes here + try { + String hostname = InetAddress.getLocalHost().getCanonicalHostName(); + baseLoggingContext.setServer(hostname); + } catch (UnknownHostException e) { + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging"); + } + // Initialize + XACMLRest.xacmlInit(config); + // Load the properties + XACMLRest.loadXacmlProperties(null, null); + /* + * Retrieve the property values + */ + CONFIG_HOME = getConfigHome(); + ACTION_HOME = getActionHome(); + papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER); + if(papDbDriver == null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbDriver property entry"); + throw new PAPException("papDbDriver is null"); + } + setPapDbDriver(papDbDriver); + papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); + if(papDbUrl == null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUrl property entry"); + throw new PAPException("papDbUrl is null"); + } + setPapDbUrl(papDbUrl); + papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER); + if(papDbUser == null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbUser property entry"); + throw new PAPException("papDbUser is null"); + } + setPapDbUser(papDbUser); + papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD); + if(papDbPassword == null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papDbPassword property entry"); + throw new PAPException("papDbPassword is null"); + } + setPapDbPassword(papDbPassword); + papResourceName = XACMLProperties.getProperty(XACMLRestProperties.PAP_RESOURCE_NAME); + if(papResourceName == null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papResourceName property entry"); + throw new PAPException("papResourceName is null"); + } + papSiteName = XACMLProperties.getProperty(XACMLRestProperties.PAP_SITE_NAME); + if(papSiteName == null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papSiteName property entry"); + throw new PAPException("papSiteName is null"); + } + papNodeType = XACMLProperties.getProperty(XACMLRestProperties.PAP_NODE_TYPE); + if(papNodeType == null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE,"XACMLPapServlet", " ERROR: Bad papNodeType property entry"); + throw new PAPException("papNodeType is null"); + } + environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); + //Integer will throw an exception of anything is missing or unrecognized + papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); + papTransTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)); + papAuditTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); + //Boolean will default to false if anything is missing or unrecognized + papAuditFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG)); + papFileSystemAudit = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG)); + //PAP Auto Push + autoPushFlag = Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PUSH_FLAG)); + // if Auto push then Load with properties. + if(autoPushFlag){ + String file; + try{ + file = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PUSH_FILE); + if(file.endsWith(".properties")){ + autoPushPolicy = new AutoPushPolicy(file); + }else{ + throw new PAPException(); + } + }catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Missing property or not a proper property file check for: " + XACMLRestProperties.PROP_PAP_PUSH_FILE ); + LOGGER.info("Overriding the autoPushFlag to False..."); + autoPushFlag = false; + } + } + papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS); + if(papDependencyGroups == null){ + throw new PAPException("papDependencyGroups is null"); + } + try{ + //Now we have flattened the array into a simple comma-separated list + papDependencyGroupsFlatArray = papDependencyGroups.split("[;,]"); + //clean up the entries + for (int i = 0 ; i < papDependencyGroupsFlatArray.length ; i ++){ + papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim(); + } + try{ + if(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null){ + papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim()); + } + }catch(Exception e){ + String msg = "integrity_audit_period_seconds "; + LOGGER.error("\n\nERROR: " + msg + "Bad property entry: " + e.getMessage() + "\n"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: " + msg +"Bad property entry"); + throw e; + } + }catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry"); + throw e; + } + //Integer will throw an exception of anything is missing or unrecognized + fpMonitorInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL)); + failedCounterThreshold = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD)); + testTransInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL)); + writeFpcInterval = Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL)); + LOGGER.debug("\n\n\n**************************************" + + "\n**************************************" + + "\n" + + "\n papDbDriver = " + papDbDriver + + "\n papDbUrl = " + papDbUrl + + "\n papDbUser = " + papDbUser + + "\n papDbPassword = " + papDbPassword + + "\n papTransWait = " + papTransWait + + "\n papTransTimeout = " + papTransTimeout + + "\n papAuditTimeout = " + papAuditTimeout + + "\n papAuditFlag = " + papAuditFlag + + "\n papFileSystemAudit = " + papFileSystemAudit + + "\n autoPushFlag = " + autoPushFlag + + "\n papResourceName = " + papResourceName + + "\n fpMonitorInterval = " + fpMonitorInterval + + "\n failedCounterThreshold = " + failedCounterThreshold + + "\n testTransInterval = " + testTransInterval + + "\n writeFpcInterval = " + writeFpcInterval + + "\n papSiteName = " + papSiteName + + "\n papNodeType = " + papNodeType + + "\n papDependencyGroupsList = " + papDependencyGroups + + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds + + "\n\n**************************************" + + "\n**************************************"); + // Pull custom persistence settings + Properties properties; + try { + properties = XACMLProperties.getProperties(); + LOGGER.debug("\n\n\n**************************************" + + "\n**************************************" + + "\n\n" + + "properties = " + properties + + "\n\n**************************************"); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: " + + "XACMLProperties.getProperties()"); + throw new ServletException(e.getMessage(), e.getCause()); + } + //Micro Service Properties + msOnapName=properties.getProperty("xacml.policy.msOnapName"); + setMsOnapName(msOnapName); + msPolicyName=properties.getProperty("xacml.policy.msPolicyName"); + setMsPolicyName(msPolicyName); + // PDPId File location + XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); + if (XACMLPapServlet.pdpFile == null) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: " + + XACMLRestProperties.PROP_PDP_IDFILE); + throw new PAPException("The PDP Id Authentication File Property :"+ XACMLRestProperties.PROP_PDP_IDFILE+ " is not Valid. "); + } + // Create an IntegrityMonitor + im = IntegrityMonitor.getInstance(papResourceName,properties); + // Create an IntegrityAudit + ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties); + ia.startAuditThread(); + // Create the entity manager factory + emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT, properties); + if (emf == null) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager factory with persistence unit: " + + PERSISTENCE_UNIT); + throw new ServletException("Unable to create Entity Manager Factory"); + } + // we are about to call the PDPs and give them their configuration. + // To do that we need to have the URL of this PAP so we can construct the Policy file URLs + XACMLPapServlet.papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + //Create the policyDBDao + policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(getEmf()); + // Load our PAP engine, first create a factory + ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY)); + // The factory knows how to go about creating a PAP Engine + XACMLPapServlet.papEngine = (PAPPolicyEngine) factory.newEngine(); + PolicyDBDaoTransaction addNewGroup = null; + try{ + if(((org.onap.policy.xacml.std.pap.StdEngine)papEngine).wasDefaultGroupJustAdded){ + addNewGroup = policyDBDao.getNewTransaction(); + OnapPDPGroup group = papEngine.getDefaultGroup(); + addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), "automaticallyAdded"); + addNewGroup.commitTransaction(); + addNewGroup = policyDBDao.getNewTransaction(); + addNewGroup.changeDefaultGroup(group, "automaticallyAdded"); + addNewGroup.commitTransaction(); + } + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Error creating new default group in the database"); + if(addNewGroup != null){ + addNewGroup.rollbackTransaction(); + } + } + policyDBDao.setPapEngine((PAPPolicyEngine) XACMLPapServlet.papEngine); + //boolean performFileToDatabaseAudit = false; + if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))){ + //get an AuditTransaction to lock out all other transactions + PolicyDBDaoTransaction auditTrans = policyDBDao.getNewAuditTransaction(); + policyDBDao.auditLocalDatabase(XACMLPapServlet.papEngine); + //release the transaction lock + auditTrans.close(); + } + + // Sanity check for URL. + if (XACMLPapServlet.papURL == null) { + throw new PAPException("The property " + XACMLRestProperties.PROP_PAP_URL + " is not valid: " + XACMLPapServlet.papURL); + } + // Configurable - have the PAP servlet initiate sending the latest PDP policy/pip configuration + // to all its known PDP nodes. + if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) { + this.initiateThread = new Thread(this); + this.initiateThread.start(); + } + // After startup, the PAP does Heartbeat's to each of the PDPs periodically + XACMLPapServlet.heartbeat = new Heartbeat((PAPPolicyEngine) XACMLPapServlet.papEngine); + XACMLPapServlet.heartbeatThread = new Thread(XACMLPapServlet.heartbeat); + XACMLPapServlet.heartbeatThread.start(); + + } catch (FactoryException | PAPException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine"); + throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: "+e); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine - unexpected error"); + throw new ServletException (XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: "+e); + } + } + + /** + * Thread used only during PAP startup to initiate change messages to all known PDPs. + * This must be on a separate thread so that any GET requests from the PDPs during this update can be serviced. + */ + @Override + public void run() { + // send the current configuration to all the PDPs that we know about + changed(); + } + + /** + * @see Servlet#destroy() + * + * Depending on how this servlet is run, we may or may not care about cleaning up the resources. + * For now we assume that we do care. + */ + public void destroy() { + // Make sure our threads are destroyed + if (XACMLPapServlet.heartbeatThread != null) { + // stop the heartbeat + try { + if (XACMLPapServlet.heartbeat != null) { + XACMLPapServlet.heartbeat.terminate(); + } + XACMLPapServlet.heartbeatThread.interrupt(); + XACMLPapServlet.heartbeatThread.join(); + } catch (InterruptedException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat"); + } + } + if (this.initiateThread != null) { + try { + this.initiateThread.interrupt(); + this.initiateThread.join(); + } catch (InterruptedException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread"); + } + } + } + + /** + * Called by: + * - PDP nodes to register themselves with the PAP, and + * - Admin Console to make changes in the PDP Groups. + * + * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) + */ + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + loggingContext.transactionStarted(); + loggingContext.setServiceName("PAP.post"); + if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPost) so we generated one"); + } else { + PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPost)"); + } + PolicyDBDaoTransaction pdpTransaction = null; + try { + im.startTransaction(); + } catch (AdministrativeStateException ae){ + String message = "POST interface called for PAP " + papResourceName + " but it has an Administrative" + + " state of " + im.getStateManager().getAdminState() + + "\n Exception Message: " + ae.getMessage(); + LOGGER.info(message); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + }catch (StandbyStatusException se) { + String message = "POST interface called for PAP " + papResourceName + " but it has a Standby Status" + + " of " + im.getStateManager().getStandbyStatus() + + "\n Exception Message: " + se.getMessage(); + LOGGER.info(message); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + } + try { + XACMLRest.dumpRequest(request); + // since getParameter reads the content string, explicitly get the content before doing that. + // Simply getting the inputStream seems to protect it against being consumed by getParameter. + request.getInputStream(); + String groupId = request.getParameter("groupId"); + String apiflag = request.getParameter("apiflag"); + if(groupId != null) { + // Is this from the Admin Console or API? + if(apiflag!=null && apiflag.equalsIgnoreCase("api")) { + // this is from the API so we need to check the client credentials before processing the request + if(!authorizeRequest(request)){ + String message = "PEP not Authorized for making this Request!!"; + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_FORBIDDEN, message); + im.endTransaction(); + return; + } + } + doACPost(request, response, groupId, loggingContext); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + // Request is from a PDP asking for its config. + loggingContext.setServiceName("PDP:PAP.register"); + // Get the PDP's ID + String id = this.getPDPID(request); + String jmxport = this.getPDPJMX(request); + LOGGER.info("Request(doPost) from PDP coming up: " + id); + // Get the PDP Object + OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id); + // Is it known? + if (pdp == null) { + LOGGER.info("Unknown PDP: " + id); + // Check PDP ID + if(CheckPDP.validateID(id)){ + pdpTransaction = policyDBDao.getNewTransaction(); + try { + pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister"); + XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport)); + } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException | PersistenceException e) { + pdpTransaction.rollbackTransaction(); + String message = "Failed to create new PDP for id: " + id; + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + im.endTransaction(); + return; + } + // get the PDP we just created + pdp = XACMLPapServlet.papEngine.getPDP(id); + if (pdp == null) { + if(pdpTransaction != null){ + pdpTransaction.rollbackTransaction(); + } + String message = "Failed to create new PDP for id: " + id; + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + im.endTransaction(); + return; + } + } else { + String message = "PDP is Unauthorized to Connect to PAP: "+ id; + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); + loggingContext.transactionEnded(); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "PDP not Authorized to connect to this PAP. Please contact the PAP Admin for registration."); + PolicyLogger.audit("Transaction Failed - See Error.log"); + im.endTransaction(); + return; + } + try{ + pdpTransaction.commitTransaction(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Could not commit transaction to put pdp in the database"); + } + } + if (jmxport != null && jmxport != ""){ + ((StdPDP) pdp).setJmxPort(Integer.valueOf(jmxport)); + } + // Get the PDP's Group + OnapPDPGroup group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp); + if (group == null) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "PDP not associated with any group, even the default"); + im.endTransaction(); + return; + } + // Determine what group the PDP node is in and get + // its policy/pip properties. + Properties policies = group.getPolicyProperties(); + Properties pipconfig = group.getPipConfigProperties(); + // Get the current policy/pip configuration that the PDP has + Properties pdpProperties = new Properties(); + pdpProperties.load(request.getInputStream()); + LOGGER.info("PDP Current Properties: " + pdpProperties.toString()); + LOGGER.info("Policies: " + (policies != null ? policies.toString() : "null")); + LOGGER.info("Pip config: " + (pipconfig != null ? pipconfig.toString() : "null")); + // Validate the node's properties + boolean isCurrent = this.isPDPCurrent(policies, pipconfig, pdpProperties); + // Send back current configuration + if (isCurrent == false) { + // Tell the PDP we are sending back the current policies/pip config + LOGGER.info("PDP configuration NOT current."); + if (policies != null) { + // Put URL's into the properties in case the PDP needs to + // retrieve them. + this.populatePolicyURL(request.getRequestURL(), policies); + // Copy the properties to the output stream + policies.store(response.getOutputStream(), ""); + } + if (pipconfig != null) { + // Copy the properties to the output stream + pipconfig.store(response.getOutputStream(), ""); + } + // We are good - and we are sending them information + response.setStatus(HttpServletResponse.SC_OK); + setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH); + } else { + // Tell them they are good + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE); + } + // tell the AC that something changed + notifyAC(); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + } catch (PAPException e) { + if(pdpTransaction != null){ + pdpTransaction.rollbackTransaction(); + } + LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(500, e.getMessage()); + im.endTransaction(); + return; + } + //Catch anything that fell through + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended"); + im.endTransaction(); + } + + /** + * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) + */ + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + loggingContext.transactionStarted(); + loggingContext.setServiceName("PAP.get"); + if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doGet) so we generated one"); + } else { + PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doGet)"); + } + try { + XACMLRest.dumpRequest(request); + String pathInfo = request.getRequestURI(); + LOGGER.info("path info: " + pathInfo); + if (pathInfo != null){ + //DO NOT do a im.startTransaction for the test request + if (pathInfo.equals("/pap/test")) { + testService(loggingContext, response); + return; + } + } + //This im.startTransaction() covers all other Get transactions + try { + im.startTransaction(); + } catch (AdministrativeStateException ae){ + String message = "GET interface called for PAP " + papResourceName + " but it has an Administrative" + + " state of " + im.getStateManager().getAdminState() + + "\n Exception Message: " + ae.getMessage(); + LOGGER.info(message); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + }catch (StandbyStatusException se) { + String message = "GET interface called for PAP " + papResourceName + " but it has a Standby Status" + + " of " + im.getStateManager().getStandbyStatus() + + "\n Exception Message: " + se.getMessage(); + LOGGER.info(message); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + } + // Request from the API to get the gitPath + String apiflag = request.getParameter("apiflag"); + if (apiflag!=null) { + if(authorizeRequest(request)){ + APIRequestHandler apiRequestHandler = new APIRequestHandler(); + apiRequestHandler.doGet(request,response, apiflag); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } else { + String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_FORBIDDEN, message); + im.endTransaction(); + return; + } + } + // Is this from the Admin Console? + String groupId = request.getParameter("groupId"); + if (groupId != null) { + // this is from the Admin Console, so handle separately + doACGet(request, response, groupId, loggingContext); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + // Get the PDP's ID + String id = this.getPDPID(request); + LOGGER.info("doGet from: " + id); + // Get the PDP Object + OnapPDP pdp = XACMLPapServlet.papEngine.getPDP(id); + // Is it known? + if (pdp == null) { + // Check if request came from localhost + if (request.getRemoteHost().equals("localhost") || + request.getRemoteHost().equals("127.0.0.1") || + request.getRemoteHost().equals(request.getLocalAddr())) { + // Return status information - basically all the groups + loggingContext.setServiceName("PAP.getGroups"); + Set groups = papEngine.getOnapPDPGroups(); + // convert response object to JSON and include in the response + ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(response.getOutputStream(), groups); + response.setHeader("content-type", "application/json"); + response.setStatus(HttpServletResponse.SC_OK); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr(); + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message); + im.endTransaction(); + return; + } + loggingContext.setServiceName("PAP.getPolicy"); + // Get the PDP's Group + OnapPDPGroup group = XACMLPapServlet.papEngine.getPDPGroup((OnapPDP) pdp); + if (group == null) { + String message = "No group associated with pdp " + pdp.getId(); + LOGGER.warn(XACMLErrorConstants.ERROR_PERMISSIONS + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_UNAUTHORIZED, message); + im.endTransaction(); + return; + } + // Which policy do they want? + String policyId = request.getParameter("id"); + if (policyId == null) { + String message = "Did not specify an id for the policy"; + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_NOT_FOUND, message); + im.endTransaction(); + return; + } + PDPPolicy policy = group.getPolicy(policyId); + if (policy == null) { + String message = "Unknown policy: " + policyId; + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_NOT_FOUND, message); + im.endTransaction(); + return; + } + LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n " + + "Policy Name : " + policy.getName() + "\n Policy URI: " + policy.getLocation().toString()); + try (InputStream is = new FileInputStream(((StdPDPGroup)group).getDirectory().toString()+File.separator+policyId); OutputStream os = response.getOutputStream()) { + // Send the policy back + IOUtils.copy(is, os); + response.setStatus(HttpServletResponse.SC_OK); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + } catch (IOException e) { + String message = "Failed to open policy id " + policyId; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_NOT_FOUND, message); + } + } catch (PAPException e) { + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(500, e.getMessage()); + im.endTransaction(); + return; + } + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended"); + im.endTransaction(); + } + + /** + * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response) + */ + protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + storedRequestId = loggingContext.getRequestID(); + loggingContext.transactionStarted(); + loggingContext.setServiceName("PAP.put"); + if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doPut) so we generated one"); + } else { + PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doPut)"); + } + try { + im.startTransaction(); + } catch (AdministrativeStateException ae){ + String message = "PUT interface called for PAP " + papResourceName + " but it has an Administrative" + + " state of " + im.getStateManager().getAdminState() + + "\n Exception Message: " + ae.getMessage(); + LOGGER.info(message +ae); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + }catch (StandbyStatusException se) { + String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status" + + " of " + im.getStateManager().getStandbyStatus() + + "\n Exception Message: " + se.getMessage(); + LOGGER.info(message +se); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + } + XACMLRest.dumpRequest(request); + //need to check if request is from the API or Admin console + String apiflag = request.getParameter("apiflag"); + //This would occur if a PolicyDBDao notification was received + String policyDBDaoRequestUrl = request.getParameter("policydbdaourl"); + if(policyDBDaoRequestUrl != null){ + String policyDBDaoRequestEntityId = request.getParameter("entityid"); + //String policyDBDaoRequestEntityType = request.getParameter("entitytype"); + String policyDBDaoRequestEntityType = request.getParameter("entitytype"); + String policyDBDaoRequestExtraData = request.getParameter("extradata"); + if(policyDBDaoRequestEntityId == null || policyDBDaoRequestEntityType == null){ + response.sendError(400, "entityid or entitytype not supplied"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + policyDBDao.handleIncomingHttpNotification(policyDBDaoRequestUrl,policyDBDaoRequestEntityId,policyDBDaoRequestEntityType,policyDBDaoRequestExtraData,this); + response.setStatus(200); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + /* + * Request for ImportService + */ + String importService = request.getParameter("importService"); + if (importService != null) { + if(authorizeRequest(request)){ + APIRequestHandler apiRequestHandler = new APIRequestHandler(); + apiRequestHandler.doPut(request, response, importService); + im.endTransaction(); + return; + } else { + String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + message ); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_FORBIDDEN, message); + return; + } + } + //This would occur if we received a notification of a policy rename from AC + String oldPolicyName = request.getParameter("oldPolicyName"); + String newPolicyName = request.getParameter("newPolicyName"); + if(oldPolicyName != null && newPolicyName != null){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPapServlet.doPut() - before decoding" + + "\npolicyToCreateUpdate = " + " "); + } + //decode it + try{ + oldPolicyName = URLDecoder.decode(oldPolicyName, "UTF-8"); + newPolicyName = URLDecoder.decode(newPolicyName, "UTF-8"); + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPapServlet.doPut() - after decoding" + + "\npolicyToCreateUpdate = " + " "); + } + } catch(UnsupportedEncodingException e){ + PolicyLogger.error("\nXACMLPapServlet.doPut() - Unsupported URL encoding of policyToCreateUpdate (UTF-8)" + + "\npolicyToCreateUpdate = " + " "); + response.sendError(500,"policyToCreateUpdate encoding not supported" + + "\nfailure with the following exception: " + e); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See error.log"); + im.endTransaction(); + return; + } + //send it to PolicyDBDao + PolicyDBDaoTransaction renameTransaction = policyDBDao.getNewTransaction(); + try{ + renameTransaction.renamePolicy(oldPolicyName,newPolicyName, "XACMLPapServlet.doPut"); + }catch(Exception e){ + renameTransaction.rollbackTransaction(); + response.sendError(500,"createUpdateTransaction.createPolicy(policyToCreateUpdate, XACMLPapServlet.doPut) " + + "\nfailure with the following exception: " + e); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See error.log"); + im.endTransaction(); + return; + } + renameTransaction.commitTransaction(); + response.setStatus(HttpServletResponse.SC_OK); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + // + // See if this is Admin Console registering itself with us + // + String acURLString = request.getParameter("adminConsoleURL"); + if (acURLString != null) { + loggingContext.setServiceName("AC:PAP.register"); + // remember this Admin Console for future updates + if ( ! adminConsoleURLStringList.contains(acURLString)) { + adminConsoleURLStringList.add(acURLString); + } + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Admin Console registering with URL: " + acURLString); + } + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + /* + * This is to update the PDP Group with the policy/policies being pushed + * Part of a 2 step process to push policies to the PDP that can now be done + * From both the Admin Console and the PolicyEngine API + */ + String groupId = request.getParameter("groupId"); + if (groupId != null) { + if(apiflag!=null){ + if(!authorizeRequest(request)){ + String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_FORBIDDEN, message); + return; + } + if(apiflag.equalsIgnoreCase("addPolicyToGroup")){ + updateGroupsFromAPI(request, response, groupId, loggingContext); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + } + // this is from the Admin Console, so handle separately + doACPut(request, response, groupId, loggingContext); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + // + // Request is for policy validation and creation + // + if (apiflag != null && apiflag.equalsIgnoreCase("admin")){ + // this request is from the Admin Console + SavePolicyHandler savePolicyHandler = SavePolicyHandler.getInstance(); + savePolicyHandler.doPolicyAPIPut(request, response); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } else if (apiflag != null && apiflag.equalsIgnoreCase("api")) { + // this request is from the Policy Creation API + if(authorizeRequest(request)){ + APIRequestHandler apiRequestHandler = new APIRequestHandler(); + apiRequestHandler.doPut(request, response, request.getHeader("ClientScope")); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } else { + String message = "PEP not Authorized for making this Request!!"; + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_FORBIDDEN, message); + im.endTransaction(); + return; + } + } + // We do not expect anything from anywhere else. + // This method is here in case we ever need to support other operations. + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See error.log"); + im.endTransaction(); + } + + /** + * @see HttpServlet#doDelete(HttpServletRequest request, HttpServletResponse response) + */ + protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + loggingContext.transactionStarted(); + loggingContext.setServiceName("PAP.delete"); + if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (doDelete) so we generated one"); + } else { + PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (doDelete)"); + } + try { + im.startTransaction(); + } catch (AdministrativeStateException ae){ + String message = "DELETE interface called for PAP " + papResourceName + " but it has an Administrative" + + " state of " + im.getStateManager().getAdminState() + + "\n Exception Message: " + ae.getMessage(); + LOGGER.info(message); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + }catch (StandbyStatusException se) { + String message = "PUT interface called for PAP " + papResourceName + " but it has a Standby Status" + + " of " + im.getStateManager().getStandbyStatus() + + "\n Exception Message: " + se.getMessage(); + LOGGER.info(message); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + } + XACMLRest.dumpRequest(request); + String groupId = request.getParameter("groupId"); + String apiflag = request.getParameter("apiflag"); + if (groupId != null) { + // Is this from the Admin Console or API? + if(apiflag!=null) { + if(!authorizeRequest(request)){ + String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_FORBIDDEN, message); + return; + } + APIRequestHandler apiRequestHandler = new APIRequestHandler(); + try { + apiRequestHandler.doDelete(request, response, loggingContext, apiflag); + } catch (Exception e) { + LOGGER.error("Exception Occured"+e); + } + if(apiRequestHandler.getNewGroup()!=null){ + groupChanged(apiRequestHandler.getNewGroup()); + } + return; + } + // this is from the Admin Console, so handle separately + doACDelete(request, response, groupId, loggingContext); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended Successfully"); + im.endTransaction(); + return; + } + //Catch anything that fell through + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId"); + im.endTransaction(); + } + + private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) { + String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES); + String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); + if (localRootPolicies == null || localReferencedPolicies == null) { + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies="+localRootPolicies+" ReferencedPolicies="+localReferencedPolicies); + return false; + } + // Compare the policies and pipconfig properties to the pdpProperties + try { + // the policy properties includes only xacml.rootPolicies and + // xacml.referencedPolicies without any .url entries + Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false); + Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties); + if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) && + localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) && + pdpPipConfig.equals(pipconfig)) { + // The PDP is current + return true; + } + } catch (Exception e) { + // we get here if the PDP did not include either xacml.rootPolicies or xacml.pip.engines, + // or if there are policies that do not have a corresponding ".url" property. + // Either of these cases means that the PDP is not up-to-date, so just drop-through to return false. + PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error"); + } + return false; + } + + private void populatePolicyURL(StringBuffer urlPath, Properties policies) { + String lists[] = new String[2]; + lists[0] = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES); + lists[1] = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); + for (String list : lists) { + if (list != null && list.isEmpty() == false) { + for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) { + String url = urlPath + "?id=" + id; + LOGGER.info("Policy URL for " + id + ": " + url); + policies.setProperty(id + ".url", url); + } + } + } + } + + protected String getPDPID(HttpServletRequest request) { + String pdpURL = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID); + if (pdpURL == null || pdpURL.isEmpty()) { + // Should send back its port for identification + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header"); + pdpURL = ""; + } + return pdpURL; + } + + protected String getPDPJMX(HttpServletRequest request) { + String pdpJMMX = request.getHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT); + if (pdpJMMX == null || pdpJMMX.isEmpty()) { + // Should send back its port for identification + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP did not send custom header for JMX Port so the value of 0 is assigned"); + return null; + } + return pdpJMMX; + } + + /** + * Requests from the PolicyEngine API to update the PDP Group with pushed policy + * + * @param request + * @param response + * @param groupId + * @param loggingContext + * @throws ServletException + * @throws IOException + */ + public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws IOException { + PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction(); + try { + // for PUT operations the group may or may not need to exist before the operation can be done + StdPDPGroup group = (StdPDPGroup) papEngine.getGroup(groupId); + // get the request input stream content into a String + String json = null; + java.util.Scanner scanner = new java.util.Scanner(request.getInputStream()); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + PolicyLogger.info("JSON request from PolicyEngine API: " + json); + // convert Object sent as JSON into local object + StdPDPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPDPPolicy.class); + Set policies = new HashSet<>(); + if(policy!=null){ + policies.add(policy); + } + //Get the current policies from the Group and Add the new one + Set currentPoliciesInGroup = new HashSet<>(); + currentPoliciesInGroup = group.getPolicies(); + //If the selected policy is in the group we must remove it because the name is default + Iterator policyIterator = policies.iterator(); + LOGGER.debug("policyIterator....." + policies); + while (policyIterator.hasNext()) { + PDPPolicy selPolicy = policyIterator.next(); + for (PDPPolicy existingPolicy : currentPoliciesInGroup) { + if (existingPolicy.getId().equals(selPolicy.getId())) { + group.removePolicyFromGroup(existingPolicy); + LOGGER.debug("Removing policy: " + existingPolicy); + break; + } + } + } + //Update the PDP Group after removing old version of policy + Set updatedPoliciesInGroup = new HashSet<>(); + updatedPoliciesInGroup = group.getPolicies(); + //need to remove the policy with default name from group + for (PDPPolicy updatedPolicy : currentPoliciesInGroup) { + if (updatedPolicy.getName().equalsIgnoreCase("default")) { + group.removePolicyFromGroup(updatedPolicy); + break; + } + } + if(updatedPoliciesInGroup!=null){ + policies.addAll(updatedPoliciesInGroup); + } + group.setPolicies(policies); + // Assume that this is an update of an existing PDP Group + loggingContext.setServiceName("PolicyEngineAPI:PAP.updateGroup"); + try{ + acPutTransaction.updateGroup(group, "XACMLPapServlet.doACPut"); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: " + +"group="+group.getId()); + throw new PAPException(e.getMessage()); + } + papEngine.updateGroup(group); + String policyId = "empty"; + if(policy!=null){ + policyId = policy.getId(); + } + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + response.addHeader("operation", "push"); + response.addHeader("policyId", policyId); + response.addHeader("groupId", groupId); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Group '" + group.getId() + "' updated"); + } + acPutTransaction.commitTransaction(); + notifyAC(); + // Group changed, which might include changing the policies + groupChanged(group); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + + if (policy != null && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) { + PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); + if (pushPolicyHandler.preSafetyCheck(policy, CONFIG_HOME)) { + LOGGER.debug("Precheck Successful."); + } + } + + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } catch (PAPException e) { + acPutTransaction.rollbackTransaction(); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP."; + response.sendError(500, e.getMessage()); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader("error","addGroupError"); + response.addHeader("message", message); + return; + } + } + + /** + * Requests from the Admin Console for operations not on single specific objects + * + * @param request + * @param response + * @param groupId + * @param loggingContext + * @throws ServletException + * @throws IOException + */ + private void doACPost(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException { + PolicyDBDaoTransaction doACPostTransaction = null; + try { + String groupName = request.getParameter("groupName"); + String groupDescription = request.getParameter("groupDescription"); + String apiflag = request.getParameter("apiflag"); + if (groupName != null && groupDescription != null) { + // Args: group= groupName= groupDescription= <= create a new group + loggingContext.setServiceName("AC:PAP.createGroup"); + String unescapedName = URLDecoder.decode(groupName, "UTF-8"); + String unescapedDescription = URLDecoder.decode(groupDescription, "UTF-8"); + PolicyDBDaoTransaction newGroupTransaction = policyDBDao.getNewTransaction(); + try { + newGroupTransaction.createGroup(PolicyDBDao.createNewPDPGroupId(unescapedName), unescapedName, unescapedDescription,"XACMLPapServlet.doACPost"); + papEngine.newGroup(unescapedName, unescapedDescription); + newGroupTransaction.commitTransaction(); + } catch (Exception e) { + newGroupTransaction.rollbackTransaction(); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to create new group"); + loggingContext.transactionEnded(); + + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(500, "Unable to create new group '" + groupId + "'"); + return; + } + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("New Group '" + groupId + "' created"); + } + // tell the Admin Consoles there is a change + notifyAC(); + // new group by definition has no PDPs, so no need to notify them of changes + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } + // for all remaining POST operations the group must exist before the operation can be done + OnapPDPGroup group = papEngine.getGroup(groupId); + if (group == null) { + String message = "Unknown groupId '" + groupId + "'"; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + if (apiflag!=null){ + response.addHeader("error", "unknownGroupId"); + response.addHeader("operation", "push"); + response.addHeader("message", message); + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + } else { + response.sendError(HttpServletResponse.SC_NOT_FOUND, message); + } + return; + } + // determine the operation needed based on the parameters in the request + if (request.getParameter("policyId") != null) { + // Args: group= policy= <= copy file + // copy a policy from the request contents into a file in the group's directory on this machine + if(apiflag!=null){ + loggingContext.setServiceName("PolicyEngineAPI:PAP.postPolicy"); + } else { + loggingContext.setServiceName("AC:PAP.postPolicy"); + } + String policyId = request.getParameter("policyId"); + PolicyDBDaoTransaction addPolicyToGroupTransaction = policyDBDao.getNewTransaction(); + try { + InputStream is = null; + File temp= null; + if (apiflag != null){ + // get the request content into a String if the request is from API + 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(request.getInputStream()); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + LOGGER.info("JSON request from API: " + json); + // convert Object sent as JSON into local object + ObjectMapper mapper = new ObjectMapper(); + Object objectFromJSON = mapper.readValue(json, StdPAPPolicy.class); + StdPAPPolicy policy = (StdPAPPolicy) objectFromJSON; + temp = new File(policy.getLocation()); + is = new FileInputStream(temp); + } else { + is = request.getInputStream(); + } + addPolicyToGroupTransaction.addPolicyToGroup(group.getId(), policyId,"XACMLPapServlet.doACPost"); + if (apiflag != null){ + ((StdPDPGroup) group).copyPolicyToFile(policyId,"API", is); + } else { + String name = null; + if (policyId.endsWith(".xml")) { + name = policyId.replace(".xml", ""); + name = name.substring(0, name.lastIndexOf(".")); + } + ((StdPDPGroup) group).copyPolicyToFile(policyId, name, is); + } + if(is!=null && temp!=null){ + is.close(); + temp.delete(); + } + addPolicyToGroupTransaction.commitTransaction(); + } catch (Exception e) { + addPolicyToGroupTransaction.rollbackTransaction(); + String message = "Policy '" + policyId + "' not copied to group '" + groupId +"': " + e; + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + if (apiflag!=null){ + response.addHeader("error", "policyCopyError"); + response.addHeader("message", message); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } else { + response.sendError(500, message); + } + return; + } + // policy file copied ok and the Group was updated on the PDP + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + response.addHeader("operation", "push"); + response.addHeader("policyId", policyId); + response.addHeader("groupId", groupId); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("policy '" + policyId + "' copied to directory for group '" + groupId + "'"); + } + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } else if (request.getParameter("default") != null) { + // Args: group= default=true <= make default + // change the current default group to be the one identified in the request. + loggingContext.setServiceName("AC:PAP.setDefaultGroup"); + // This is a POST operation rather than a PUT "update group" because of the side-effect that the current default group is also changed. + // It should never be the case that multiple groups are currently marked as the default, but protect against that anyway. + PolicyDBDaoTransaction setDefaultGroupTransaction = policyDBDao.getNewTransaction(); + try { + setDefaultGroupTransaction.changeDefaultGroup(group, "XACMLPapServlet.doACPost"); + papEngine.SetDefaultGroup(group); + setDefaultGroupTransaction.commitTransaction(); + } catch (Exception e) { + setDefaultGroupTransaction.rollbackTransaction(); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Unable to set group"); + loggingContext.transactionEnded(); + + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(500, "Unable to set group '" + groupId + "' to default"); + return; + } + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Group '" + groupId + "' set to be default"); + } + // Notify the Admin Consoles that something changed + // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that + //TODO - Future: FIGURE OUT WHAT LEVEL TO NOTIFY: 2 groups or entire set - currently notify AC to update whole configuration of all groups + notifyAC(); + // This does not affect any PDPs in the existing groups, so no need to notify them of this change + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } else if (request.getParameter("pdpId") != null) { + doACPostTransaction = policyDBDao.getNewTransaction(); + // Args: group= pdpId= <= move PDP to group + loggingContext.setServiceName("AC:PAP.movePDP"); + String pdpId = request.getParameter("pdpId"); + OnapPDP pdp = papEngine.getPDP(pdpId); + OnapPDPGroup originalGroup = papEngine.getPDPGroup((OnapPDP) pdp); + try{ + doACPostTransaction.movePdp(pdp, group, "XACMLPapServlet.doACPost"); + }catch(Exception e){ + doACPostTransaction.rollbackTransaction(); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", + " Error while moving pdp in the database: " + +"pdp="+pdp.getId()+",to group="+group.getId()); + throw new PAPException(e.getMessage()); + } + papEngine.movePDP((OnapPDP) pdp, group); + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("PDP '" + pdp.getId() +"' moved to group '" + group.getId() + "' set to be default"); + } + // update the status of both the original group and the new one + ((StdPDPGroup)originalGroup).resetStatus(); + ((StdPDPGroup)group).resetStatus(); + // Notify the Admin Consoles that something changed + // For now the AC cannot handle anything more detailed than the whole set of PDPGroups, so just notify on that + notifyAC(); + // Need to notify the PDP that it's config may have changed + pdpChanged(pdp); + doACPostTransaction.commitTransaction(); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } + } catch (PAPException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC POST exception"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(500, e.getMessage()); + return; + } + } + + /** + * Requests from the Admin Console to GET info about the Groups and PDPs + * + * @param request + * @param response + * @param groupId + * @param loggingContext + * @throws ServletException + * @throws IOException + */ + private void doACGet(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException { + try { + String parameterDefault = request.getParameter("default"); + String pdpId = request.getParameter("pdpId"); + String pdpGroup = request.getParameter("getPDPGroup"); + if ("".equals(groupId)) { + // request IS from AC but does not identify a group by name + if (parameterDefault != null) { + // Request is for the Default group (whatever its id) + loggingContext.setServiceName("AC:PAP.getDefaultGroup"); + OnapPDPGroup group = papEngine.getDefaultGroup(); + // convert response object to JSON and include in the response + ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(response.getOutputStream(), group); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("GET Default group req from '" + request.getRequestURL() + "'"); + } + response.setStatus(HttpServletResponse.SC_OK); + response.setHeader("content-type", "application/json"); + response.getOutputStream().close(); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } else if (pdpId != null) { + // Request is related to a PDP + if (pdpGroup == null) { + // Request is for the (unspecified) group containing a given PDP + loggingContext.setServiceName("AC:PAP.getPDP"); + OnapPDP pdp = papEngine.getPDP(pdpId); + // convert response object to JSON and include in the response + ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(response.getOutputStream(), pdp); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("GET pdp '" + pdpId + "' req from '" + request.getRequestURL() + "'"); + } + response.setStatus(HttpServletResponse.SC_OK); + response.setHeader("content-type", "application/json"); + response.getOutputStream().close(); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } else { + // Request is for the group containing a given PDP + loggingContext.setServiceName("AC:PAP.getGroupForPDP"); + OnapPDP pdp = papEngine.getPDP(pdpId); + OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp); + // convert response object to JSON and include in the response + ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(response.getOutputStream(), group); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("GET PDP '" + pdpId + "' Group req from '" + request.getRequestURL() + "'"); + } + response.setStatus(HttpServletResponse.SC_OK); + response.setHeader("content-type", "application/json"); + response.getOutputStream().close(); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } + } else { + // request is for top-level properties about all groups + loggingContext.setServiceName("AC:PAP.getAllGroups"); + Set groups = papEngine.getOnapPDPGroups(); + // convert response object to JSON and include in the response + ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(response.getOutputStream(), groups); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("GET All groups req"); + } + response.setStatus(HttpServletResponse.SC_OK); + response.setHeader("content-type", "application/json"); + response.getOutputStream().close(); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } + } + // for all other GET operations the group must exist before the operation can be done + OnapPDPGroup group = papEngine.getGroup(groupId); + if (group == null) { + String message = "Unknown groupId '" + groupId + "'"; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); + loggingContext.transactionEnded(); + + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_NOT_FOUND, message); + return; + } + // Figure out which request this is based on the parameters + String policyId = request.getParameter("policyId"); + if (policyId != null) { + // retrieve a policy + loggingContext.setServiceName("AC:PAP.getPolicy"); + // convert response object to JSON and include in the response + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " GET Policy not implemented"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "GET Policy not implemented"); + } else { + // No other parameters, so return the identified Group + loggingContext.setServiceName("AC:PAP.getGroup"); + // convert response object to JSON and include in the response + ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(response.getOutputStream(), group); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("GET group '" + group.getId() + "' req from '" + request.getRequestURL() + "'"); + } + response.setStatus(HttpServletResponse.SC_OK); + response.setHeader("content-type", "application/json"); + response.getOutputStream().close(); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } + // Currently there are no other GET calls from the AC. + // The AC uses the "GET All Groups" operation to fill its local cache and uses that cache for all other GETs without calling the PAP. + // Other GETs that could be called: + // Specific Group (groupId=) + // A Policy (groupId= policyId=) + // A PDP (groupId= pdpId=) + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " UNIMPLEMENTED "); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + } catch (PAPException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC Get exception"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(500, e.getMessage()); + return; + } + } + + /** + * Requests from the Admin Console to create new items or update existing ones + * + * @param request + * @param response + * @param groupId + * @param loggingContext + * @throws ServletException + * @throws IOException + */ + private void doACPut(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException { + PolicyDBDaoTransaction acPutTransaction = policyDBDao.getNewTransaction(); + try { + // for PUT operations the group may or may not need to exist before the operation can be done + OnapPDPGroup group = papEngine.getGroup(groupId); + // determine the operation needed based on the parameters in the request + // for remaining operations the group must exist before the operation can be done + if (group == null) { + String message = "Unknown groupId '" + groupId + "'"; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_NOT_FOUND, message); + return; + } + if (request.getParameter("policy") != null) { + // group= policy= contents=policy file <= Create new policy file in group dir, or replace it if it already exists (do not touch properties) + loggingContext.setServiceName("AC:PAP.putPolicy"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PARTIALLY IMPLEMENTED!!! ACTUAL CHANGES SHOULD BE MADE BY PAP SERVLET!!! "); + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } else if (request.getParameter("pdpId") != null) { + // ARGS: group= pdpId= <= create a new PDP or Update an Existing one + String pdpId = request.getParameter("pdpId"); + if (papEngine.getPDP(pdpId) == null) { + loggingContext.setServiceName("AC:PAP.createPDP"); + } else { + loggingContext.setServiceName("AC:PAP.updatePDP"); + } + // get the request 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(request.getInputStream()); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + LOGGER.info("JSON request from AC: " + json); + // convert Object sent as JSON into local object + ObjectMapper mapper = new ObjectMapper(); + Object objectFromJSON = mapper.readValue(json, StdPDP.class); + if (pdpId == null || + objectFromJSON == null || + ! (objectFromJSON instanceof StdPDP) || + ((StdPDP)objectFromJSON).getId() == null || + ! ((StdPDP)objectFromJSON).getId().equals(pdpId)) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " PDP new/update had bad input. pdpId=" + pdpId + " objectFromJSON="+objectFromJSON); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(500, "Bad input, pdpid="+pdpId+" object="+objectFromJSON); + } + StdPDP pdp = (StdPDP) objectFromJSON; + if(pdp != null){ + if (papEngine.getPDP(pdpId) == null) { + // this is a request to create a new PDP object + try{ + acPutTransaction.addPdpToGroup(pdp.getId(), group.getId(), pdp.getName(), + pdp.getDescription(), pdp.getJmxPort(),"XACMLPapServlet.doACPut"); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while adding pdp to group in the database: " + +"pdp="+ (pdp.getId()) +",to group="+group.getId()); + throw new PAPException(e.getMessage()); + } + papEngine.newPDP(pdp.getId(), group, pdp.getName(), pdp.getDescription(), pdp.getJmxPort()); + } else { + try{ + acPutTransaction.updatePdp(pdp, "XACMLPapServlet.doACPut"); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating pdp in the database: " + +"pdp="+ pdp.getId()); + throw new PAPException(e.getMessage()); + } + // this is a request to update the pdp + papEngine.updatePDP(pdp); + } + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("PDP '" + pdpId + "' created/updated"); + } + // adjust the group's state including the new PDP + ((StdPDPGroup)group).resetStatus(); + // tell the Admin Consoles there is a change + notifyAC(); + // this might affect the PDP, so notify it of the change + pdpChanged(pdp); + acPutTransaction.commitTransaction(); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + }else{ + try{ + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "XACMLPapServlet", " Error while adding pdp to group in the database: " + +"pdp=null" + ",to group="+group.getId()); + throw new PAPException("PDP is null"); + } catch(Exception e){ + throw new PAPException("PDP is null" + e.getMessage() +e); + } + } + } else if (request.getParameter("pipId") != null) { + // group= pipId= contents=pip properties <= add a PIP to pip config, or replace it if it already exists (lenient operation) + loggingContext.setServiceName("AC:PAP.putPIP"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + return; + } else { + // Assume that this is an update of an existing PDP Group + // ARGS: group= <= Update an Existing Group + loggingContext.setServiceName("AC:PAP.updateGroup"); + // get the request 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(request.getInputStream()); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + LOGGER.info("JSON request from AC: " + json); + // convert Object sent as JSON into local object + ObjectMapper mapper = new ObjectMapper(); + Object objectFromJSON = mapper.readValue(json, StdPDPGroup.class); + if (objectFromJSON == null || ! (objectFromJSON instanceof StdPDPGroup) || + ! ((StdPDPGroup)objectFromJSON).getId().equals(group.getId())) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + group.getId() + " objectFromJSON="+objectFromJSON); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(500, "Bad input, id="+group.getId() +" object="+objectFromJSON); + } + // The Path on the PAP side is not carried on the RESTful interface with the AC + // (because it is local to the PAP) + // so we need to fill that in before submitting the group for update + if(objectFromJSON != null){ + ((StdPDPGroup)objectFromJSON).setDirectory(((StdPDPGroup)group).getDirectory()); + } + try{ + acPutTransaction.updateGroup((StdPDPGroup)objectFromJSON, "XACMLPapServlet.doACPut"); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database: " + +"group="+group.getId()); + throw new PAPException(e.getMessage()); + } + + PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); + OnapPDPGroup updatedGroup = (StdPDPGroup)objectFromJSON; + if (pushPolicyHandler.preSafetyCheck(updatedGroup, CONFIG_HOME)) { + LOGGER.debug("Precheck Successful."); + } + + papEngine.updateGroup((StdPDPGroup)objectFromJSON); + + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Group '" + group.getId() + "' updated"); + } + acPutTransaction.commitTransaction(); + // tell the Admin Consoles there is a change + notifyAC(); + // Group changed, which might include changing the policies + groupChanged(group); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } + } catch (PAPException e) { + acPutTransaction.rollbackTransaction(); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC PUT exception"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(500, e.getMessage()); + return; + } + } + + /** + * Requests from the Admin Console to delete/remove items + * + * @param request + * @param response + * @param groupId + * @param loggingContext + * @throws ServletException + * @throws IOException + */ + private void doACDelete(HttpServletRequest request, HttpServletResponse response, String groupId, ONAPLoggingContext loggingContext) throws ServletException, IOException { + //This code is to allow deletes to propagate to the database since delete is not implemented + String isDeleteNotify = request.getParameter("isDeleteNotify"); + if(isDeleteNotify != null){ + String policyToDelete = request.getParameter("policyToDelete"); + try{ + policyToDelete = URLDecoder.decode(policyToDelete,"UTF-8"); + } catch(UnsupportedEncodingException e){ + PolicyLogger.error("Unsupported URL encoding of policyToDelete (UTF-8"); + response.sendError(500,"policyToDelete encoding not supported"); + return; + } + PolicyDBDaoTransaction deleteTransaction = policyDBDao.getNewTransaction(); + try{ + deleteTransaction.deletePolicy(policyToDelete); + } catch(Exception e){ + deleteTransaction.rollbackTransaction(); + response.sendError(500,"deleteTransaction.deleteTransaction(policyToDelete) " + + "\nfailure with the following exception: " + e); + return; + } + deleteTransaction.commitTransaction(); + response.setStatus(HttpServletResponse.SC_OK); + return; + } + PolicyDBDaoTransaction removePdpOrGroupTransaction = policyDBDao.getNewTransaction(); + try { + // for all DELETE operations the group must exist before the operation can be done + loggingContext.setServiceName("AC:PAP.delete"); + OnapPDPGroup group = papEngine.getGroup(groupId); + if (group == null) { + String message = "Unknown groupId '" + groupId + "'"; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_NOT_FOUND, "Unknown groupId '" + groupId +"'"); + return; + } + // determine the operation needed based on the parameters in the request + if (request.getParameter("policy") != null) { + // group= policy= [delete=] <= delete policy file from group + loggingContext.setServiceName("AC:PAP.deletePolicy"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + return; + } else if (request.getParameter("pdpId") != null) { + // ARGS: group= pdpId= <= delete PDP + String pdpId = request.getParameter("pdpId"); + OnapPDP pdp = papEngine.getPDP(pdpId); + try{ + removePdpOrGroupTransaction.removePdpFromGroup(pdp.getId(),"XACMLPapServlet.doACDelete"); + } catch(Exception e){ + throw new PAPException(); + } + papEngine.removePDP((OnapPDP) pdp); + // adjust the status of the group, which may have changed when we removed this PDP + ((StdPDPGroup)group).resetStatus(); + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + notifyAC(); + // update the PDP and tell it that it has NO Policies (which prevents it from serving PEP Requests) + pdpChanged(pdp); + removePdpOrGroupTransaction.commitTransaction(); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } else if (request.getParameter("pipId") != null) { + // group= pipId= <= delete PIP config for given engine + loggingContext.setServiceName("AC:PAP.deletePIPConfig"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " UNIMPLEMENTED"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "UNIMPLEMENTED"); + return; + } else { + // ARGS: group= movePDPsToGroupId= <= delete a group and move all its PDPs to the given group + String moveToGroupId = request.getParameter("movePDPsToGroupId"); + OnapPDPGroup moveToGroup = null; + if (moveToGroupId != null) { + moveToGroup = papEngine.getGroup(moveToGroupId); + } + // get list of PDPs in the group being deleted so we can notify them that they got changed + Set movedPDPs = new HashSet<>(); + movedPDPs.addAll(group.getOnapPdps()); + // do the move/remove + try{ + removePdpOrGroupTransaction.deleteGroup(group, moveToGroup,"XACMLPapServlet.doACDelete"); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " Failed to delete PDP Group. Exception"); + throw new PAPException(e.getMessage()); + } + papEngine.removeGroup(group, moveToGroup); + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + notifyAC(); + // notify any PDPs in the removed set that their config may have changed + for (OnapPDP pdp : movedPDPs) { + pdpChanged(pdp); + } + removePdpOrGroupTransaction.commitTransaction(); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Transaction Ended Successfully"); + return; + } + } catch (PAPException e) { + removePdpOrGroupTransaction.rollbackTransaction(); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " AC DELETE exception"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(500, e.getMessage()); + return; + } + } + + /** + * Heartbeat thread - periodically check on PDPs' status + * + * Heartbeat with all known PDPs. + * + * Implementation note: + * + * The PDPs are contacted Sequentially, not in Parallel. + * + * If we did this in parallel using multiple threads we would simultaneously use + * - 1 thread and + * - 1 connection + * for EACH PDP. + * This could become a resource problem since we already use multiple threads and connections for updating the PDPs + * when user changes occur. + * Using separate threads can also make it tricky dealing with timeouts on PDPs that are non-responsive. + * + * The Sequential operation does a heartbeat request to each PDP one at a time. + * This has the flaw that any PDPs that do not respond will hold up the entire heartbeat sequence until they timeout. + * If there are a lot of non-responsive PDPs and the timeout is large-ish (the default is 20 seconds) + * it could take a long time to cycle through all of the PDPs. + * That means that this may not notice a PDP being down in a predictable time. + */ + private class Heartbeat implements Runnable { + private PAPPolicyEngine papEngine; + private Set pdps = new HashSet<>(); + private int heartbeatInterval; + private int heartbeatTimeout; + + public volatile boolean isRunning = false; + + public synchronized boolean isRunning() { + return this.isRunning; + } + + public synchronized void terminate() { + this.isRunning = false; + } + + public Heartbeat(PAPPolicyEngine papEngine2) { + papEngine = papEngine2; + this.heartbeatInterval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_INTERVAL, "10000")); + this.heartbeatTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_HEARTBEAT_TIMEOUT, "10000")); + } + + @Override + public void run() { + // Set ourselves as running + synchronized(this) { + this.isRunning = true; + } + HashMap idToURLMap = new HashMap<>(); + try { + while (this.isRunning()) { + // Wait the given time + Thread.sleep(heartbeatInterval); + // get the list of PDPs (may have changed since last time) + pdps.clear(); + synchronized(papEngine) { + try { + for (OnapPDPGroup g : papEngine.getOnapPDPGroups()) { + for (OnapPDP p : g.getOnapPdps()) { + pdps.add(p); + } + } + } catch (PAPException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat unable to read PDPs from PAPEngine"); + } + } + // Check for shutdown + if (this.isRunning() == false) { + LOGGER.info("isRunning is false, getting out of loop."); + break; + } + // try to get the summary status from each PDP + boolean changeSeen = false; + for (OnapPDP pdp : pdps) { + // Check for shutdown + if (this.isRunning() == false) { + LOGGER.info("isRunning is false, getting out of loop."); + break; + } + // the id of the PDP is its url (though we add a query parameter) + URL pdpURL = idToURLMap.get(pdp.getId()); + if (pdpURL == null) { + // haven't seen this PDP before + String fullURLString = null; + try { + // Check PDP ID + if(CheckPDP.validateID(pdp.getId())){ + fullURLString = pdp.getId() + "?type=hb"; + pdpURL = new URL(fullURLString); + idToURLMap.put(pdp.getId(), pdpURL); + } + } catch (MalformedURLException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " PDP id '" + fullURLString + "' is not a valid URL"); + continue; + } + } + // Do a GET with type HeartBeat + String newStatus = ""; + HttpURLConnection connection = null; + try { + // Open up the connection + if(pdpURL != null){ + connection = (HttpURLConnection)pdpURL.openConnection(); + // Setup our method and headers + connection.setRequestMethod("GET"); + connection.setConnectTimeout(heartbeatTimeout); + // Authentication + String encoding = CheckPDP.getEncoding(pdp.getId()); + if(encoding !=null){ + connection.setRequestProperty("Authorization", "Basic " + encoding); + } + // Do the connect + connection.connect(); + if (connection.getResponseCode() == 204) { + newStatus = connection.getHeaderField(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Heartbeat '" + pdp.getId() + "' status='" + newStatus + "'"); + } + } else { + // anything else is an unexpected result + newStatus = PDPStatus.Status.UNKNOWN.toString(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat connect response code " + connection.getResponseCode() + ": " + pdp.getId()); + } + } + } catch (UnknownHostException e) { + newStatus = PDPStatus.Status.NO_SUCH_HOST.toString(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' NO_SUCH_HOST"); + } catch (SocketTimeoutException e) { + newStatus = PDPStatus.Status.CANNOT_CONNECT.toString(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' connection timeout"); + } catch (ConnectException e) { + newStatus = PDPStatus.Status.CANNOT_CONNECT.toString(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Heartbeat '" + pdp.getId() + "' cannot connect"); + } catch (Exception e) { + newStatus = PDPStatus.Status.UNKNOWN.toString(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", "Heartbeat '" + pdp.getId() + "' connect exception"); + } finally { + // cleanup the connection + if(connection != null) + connection.disconnect(); + } + if ( ! pdp.getStatus().getStatus().toString().equals(newStatus)) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("previous status='" + pdp.getStatus().getStatus()+"' new Status='" + newStatus + "'"); + } + try { + setPDPSummaryStatus(pdp, newStatus); + } catch (PAPException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", "Unable to set state for PDP '" + pdp.getId()); + } + changeSeen = true; + } + } + // Check for shutdown + if (this.isRunning() == false) { + LOGGER.info("isRunning is false, getting out of loop."); + break; + } + // if any of the PDPs changed state, tell the ACs to update + if (changeSeen) { + notifyAC(); + } + } + } catch (InterruptedException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " Heartbeat interrupted. Shutting down"); + this.terminate(); + } + } + } + + /* + * HELPER to change Group status when PDP status is changed + * (Must NOT be called from a method that is synchronized on the papEngine or it may deadlock) + */ + private void setPDPSummaryStatus(OnapPDP pdp, PDPStatus.Status newStatus) throws PAPException { + setPDPSummaryStatus(pdp, newStatus.toString()); + } + + private void setPDPSummaryStatus(OnapPDP pdp, String newStatus) throws PAPException { + synchronized(papEngine) { + StdPDPStatus status = new StdPDPStatus(); + status.setStatus(PDPStatus.Status.valueOf(newStatus)); + ((StdPDP)pdp).setStatus(status); + // now adjust the group + StdPDPGroup group = (StdPDPGroup)papEngine.getPDPGroup((OnapPDP) pdp); + // if the PDP was just deleted it may transiently exist but not be in a group + if (group != null) { + group.resetStatus(); + } + } + } + + /* + * Callback methods telling this servlet to notify PDPs of changes made by the PAP StdEngine + * in the PDP group directories + */ + @Override + public void changed() { + // all PDPs in all groups need to be updated/sync'd + Set groups; + try { + groups = papEngine.getOnapPDPGroups(); + } catch (PAPException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed"); + throw new RuntimeException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); + } + for (OnapPDPGroup group : groups) { + groupChanged(group); + } + } + + @Override + public void groupChanged(OnapPDPGroup group) { + // all PDPs within one group need to be updated/sync'd + for (OnapPDP pdp : group.getOnapPdps()) { + pdpChanged(pdp); + } + } + + @Override + public void pdpChanged(OnapPDP pdp) { + // kick off a thread to do an event notification for each PDP. + // This needs to be on a separate thread so that PDPs that do not respond (down, non-existent, etc) + // do not block the PSP response to the AC, which would freeze the GUI until all PDPs sequentially respond or time-out. + Thread t = new Thread(new UpdatePDPThread(pdp, storedRequestId)); + if(CheckPDP.validateID(pdp.getId())){ + t.start(); + } + } + + private class UpdatePDPThread implements Runnable { + private OnapPDP pdp; + private String requestId; + + public UpdatePDPThread(OnapPDP pdp, String storedRequestId) { + this.pdp = pdp; + requestId = storedRequestId; + } + + public void run() { + // send the current configuration to one PDP + HttpURLConnection connection = null; + // get a new logging context for the thread + ONAPLoggingContext loggingContext = new ONAPLoggingContext(baseLoggingContext); + try { + loggingContext.setServiceName("PAP:PDP.putConfig"); + // If a requestId was provided, use it, otherwise generate one; post to loggingContext to be used later when calling PDP + if ((requestId == null) || (requestId == "")) { + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + PolicyLogger.info("requestID not provided in call to XACMLPapSrvlet (UpdatePDPThread) so we generated one: " + loggingContext.getRequestID()); + } else { + loggingContext.setRequestID(requestId); + PolicyLogger.info("requestID was provided in call to XACMLPapSrvlet (UpdatePDPThread): " + loggingContext.getRequestID()); + } + loggingContext.transactionStarted(); + // the Id of the PDP is its URL + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("creating url for id '" + pdp.getId() + "'"); + } + //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other? + //TODO (need to change "cache=", implying getting some input saying which to change) + URL url = new URL(pdp.getId() + "?cache=all"); + // Open up the connection + connection = (HttpURLConnection)url.openConnection(); + // Setup our method and headers + connection.setRequestMethod("PUT"); + // Authentication + String encoding = CheckPDP.getEncoding(pdp.getId()); + if(encoding !=null){ + connection.setRequestProperty("Authorization", "Basic " + encoding); + } + connection.setRequestProperty("Content-Type", "text/x-java-properties"); + connection.setRequestProperty("X-ECOMP-RequestID", loggingContext.getRequestID()); + storedRequestId = null; + connection.setInstanceFollowRedirects(true); + connection.setDoOutput(true); + try (OutputStream os = connection.getOutputStream()) { + OnapPDPGroup group = papEngine.getPDPGroup((OnapPDP) pdp); + // if the PDP was just deleted, there is no group, but we want to send an update anyway + if (group == null) { + // create blank properties files + Properties policyProperties = new Properties(); + policyProperties.put(XACMLProperties.PROP_ROOTPOLICIES, ""); + policyProperties.put(XACMLProperties.PROP_REFERENCEDPOLICIES, ""); + policyProperties.store(os, ""); + Properties pipProps = new Properties(); + pipProps.setProperty(XACMLProperties.PROP_PIP_ENGINES, ""); + pipProps.store(os, ""); + } else { + // send properties from the current group + group.getPolicyProperties().store(os, ""); + Properties policyLocations = new Properties(); + for (PDPPolicy policy : group.getPolicies()) { + policyLocations.put(policy.getId() + ".url", XACMLPapServlet.papURL + "?id=" + policy.getId()); + } + policyLocations.store(os, ""); + group.getPipConfigProperties().store(os, ""); + } + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to send property file to " + pdp.getId()); + // Since this is a server-side error, it probably does not reflect a problem on the client, + // so do not change the PDP status. + return; + } + // Do the connect + connection.connect(); + if (connection.getResponseCode() == 204) { + LOGGER.info("Success. We are configured correctly."); + loggingContext.transactionEnded(); + auditLogger.info("Success. PDP is configured correctly."); + PolicyLogger.audit("Transaction Success. PDP is configured correctly."); + setPDPSummaryStatus(pdp, PDPStatus.Status.UP_TO_DATE); + } else if (connection.getResponseCode() == 200) { + LOGGER.info("Success. PDP needs to update its configuration."); + loggingContext.transactionEnded(); + auditLogger.info("Success. PDP needs to update its configuration."); + PolicyLogger.audit("Transaction Success. PDP is configured correctly."); + setPDPSummaryStatus(pdp, PDPStatus.Status.OUT_OF_SYNCH); + } else { + LOGGER.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + loggingContext.transactionEnded(); + auditLogger.warn("Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + PolicyLogger.audit("Transaction Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN); + } + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config with PDP '" + pdp.getId() + "'"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed: Unable to sync config with PDP '" + pdp.getId() + "': " + e); + try { + setPDPSummaryStatus(pdp, PDPStatus.Status.UNKNOWN); + } catch (PAPException e1) { + PolicyLogger.audit("Transaction Failed: Unable to set status of PDP " + pdp.getId() + " to UNKNOWN: " + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to set status of PDP '" + pdp.getId() + "' to UNKNOWN"); + } + } finally { + // cleanup the connection + if(connection != null){ + connection.disconnect(); + } + // tell the AC to update it's status info + notifyAC(); + } + } + } + + /* + * RESTful Interface from PAP to ACs notifying them of changes + */ + private void notifyAC() { + // kick off a thread to do one event notification for all registered ACs + // This needs to be on a separate thread so that ACs can make calls back to PAP to get the updated Group data + // as part of processing this message on their end. + Thread t = new Thread(new NotifyACThread()); + t.start(); + } + + private class NotifyACThread implements Runnable { + public void run() { + List disconnectedACs = new ArrayList<>(); + // There should be no Concurrent exception here because the list is a CopyOnWriteArrayList. + // The "for each" loop uses the collection's iterator under the covers, so it should be correct. + for (String acURL : adminConsoleURLStringList) { + HttpURLConnection connection = null; + try { + acURL += "?PAPNotification=true"; + //TODO - Currently we just tell AC that "Something changed" without being specific. Do we want to tell it which group/pdp changed? + //TODO - If so, put correct parameters into the Query string here + acURL += "&objectType=all" + "&action=update"; + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("creating url for id '" + acURL + "'"); + } + //TODO - currently always send both policies and pips. Do we care enough to add code to allow sending just one or the other? + //TODO (need to change "cache=", implying getting some input saying which to change) + URL url = new URL(acURL ); + // Open up the connection + connection = (HttpURLConnection)url.openConnection(); + // Setup our method and headers + connection.setRequestMethod("PUT"); + connection.setRequestProperty("Content-Type", "text/x-java-properties"); + // 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. + //TODO - is this needed for a PUT? seems better to leave in for now? + connection.setInstanceFollowRedirects(false); + // Do not include any data in the PUT because this is just a + // notification to the AC. + // The AC will use GETs back to the PAP to get what it needs + // to fill in the screens. + // Do the connect + connection.connect(); + if (connection.getResponseCode() == 204) { + LOGGER.info("Success. We updated correctly."); + } else { + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + } + + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Unable to sync config AC '" + acURL + "'"); + disconnectedACs.add(acURL); + } finally { + // cleanup the connection + if(connection != null) + connection.disconnect(); + } + } + // remove any ACs that are no longer connected + if (disconnectedACs.size() > 0) { + adminConsoleURLStringList.removeAll(disconnectedACs); + } + } + } + + private void testService(ONAPLoggingContext loggingContext, HttpServletResponse response) throws IOException{ + LOGGER.info("Test request received"); + try { + im.evaluateSanity(); + //If we make it this far, all is well + String message = "GET:/pap/test called and PAP " + papResourceName + " is OK"; + LOGGER.info(message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.setStatus(HttpServletResponse.SC_OK); + return; + }catch (ForwardProgressException fpe){ + //No forward progress is being made + String message = "GET:/pap/test called and PAP " + papResourceName + " is not making forward progress." + + " Exception Message: " + fpe.getMessage(); + LOGGER.info(message); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + }catch (AdministrativeStateException ase){ + //Administrative State is locked + String message = "GET:/pap/test called and PAP " + papResourceName + " Administrative State is LOCKED " + + " Exception Message: " + ase.getMessage(); + LOGGER.info(message); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + }catch (StandbyStatusException sse){ + //Administrative State is locked + String message = "GET:/pap/test called and PAP " + papResourceName + " Standby Status is NOT PROVIDING SERVICE " + + " Exception Message: " + sse.getMessage(); + LOGGER.info(message); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + }catch (Exception e) { + //A subsystem is not making progress, is locked, standby or is not responding + String eMsg = e.getMessage(); + if(eMsg == null){ + eMsg = "No Exception Message"; + } + String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure." + + " Exception Message: " + eMsg; + LOGGER.info(message); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + //Get the specific list of subsystems that failed + String ssFailureList = null; + for(String failedSS : papDependencyGroupsFlatArray){ + if(eMsg.contains(failedSS)){ + if(ssFailureList == null){ + ssFailureList = failedSS; + }else{ + ssFailureList = ssFailureList.concat(","+failedSS); + } + } + } + if(ssFailureList == null){ + ssFailureList = "UnknownSubSystem"; + } + response.addHeader("X-ONAP-SubsystemFailure", ssFailureList); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + return; + } + } + + /* + * Authorizing the PEP Requests. + */ + private boolean authorizeRequest(HttpServletRequest request) { + String clientCredentials = request.getHeader(ENVIRONMENT_HEADER); + // Check if the Client is Authorized. + if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){ + return true; + }else{ + return false; + } + } + + private static void loadWebapps() throws PAPException{ + if(ACTION_HOME == null || CONFIG_HOME == null){ + Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); + //Sanity Check + if (webappsPath == null) { + PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); + throw new PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); + } + Path webappsPathConfig = Paths.get(webappsPath.toString()+File.separator+"Config"); + Path webappsPathAction = Paths.get(webappsPath.toString()+File.separator+"Action"); + if (Files.notExists(webappsPathConfig)) { + try { + Files.createDirectories(webappsPathConfig); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Failed to create config directory: " + + webappsPathConfig.toAbsolutePath().toString()); + } + } + if (Files.notExists(webappsPathAction)) { + try { + Files.createDirectories(webappsPathAction); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: " + + webappsPathAction.toAbsolutePath().toString(), e); + } + } + ACTION_HOME = webappsPathAction.toString(); + CONFIG_HOME = webappsPathConfig.toString(); + } + } + + public static String getConfigHome(){ + try { + loadWebapps(); + } catch (PAPException e) { + return null; + } + return CONFIG_HOME; + } + + public static String getActionHome(){ + try { + loadWebapps(); + } catch (PAPException e) { + return null; + } + return ACTION_HOME; + } + + public static EntityManagerFactory getEmf() { + return emf; + } + + public IntegrityAudit getIa() { + return ia; + } + + public static String getPDPFile(){ + return XACMLPapServlet.pdpFile; + } + + public static String getPersistenceUnit(){ + return PERSISTENCE_UNIT; + } + + public static PAPPolicyEngine getPAPEngine(){ + return papEngine; + } + + public static PolicyDBDaoTransaction getDbDaoTransaction(){ + return policyDBDao.getNewTransaction(); + } + public static String getPapDbDriver() { + return papDbDriver; + } + + public static void setPapDbDriver(String papDbDriver) { + XACMLPapServlet.papDbDriver = papDbDriver; + } + + public static String getPapDbUrl() { + return papDbUrl; + } + + public static void setPapDbUrl(String papDbUrl) { + XACMLPapServlet.papDbUrl = papDbUrl; + } + + public static String getPapDbUser() { + return papDbUser; + } + + public static void setPapDbUser(String papDbUser) { + XACMLPapServlet.papDbUser = papDbUser; + } + + public static String getPapDbPassword() { + return papDbPassword; + } + + public static void setPapDbPassword(String papDbPassword) { + XACMLPapServlet.papDbPassword = papDbPassword; + } + + public static String getMsOnapName() { + return msOnapName; + } + + public static void setMsOnapName(String msOnapName) { + XACMLPapServlet.msOnapName = msOnapName; + } + + public static String getMsPolicyName() { + return msPolicyName; + } + + public static void setMsPolicyName(String msPolicyName) { + XACMLPapServlet.msPolicyName = msPolicyName; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/GridData.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/GridData.java new file mode 100644 index 000000000..1ed4bf3b5 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/GridData.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.adapters; + +import java.util.ArrayList; + +public class GridData { + private ArrayList attributes; + private ArrayList alAttributes; + private ArrayList transportProtocols; + private ArrayList appProtocols; + + public ArrayList getAttributes() { + return attributes; + } + + public void setAttributes(ArrayList attributes) { + this.attributes = attributes; + } + + public ArrayList getAlAttributes() { + return alAttributes; + } + + public void setAlAttributes(ArrayList alAttributes) { + this.alAttributes = alAttributes; + } + + public ArrayList getAppProtocols() { + return appProtocols; + } + + public void setAppProtocols(ArrayList appProtocols) { + this.appProtocols = appProtocols; + } + + public ArrayList getTransportProtocols() { + return transportProtocols; + } + + public void setTransportProtocols(ArrayList transportProtocols) { + this.transportProtocols = transportProtocols; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/package-info.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/package-info.java new file mode 100644 index 000000000..b51d08076 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/package-info.java @@ -0,0 +1,21 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.adapters; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java new file mode 100644 index 000000000..4aec72bed --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java @@ -0,0 +1,529 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.Query; + +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.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +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.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.pap.xacml.rest.util.JPAUtils; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.ActionPolicyDict; +import org.onap.policy.rest.jpa.Datatype; +import org.onap.policy.rest.jpa.FunctionDefinition; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +public class ActionPolicy extends Policy { + + /** + * ActionPolicy Fields + */ + private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicy.class); + + public static final String JSON_CONFIG = "JSON"; + + public static final String PDP_ACTION = "PDP"; + public static final String PEP_ACTION = "PEP"; + public static final String TYPE_ACTION = "REST"; + + public static final String GET_METHOD = "GET"; + public static final String PUT_METHOD = "PUT"; + public static final String POST_METHOD = "POST"; + + public static final String PERFORMER_ATTRIBUTEID = "performer"; + public static final String TYPE_ATTRIBUTEID = "type"; + public static final String METHOD_ATTRIBUTEID = "method"; + public static final String HEADERS_ATTRIBUTEID = "headers"; + public static final String URL_ATTRIBUTEID = "url"; + public static final String BODY_ATTRIBUTEID = "body"; + + private static boolean isAttribute = false; + + + List dynamicLabelRuleAlgorithms = new LinkedList<>(); + List dynamicFieldFunctionRuleAlgorithms = new LinkedList<>(); + List dynamicFieldOneRuleAlgorithms = new LinkedList<>(); + List dynamicFieldTwoRuleAlgorithms = new LinkedList<>(); + + protected Map dropDownMap = new HashMap<>(); + + + public ActionPolicy() { + super(); + } + + public ActionPolicy(PolicyRestAdapter policyAdapter){ + this.policyAdapter = policyAdapter; + } + + @Override + public Map savePolicies() throws Exception { + + Map successMap = new HashMap<>(); + if(isPolicyExists()){ + successMap.put("EXISTS", "This Policy already exist on the PAP"); + return successMap; + } + + if(!ActionPolicy.isAttribute) { + successMap.put("invalidAttribute", "Action Attrbute was not in the database."); + return successMap; + } + + if(!isPreparedToSave()){ + //Prep and configure the policy for saving + prepareToSave(); + } + + // Until here we prepared the data and here calling the method to create xml. + Path newPolicyPath = null; + newPolicyPath = Paths.get(policyAdapter.getNewFileName()); + successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject() ); + return successMap; + } + + //This is the method for preparing the policy for saving. We have broken it out + //separately because the fully configured policy is used for multiple things + @Override + public boolean prepareToSave() throws Exception{ + + if(isPreparedToSave()){ + //we have already done this + return true; + } + + int version = 0; + String policyID = policyAdapter.getPolicyID(); + version = policyAdapter.getHighestVersion(); + + // Create the Instance for pojo, PolicyType object is used in marshalling. + if (policyAdapter.getPolicyType().equals("Action")) { + PolicyType policyConfig = new PolicyType(); + + policyConfig.setVersion(Integer.toString(version)); + policyConfig.setPolicyId(policyID); + policyConfig.setTarget(new TargetType()); + policyAdapter.setData(policyConfig); + } + + policyName = policyAdapter.getNewFileName(); + + if (policyAdapter.getData() != null) { + // Action body is optional so checking value provided or not + String comboDictValue = policyAdapter.getActionAttribute(); + String actionBody = getActionPolicyDict(comboDictValue).getBody(); + if(!(actionBody==null || "".equals(actionBody))){ + saveActionBody(policyName, actionBody); + } else { + if(!isAttribute){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not find " + comboDictValue + " in the ActionPolicyDict table."); + return false; + } + } + + PolicyType actionPolicy = (PolicyType) policyAdapter.getData(); + actionPolicy.setDescription(policyAdapter.getPolicyDescription()); + actionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); + + AllOfType allOf = new AllOfType(); + + Map dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes(); + + // If there is any dynamic field attributes create the matches here + for (String keyField : dynamicFieldComponentAttributes.keySet()) { + String key = keyField; + String value = dynamicFieldComponentAttributes.get(key); + MatchType dynamicMatch = createDynamicMatch(key, value); + allOf.getMatch().add(dynamicMatch); + } + + AnyOfType anyOf = new AnyOfType(); + anyOf.getAllOf().add(allOf); + + TargetType target = new TargetType(); + target.getAnyOf().add(anyOf); + + // Adding the target to the policy element + actionPolicy.setTarget(target); + + RuleType rule = new RuleType(); + rule.setRuleId(policyAdapter.getRuleID()); + + rule.setEffect(EffectType.PERMIT); + rule.setTarget(new TargetType()); + + dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels(); + dynamicFieldFunctionRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo(); + dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1(); + dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2(); + //dropDownMap = policyAdapter.getDropDownMap(); + dropDownMap = createDropDownMap(); + + // Rule attributes are optional and dynamic so check and add them to condition. + if (dynamicLabelRuleAlgorithms != null && dynamicLabelRuleAlgorithms.size() > 0) { + boolean isCompound = false; + ConditionType condition = new ConditionType(); + int index = dynamicFieldOneRuleAlgorithms.size() - 1; + + for (String labelAttr : dynamicLabelRuleAlgorithms) { + // if the rule algorithm as a label means it is a compound + if (dynamicFieldOneRuleAlgorithms.get(index).toString().equals(labelAttr)) { + ApplyType actionApply = new ApplyType(); + + String selectedFunction = (String) dynamicFieldFunctionRuleAlgorithms.get(index).toString(); + String value1 = (String) dynamicFieldOneRuleAlgorithms.get(index).toString(); + String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString(); + actionApply.setFunctionId(dropDownMap.get(selectedFunction)); + actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1))); + actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2))); + condition.setExpression(new ObjectFactory().createApply(actionApply)); + isCompound = true; + } + } + // if rule algorithm not a compound + if (!isCompound) { + condition.setExpression(new ObjectFactory().createApply(getInnerActionApply(dynamicLabelRuleAlgorithms.get(index).toString()))); + } + rule.setCondition(condition); + } + // set the obligations to rule + rule.setObligationExpressions(getObligationExpressions()); + actionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); + policyAdapter.setPolicyData(actionPolicy); + } else { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); + } + + setPreparedToSave(true); + return true; + } + + // Saving the json Configurations file if exists at server location for action policy. + private void saveActionBody(String policyName, String actionBodyData) { + try { + if(policyName.endsWith(".xml")){ + policyName = policyName.replace(".xml", ""); + } + File file = new File(ACTION_HOME+ File.separator + policyName + ".json"); + FileWriter fw = new FileWriter(file.getAbsoluteFile()); + BufferedWriter bw = new BufferedWriter(fw); + bw.write(actionBodyData); + bw.close(); + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Action Body is succesfully saved at " + file.getAbsolutePath()); + } + } catch (IOException e) { + LOGGER.error("Exception Occured"+e); + } + } + + // Data required for obligation part is setting here. + private ObligationExpressionsType getObligationExpressions() { + ObligationExpressionsType obligations = new ObligationExpressionsType(); + + ObligationExpressionType obligation = new ObligationExpressionType(); + String comboDictValue = policyAdapter.getActionAttribute(); + obligation.setObligationId(comboDictValue); + obligation.setFulfillOn(EffectType.PERMIT); + + // Add Action Assignment: + AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); + assignment1.setAttributeId(PERFORMER_ATTRIBUTEID); + assignment1.setCategory(CATEGORY_RECIPIENT_SUBJECT); + + AttributeValueType actionNameAttributeValue = new AttributeValueType(); + actionNameAttributeValue.setDataType(STRING_DATATYPE); + actionNameAttributeValue.getContent().add(performer.get(policyAdapter.getActionPerformer())); + + assignment1.setExpression(new ObjectFactory().createAttributeValue(actionNameAttributeValue)); + obligation.getAttributeAssignmentExpression().add(assignment1); + + // Add Type Assignment: + AttributeAssignmentExpressionType assignmentType = new AttributeAssignmentExpressionType(); + assignmentType.setAttributeId(TYPE_ATTRIBUTEID); + assignmentType.setCategory(CATEGORY_RESOURCE); + + AttributeValueType typeAttributeValue = new AttributeValueType(); + typeAttributeValue.setDataType(STRING_DATATYPE); + String actionDictType = getActionPolicyDict(comboDictValue).getType(); + typeAttributeValue.getContent().add(actionDictType); + + assignmentType.setExpression(new ObjectFactory().createAttributeValue(typeAttributeValue)); + obligation.getAttributeAssignmentExpression().add(assignmentType); + + // Add Rest_URL Assignment: + AttributeAssignmentExpressionType assignmentURL = new AttributeAssignmentExpressionType(); + assignmentURL.setAttributeId(URL_ATTRIBUTEID); + assignmentURL.setCategory(CATEGORY_RESOURCE); + + AttributeValueType actionURLAttributeValue = new AttributeValueType(); + actionURLAttributeValue.setDataType(URI_DATATYPE); + String actionDictUrl = getActionPolicyDict(comboDictValue).getUrl(); + actionURLAttributeValue.getContent().add(actionDictUrl); + + assignmentURL.setExpression(new ObjectFactory().createAttributeValue(actionURLAttributeValue)); + obligation.getAttributeAssignmentExpression().add(assignmentURL); + + // Add Method Assignment: + AttributeAssignmentExpressionType assignmentMethod = new AttributeAssignmentExpressionType(); + assignmentMethod.setAttributeId(METHOD_ATTRIBUTEID); + assignmentMethod.setCategory(CATEGORY_RESOURCE); + + AttributeValueType methodAttributeValue = new AttributeValueType(); + methodAttributeValue.setDataType(STRING_DATATYPE); + String actionDictMethod = getActionPolicyDict(comboDictValue).getMethod(); + methodAttributeValue.getContent().add(actionDictMethod); + + assignmentMethod.setExpression(new ObjectFactory().createAttributeValue(methodAttributeValue)); + obligation.getAttributeAssignmentExpression().add(assignmentMethod); + + // Add JSON_URL Assignment: + String actionBody = getActionPolicyDict(comboDictValue).getBody(); + if (actionBody != null) { + AttributeAssignmentExpressionType assignmentJsonURL = new AttributeAssignmentExpressionType(); + assignmentJsonURL.setAttributeId(BODY_ATTRIBUTEID); + assignmentJsonURL.setCategory(CATEGORY_RESOURCE); + + AttributeValueType jsonURLAttributeValue = new AttributeValueType(); + jsonURLAttributeValue.setDataType(URI_DATATYPE); + jsonURLAttributeValue.getContent().add(CONFIG_URL + "/Action/" + policyName + ".json"); + + assignmentJsonURL.setExpression(new ObjectFactory().createAttributeValue(jsonURLAttributeValue)); + obligation.getAttributeAssignmentExpression().add(assignmentJsonURL); + } + + if(getActionPolicyDict(comboDictValue).getHeader() != null){ + String headerVal = getActionPolicyDict(comboDictValue).getHeader(); + if(headerVal != null && !headerVal.equals("")){ + // parse it on : to get number of headers + String[] result = headerVal.split(":"); + for (String eachString : result){ + // parse each value on = + String[] textFieldVals = eachString.split("="); + obligation.getAttributeAssignmentExpression().add(addDynamicHeaders(textFieldVals[0], textFieldVals[1])); + } + } + + } + + obligations.getObligationExpression().add(obligation); + return obligations; + } + + + // if compound setting the inner apply here + protected ApplyType getInnerActionApply(String value1Label) { + ApplyType actionApply = new ApplyType(); + int index = 0; + // check the index for the label. + for (String labelAttr : dynamicLabelRuleAlgorithms) { + if (labelAttr.equals(value1Label)) { + String value1 = dynamicFieldOneRuleAlgorithms.get(index).toString(); + // check if the row contains label again + for (String labelValue : dynamicLabelRuleAlgorithms) { + if (labelValue.equals(value1)) { + return getCompoundApply(index); + } + } + + // Getting the values from the form. + String functionKey = dynamicFieldFunctionRuleAlgorithms.get(index).toString(); + String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString(); + actionApply.setFunctionId(dropDownMap.get(functionKey)); + // if two text field are rule attributes. + if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) { + ApplyType innerActionApply1 = new ApplyType(); + ApplyType innerActionApply2 = new ApplyType(); + AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType(); + AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType(); + // If selected function is Integer function set integer functionID + if (functionKey.toLowerCase().contains("integer")) { + innerActionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY); + innerActionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY); + attributeDesignator1.setDataType(INTEGER_DATATYPE); + attributeDesignator2.setDataType(INTEGER_DATATYPE); + } else { + // If selected function is not a Integer function + // set String functionID + innerActionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY); + innerActionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY); + attributeDesignator1.setDataType(STRING_DATATYPE); + attributeDesignator2.setDataType(STRING_DATATYPE); + } + attributeDesignator1.setCategory(CATEGORY_RESOURCE); + attributeDesignator2.setCategory(CATEGORY_RESOURCE); + + // Here set actual field values + attributeDesignator1.setAttributeId(value1.contains("resource:") ? value1.substring(9): value1.substring(8)); + attributeDesignator2.setAttributeId(value1.contains("resource:") ? value1.substring(9): value1.substring(8)); + + innerActionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator1)); + innerActionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator2)); + + actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply1)); + actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply2)); + + } else {// if either of one text field is rule attribute. + ApplyType innerActionApply = new ApplyType(); + AttributeDesignatorType attributeDesignator = new AttributeDesignatorType(); + AttributeValueType actionConditionAttributeValue = new AttributeValueType(); + + if (functionKey.toLowerCase().contains("integer")) { + innerActionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY); + actionConditionAttributeValue.setDataType(INTEGER_DATATYPE); + attributeDesignator.setDataType(INTEGER_DATATYPE); + } else { + innerActionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY); + actionConditionAttributeValue.setDataType(STRING_DATATYPE); + attributeDesignator.setDataType(STRING_DATATYPE); + } + + String attributeId = null; + String attributeValue = null; + + // Find which textField has rule attribute and set it as + attributeId = value1; + attributeValue = value2; + + if (attributeId != null) { + attributeDesignator.setCategory(CATEGORY_RESOURCE); + attributeDesignator.setAttributeId(attributeId); + } + actionConditionAttributeValue.getContent().add(attributeValue); + innerActionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator)); + // Decide the order of element based the values. + if (attributeId.equals(value1)) { + actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply)); + actionApply.getExpression().add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue)); + } else { + actionApply.getExpression().add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue)); + actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply)); + } + } + } + index++; + } + return actionApply; + } + + // if the rule algorithm is multiple compound one setting the apply + protected ApplyType getCompoundApply(int index) { + ApplyType actionApply = new ApplyType(); + String selectedFunction = dynamicFieldFunctionRuleAlgorithms.get(index).toString(); + String value1 = dynamicFieldOneRuleAlgorithms.get(index).toString(); + String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString(); + actionApply.setFunctionId(dropDownMap.get(selectedFunction)); + actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1))); + actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2))); + return actionApply; + } + + // Adding the dynamic headers if any + private AttributeAssignmentExpressionType addDynamicHeaders(String header, String value) { + AttributeAssignmentExpressionType assignmentHeaders = new AttributeAssignmentExpressionType(); + assignmentHeaders.setAttributeId("headers:" + header); + assignmentHeaders.setCategory(CATEGORY_RESOURCE); + + AttributeValueType headersAttributeValue = new AttributeValueType(); + headersAttributeValue.setDataType(STRING_DATATYPE); + headersAttributeValue.getContent().add(value); + + assignmentHeaders.setExpression(new ObjectFactory().createAttributeValue(headersAttributeValue)); + return assignmentHeaders; + } + + private Map createDropDownMap(){ + JPAUtils jpaUtils = null; + Map dropDownMap = new HashMap<>(); + try { + jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf()); + } catch (Exception e) { + LOGGER.error("Exception Occured"+e); + } + if(jpaUtils != null){ + Map> functionMap = jpaUtils.getFunctionDatatypeMap(); + + for (Datatype id : functionMap.keySet()) { + List functionDefinitions = (List) functionMap + .get(id); + for (FunctionDefinition functionDef : functionDefinitions) { + dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid()); + } + } + } + return dropDownMap; + } + + private ActionPolicyDict getActionPolicyDict(String attributeName){ + ActionPolicyDict retObj = new ActionPolicyDict(); + EntityManager em = XACMLPapServlet.getEmf().createEntityManager(); + Query getActionPolicyDicts = em.createNamedQuery("ActionPolicyDict.findAll"); + List actionPolicyDicts = getActionPolicyDicts.getResultList(); + + for (Object id : actionPolicyDicts) { + ActionPolicyDict actionPolicy = (ActionPolicyDict) id; + if(attributeName.equals(actionPolicy.getAttributeName())){ + isAttribute = true; + retObj = actionPolicy; + break; + } + } + em.close(); + return retObj; + } + + @Override + public Object getCorrectPolicyDataObject() { + return policyAdapter.getPolicyData(); + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/AutoPushPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/AutoPushPolicy.java new file mode 100644 index 000000000..f9dbc287b --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/AutoPushPolicy.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + +import java.io.File; +import java.io.FileInputStream; +import java.nio.file.Paths; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Properties; +import java.util.Set; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.xacml.std.pap.StdPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; + +import com.att.research.xacml.api.pap.PDPPolicy; +/** + * Auto Push Policy based on the property file properties. + * + * @version 0.1 + */ +public class AutoPushPolicy { + + private static final Logger LOGGER = FlexLogger.getLogger(AutoPushPolicy.class); + + private String filePath = null; + private Properties properties; + private Long newModified; + private Long oldModified; + private File propFile; + + + /** + * Constructor Pass in the property file path. + */ + public AutoPushPolicy(String file){ + filePath = file; + properties = new Properties(); + propFile = Paths.get(filePath).toFile(); + readFile(); + } + + private void readFile(){ + try { + properties.load(new FileInputStream(propFile)); + oldModified = propFile.lastModified(); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "AutoPushPolicy", "Error while loading in the auto push properties file."); + } + } + + private StdPDPGroup addToGroup(String policyId, String policyName, String policyToCreateUpdate, StdPDPGroup pdpGroup) throws Exception{ + // Add to group. Send Notification. + StdPDPPolicy policy = new StdPDPPolicy(policyId, true, policyName, null); + //Get the current policies from the Group and Add the new one + Set currentPoliciesInGroup = pdpGroup.getPolicies(); + Set policies = new HashSet<>(); + policies.add(policy); + pdpGroup.copyPolicyToFile(policyId, new FileInputStream(Paths.get(policyToCreateUpdate).toFile())); + //If the selected policy is in the group we must remove it because the name is default + Iterator policyIterator = policies.iterator(); + while (policyIterator.hasNext()) { + PDPPolicy selPolicy = policyIterator.next(); + for (PDPPolicy existingPolicy : currentPoliciesInGroup) { + if (existingPolicy.getId().equals(selPolicy.getId())) { + pdpGroup.removePolicyFromGroup(existingPolicy); + LOGGER.debug("Removing policy: " + existingPolicy); + break; + } + } + } + if(currentPoliciesInGroup!=null){ + policies.addAll(currentPoliciesInGroup); + } + pdpGroup.setPolicies(policies); + return pdpGroup; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java new file mode 100644 index 000000000..3355fab85 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java @@ -0,0 +1,412 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; + +import com.att.research.xacml.std.IdentifierImpl; + +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.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +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; + +public class ClosedLoopPolicy extends Policy { + + private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopPolicy.class); + + public ClosedLoopPolicy() { + super(); + } + + public ClosedLoopPolicy(PolicyRestAdapter policyAdapter){ + this.policyAdapter = policyAdapter; + } + + //save configuration of the policy based on the policyname + private void saveConfigurations(String policyName, String jsonBody) { + try { + String body = jsonBody; + try { + try{ + //Remove the trapMaxAge in Verification Signature + body = body.replace(",\"trapMaxAge\":null", ""); + }catch(Exception e){ + LOGGER.debug("No Trap Max Age in JSON body"); + } + this.policyAdapter.setJsonBody(body); + } catch (Exception e) { + LOGGER.error("Exception Occured"+e); + } + + if(policyName.endsWith(".xml")){ + policyName = policyName.replace(".xml", ""); + } + PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator+ policyName +".json"); + out.println(body); + out.close(); + + } catch (Exception e) { + LOGGER.error("Exception Occured while writing Configuration Data"+e); + } + } + + //Utility to read json data from the existing file to a string + static String readFile(String path, Charset encoding) throws IOException { + + byte[] encoded = Files.readAllBytes(Paths.get(path)); + return new String(encoded, encoding); + + } + + //create the configuration file based on the policy name on adding the extension as .json + private String getConfigFile(String filename) { + filename = FilenameUtils.removeExtension(filename); + if (filename.endsWith(".xml")) { + filename = filename.substring(0, filename.length() - 4); + } + filename = filename + ".json"; + return filename; + } + + @Override + public Map savePolicies() throws Exception { + + Map successMap = new HashMap<>(); + if(isPolicyExists()){ + successMap.put("EXISTS", "This Policy already exist on the PAP"); + return successMap; + } + + if(!isPreparedToSave()){ + prepareToSave(); + } + + // Until here we prepared the data and here calling the method to create xml. + Path newPolicyPath = null; + newPolicyPath = Paths.get(policyAdapter.getNewFileName()); + + successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + return successMap; + } + + //This is the method for preparing the policy for saving. We have broken it out + //separately because the fully configured policy is used for multiple things + @Override + public boolean prepareToSave() throws Exception{ + + if(isPreparedToSave()){ + //we have already done this + return true; + } + + int version = 0; + String policyID = policyAdapter.getPolicyID(); + version = policyAdapter.getHighestVersion(); + + // Create the Instance for pojo, PolicyType object is used in marshalling. + if (policyAdapter.getPolicyType().equals("Config")) { + PolicyType policyConfig = new PolicyType(); + + policyConfig.setVersion(Integer.toString(version)); + policyConfig.setPolicyId(policyID); + policyConfig.setTarget(new TargetType()); + policyAdapter.setData(policyConfig); + } + policyName = policyAdapter.getNewFileName(); + if (policyAdapter.getData() != null) { + // Save the Configurations file with the policy name with extention based on selection. + String jsonBody = policyAdapter.getJsonBody(); + saveConfigurations(policyName, jsonBody); + + // Make sure the filename ends with an extension + if (policyName.endsWith(".xml") == false) { + policyName = policyName + ".xml"; + } + + PolicyType faultPolicy = (PolicyType) policyAdapter.getData(); + + faultPolicy.setDescription(policyAdapter.getPolicyDescription()); + + faultPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); + + AllOfType allOfOne = new AllOfType(); + String fileName = policyAdapter.getNewFileName(); + String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); + } + allOfOne.getMatch().add(createMatch("PolicyName", name)); + AllOfType allOf = new AllOfType(); + // Adding the matches to AllOfType element + // Match for Onap + allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); + // Match for riskType + allOf.getMatch().add( + createDynamicMatch("RiskType", policyAdapter.getRiskType())); + // Match for riskLevel + allOf.getMatch().add( + createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + // Match for riskguard + allOf.getMatch().add( + createDynamicMatch("guard", policyAdapter.getGuard())); + // Match for ttlDate + allOf.getMatch().add( + createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + + AnyOfType anyOf = new AnyOfType(); + anyOf.getAllOf().add(allOfOne); + anyOf.getAllOf().add(allOf); + + TargetType target = new TargetType(); + ((TargetType) target).getAnyOf().add(anyOf); + // Adding the target to the policy element + faultPolicy.setTarget((TargetType) target); + + RuleType rule = new RuleType(); + rule.setRuleId(policyAdapter.getRuleID()); + rule.setEffect(EffectType.PERMIT); + + // Create Target in Rule + AllOfType allOfInRule = new AllOfType(); + + // Creating match for ACCESS in rule target + MatchType accessMatch = new MatchType(); + AttributeValueType accessAttributeValue = new AttributeValueType(); + accessAttributeValue.setDataType(STRING_DATATYPE); + accessAttributeValue.getContent().add("ACCESS"); + accessMatch.setAttributeValue(accessAttributeValue); + AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); + URI accessURI = null; + try { + accessURI = new URI(ACTION_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy", "Exception creating ACCESS URI"); + } + accessAttributeDesignator.setCategory(CATEGORY_ACTION); + accessAttributeDesignator.setDataType(STRING_DATATYPE); + accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); + accessMatch.setAttributeDesignator(accessAttributeDesignator); + accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + // Creating Config Match in rule Target + MatchType closedMatch = new MatchType(); + AttributeValueType closedAttributeValue = new AttributeValueType(); + closedAttributeValue.setDataType(STRING_DATATYPE); + closedAttributeValue.getContent().add("Config"); + closedMatch.setAttributeValue(closedAttributeValue); + AttributeDesignatorType closedAttributeDesignator = new AttributeDesignatorType(); + URI closedURI = null; + try { + closedURI = new URI(RESOURCE_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy", "Exception creating closed URI"); + } + closedAttributeDesignator.setCategory(CATEGORY_RESOURCE); + closedAttributeDesignator.setDataType(STRING_DATATYPE); + closedAttributeDesignator.setAttributeId(new IdentifierImpl(closedURI).stringValue()); + closedMatch.setAttributeDesignator(closedAttributeDesignator); + closedMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + allOfInRule.getMatch().add(accessMatch); + allOfInRule.getMatch().add(closedMatch); + + AnyOfType anyOfInRule = new AnyOfType(); + anyOfInRule.getAllOf().add(allOfInRule); + + TargetType targetInRule = new TargetType(); + targetInRule.getAnyOf().add(anyOfInRule); + + rule.setTarget(targetInRule); + rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); + + faultPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); + policyAdapter.setPolicyData(faultPolicy); + + } else { + PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); + } + + setPreparedToSave(true); + return true; + } + + // Data required for Advice part is setting here. + private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { + AdviceExpressionsType advices = new AdviceExpressionsType(); + AdviceExpressionType advice = new AdviceExpressionType(); + advice.setAdviceId("faultID"); + advice.setAppliesTo(EffectType.PERMIT); + // For Configuration + AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); + assignment1.setAttributeId("type"); + assignment1.setCategory(CATEGORY_RESOURCE); + assignment1.setIssuer(""); + + AttributeValueType configNameAttributeValue = new AttributeValueType(); + configNameAttributeValue.setDataType(STRING_DATATYPE); + configNameAttributeValue.getContent().add("Configuration"); + assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); + + advice.getAttributeAssignmentExpression().add(assignment1); + // For Config file Url if configurations are provided. + AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); + assignment2.setAttributeId("URLID"); + assignment2.setCategory(CATEGORY_RESOURCE); + assignment2.setIssuer(""); + + AttributeValueType AttributeValue = new AttributeValueType(); + AttributeValue.setDataType(URI_DATATYPE); + String content = CONFIG_URL +"/Config/" + getConfigFile(policyName); + System.out.println("URL value :" + content); + AttributeValue.getContent().add(content); + assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); + + advice.getAttributeAssignmentExpression().add(assignment2); + AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); + assignment3.setAttributeId("PolicyName"); + assignment3.setCategory(CATEGORY_RESOURCE); + assignment3.setIssuer(""); + + AttributeValueType attributeValue3 = new AttributeValueType(); + attributeValue3.setDataType(STRING_DATATYPE); + fileName = FilenameUtils.removeExtension(fileName); + fileName = fileName + ".xml"; + String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); + } + attributeValue3.getContent().add(name); + assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); + advice.getAttributeAssignmentExpression().add(assignment3); + + AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); + assignment4.setAttributeId("VersionNumber"); + assignment4.setCategory(CATEGORY_RESOURCE); + assignment4.setIssuer(""); + + AttributeValueType configNameAttributeValue4 = new AttributeValueType(); + configNameAttributeValue4.setDataType(STRING_DATATYPE); + configNameAttributeValue4.getContent().add(Integer.toString(version)); + assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); + + advice.getAttributeAssignmentExpression().add(assignment4); + + AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); + assignment5.setAttributeId("matching:" + ONAPID); + assignment5.setCategory(CATEGORY_RESOURCE); + assignment5.setIssuer(""); + + AttributeValueType configNameAttributeValue5 = new AttributeValueType(); + configNameAttributeValue5.setDataType(STRING_DATATYPE); + configNameAttributeValue5.getContent().add(policyAdapter.getOnapName()); + assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); + + advice.getAttributeAssignmentExpression().add(assignment5); + + //Risk Attributes + AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); + assignment6.setAttributeId("RiskType"); + assignment6.setCategory(CATEGORY_RESOURCE); + assignment6.setIssuer(""); + + AttributeValueType configNameAttributeValue6 = new AttributeValueType(); + configNameAttributeValue6.setDataType(STRING_DATATYPE); + configNameAttributeValue6.getContent().add(policyAdapter.getRiskType()); + assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); + + advice.getAttributeAssignmentExpression().add(assignment6); + + AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); + assignment7.setAttributeId("RiskLevel"); + assignment7.setCategory(CATEGORY_RESOURCE); + assignment7.setIssuer(""); + + AttributeValueType configNameAttributeValue7 = new AttributeValueType(); + configNameAttributeValue7.setDataType(STRING_DATATYPE); + configNameAttributeValue7.getContent().add(policyAdapter.getRiskLevel()); + assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); + + advice.getAttributeAssignmentExpression().add(assignment7); + + AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); + assignment8.setAttributeId("guard"); + assignment8.setCategory(CATEGORY_RESOURCE); + assignment8.setIssuer(""); + + AttributeValueType configNameAttributeValue8 = new AttributeValueType(); + configNameAttributeValue8.setDataType(STRING_DATATYPE); + configNameAttributeValue8.getContent().add(policyAdapter.getGuard()); + assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8)); + + advice.getAttributeAssignmentExpression().add(assignment8); + + AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); + assignment9.setAttributeId("TTLDate"); + assignment9.setCategory(CATEGORY_RESOURCE); + assignment9.setIssuer(""); + + AttributeValueType configNameAttributeValue9 = new AttributeValueType(); + configNameAttributeValue9.setDataType(STRING_DATATYPE); + configNameAttributeValue9.getContent().add(policyAdapter.getTtlDate()); + assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); + + advice.getAttributeAssignmentExpression().add(assignment9); + + + + advices.getAdviceExpression().add(advice); + return advices; + } + + @Override + public Object getCorrectPolicyDataObject() { + return policyAdapter.getPolicyData(); + } + + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java new file mode 100644 index 000000000..1b29c0369 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java @@ -0,0 +1,564 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.StringReader; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; +import java.util.Scanner; + +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +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.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +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.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.xml.sax.ErrorHandler; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; +import org.xml.sax.XMLReader; + +import com.att.research.xacml.std.IdentifierImpl; + +public class ConfigPolicy extends Policy { + + /** + * Config Fields + */ + private static final Logger LOGGER = FlexLogger.getLogger(ConfigPolicy.class); + + public static final String JSON_CONFIG = "JSON"; + public static final String XML_CONFIG = "XML"; + public static final String PROPERTIES_CONFIG = "PROPERTIES"; + public static final String OTHER_CONFIG = "OTHER"; + + private String configBodyData; + + public ConfigPolicy() { + super(); + } + + public ConfigPolicy(PolicyRestAdapter policyAdapter){ + this.policyAdapter = policyAdapter; + } + + // Saving the Configurations file at server location for config policy. + protected void saveConfigurations(String policyName) { + try { + String fileName = getConfigFile(policyName); + FileWriter fw = new FileWriter(CONFIG_HOME + File.separator + fileName); + BufferedWriter bw = new BufferedWriter(fw); + bw.write(configBodyData); + bw.close(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Configuration is succesfully saved"); + } + } catch (IOException e) { + LOGGER.error("Exception Occured while writing Configuration Data"+e); + } + } + + + // Here we are adding the extension for the configurations file based on the + // config type selection for saving. + private String getConfigFile(String filename) { + filename = FilenameUtils.removeExtension(filename); + if (filename.endsWith(".xml")) { + filename = filename.substring(0, filename.length() - 4); + } + String id = policyAdapter.getConfigType(); + + if (id != null) { + if (id.equalsIgnoreCase(JSON_CONFIG)) { + filename = filename + ".json"; + } + if (id.equalsIgnoreCase(XML_CONFIG)) { + filename = filename + ".xml"; + } + if (id.equalsIgnoreCase(PROPERTIES_CONFIG)) { + filename = filename + ".properties"; + } + if (id.equalsIgnoreCase(OTHER_CONFIG)) { + filename = filename + ".txt"; + } + } + return filename; + } + + + // Validations for Config form + /* + * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object... + * BODY VALIDATION WILL BE DONE BY THE PAP-REST after receiving and deserializing the JSON object + */ + public boolean validateConfigForm() { + + isValidForm = true; + + /* + * Validate Text Area Body + */ + configBodyData = policyAdapter.getConfigBodyData(); + String id = policyAdapter.getConfigType(); + if (id != null) { + if (id.equals(JSON_CONFIG)) { + if (!isJSONValid(configBodyData)) { + isValidForm = false; + } + } else if (id.equals(XML_CONFIG)) { + if (!isXMLValid(configBodyData)) { + isValidForm = false; + } + } else if (id.equals(PROPERTIES_CONFIG)) { + if (!isPropValid(configBodyData)||configBodyData.equals("")) { + isValidForm = false; + } + } else if (id.equals(OTHER_CONFIG)) { + if (configBodyData.equals("")) { + isValidForm = false; + } + } + } + return isValidForm; + + } + + // 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 (ParserConfigurationException e) { + return false; + } catch (SAXException e) { + return false; + } catch (IOException 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.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; + + } + + public class XMLErrorHandler implements ErrorHandler { + + public void warning(SAXParseException e) throws SAXException { + System.out.println(e.getMessage()); + } + + public void error(SAXParseException e) throws SAXException { + System.out.println(e.getMessage()); + } + + public void fatalError(SAXParseException e) throws SAXException { + System.out.println(e.getMessage()); + } + + } + + @Override + public Map savePolicies() throws Exception { + + Map successMap = new HashMap<>(); + if(isPolicyExists()){ + successMap.put("EXISTS", "This Policy already exist on the PAP"); + return successMap; + } + + if(!isPreparedToSave()){ + //Prep and configure the policy for saving + prepareToSave(); + } + + // Until here we prepared the data and here calling the method to create xml. + Path newPolicyPath = null; + newPolicyPath = Paths.get(policyAdapter.getNewFileName()); + successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + return successMap; + } + + //This is the method for preparing the policy for saving. We have broken it out + //separately because the fully configured policy is used for multiple things + @Override + public boolean prepareToSave() throws Exception{ + + if(isPreparedToSave()){ + return true; + } + + int version = 0; + String policyID = policyAdapter.getPolicyID(); + version = policyAdapter.getHighestVersion(); + + // Create the Instance for pojo, PolicyType object is used in marshalling. + if (policyAdapter.getPolicyType().equals("Config")) { + PolicyType policyConfig = new PolicyType(); + + policyConfig.setVersion(Integer.toString(version)); + policyConfig.setPolicyId(policyID); + policyConfig.setTarget(new TargetType()); + policyAdapter.setData(policyConfig); + } + + policyName = policyAdapter.getNewFileName(); + configBodyData = policyAdapter.getConfigBodyData(); + saveConfigurations(policyName); + + if (policyAdapter.getData() != null) { + PolicyType configPolicy = (PolicyType) policyAdapter.getData(); + + configPolicy.setDescription(policyAdapter.getPolicyDescription()); + + configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); + AllOfType allOfOne = new AllOfType(); + + String fileName = policyAdapter.getNewFileName(); + String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); + } + allOfOne.getMatch().add(createMatch("PolicyName", name)); + AllOfType allOf = new AllOfType(); + + // Adding the matches to AllOfType element Match for Onap + allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); + // Match for riskType + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); + // Match for riskLevel + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + // Match for riskguard + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); + // Match for ttlDate + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + // Match for ConfigName + allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName())); + + Map dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes(); + + // If there is any dynamic field create the matches here + for (String keyField : dynamicFieldConfigAttributes.keySet()) { + String key = keyField; + String value = dynamicFieldConfigAttributes.get(key); + MatchType dynamicMatch = createDynamicMatch(key, value); + allOf.getMatch().add(dynamicMatch); + } + + AnyOfType anyOf = new AnyOfType(); + anyOf.getAllOf().add(allOfOne); + anyOf.getAllOf().add(allOf); + + TargetType target = new TargetType(); + ((TargetType) target).getAnyOf().add(anyOf); + + // Adding the target to the policy element + configPolicy.setTarget((TargetType) target); + + RuleType rule = new RuleType(); + rule.setRuleId(policyAdapter.getRuleID()); + rule.setEffect(EffectType.PERMIT); + + // Create Target in Rule + AllOfType allOfInRule = new AllOfType(); + + // Creating match for ACCESS in rule target + MatchType accessMatch = new MatchType(); + AttributeValueType accessAttributeValue = new AttributeValueType(); + accessAttributeValue.setDataType(STRING_DATATYPE); + accessAttributeValue.getContent().add("ACCESS"); + accessMatch.setAttributeValue(accessAttributeValue); + AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); + URI accessURI = null; + try{ + accessURI = new URI(ACTION_ID); + }catch(URISyntaxException e){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating ACCESS URI"); + } + accessAttributeDesignator.setCategory(CATEGORY_ACTION); + accessAttributeDesignator.setDataType(STRING_DATATYPE); + accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); + accessMatch.setAttributeDesignator(accessAttributeDesignator); + accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + // Creating Config Match in rule Target + MatchType configMatch = new MatchType(); + AttributeValueType configAttributeValue = new AttributeValueType(); + configAttributeValue.setDataType(STRING_DATATYPE); + configAttributeValue.getContent().add("Config"); + configMatch.setAttributeValue(configAttributeValue); + AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType(); + URI configURI = null; + try{ + configURI = new URI(RESOURCE_ID); + }catch(URISyntaxException e){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating Config URI"); + } + configAttributeDesignator.setCategory(CATEGORY_RESOURCE); + configAttributeDesignator.setDataType(STRING_DATATYPE); + configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue()); + configMatch.setAttributeDesignator(configAttributeDesignator); + configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + allOfInRule.getMatch().add(accessMatch); + allOfInRule.getMatch().add(configMatch); + + AnyOfType anyOfInRule = new AnyOfType(); + anyOfInRule.getAllOf().add(allOfInRule); + + TargetType targetInRule = new TargetType(); + targetInRule.getAnyOf().add(anyOfInRule); + + rule.setTarget(targetInRule); + rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); + + configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); + policyAdapter.setPolicyData(configPolicy); + + } else { + PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); + } + setPreparedToSave(true); + return true; + } + + // Data required for Advice part is setting here. + private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { + AdviceExpressionsType advices = new AdviceExpressionsType(); + AdviceExpressionType advice = new AdviceExpressionType(); + advice.setAdviceId("configID"); + advice.setAppliesTo(EffectType.PERMIT); + + // For Configuration + AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); + assignment1.setAttributeId("type"); + assignment1.setCategory(CATEGORY_RESOURCE); + assignment1.setIssuer(""); + + AttributeValueType configNameAttributeValue = new AttributeValueType(); + configNameAttributeValue.setDataType(STRING_DATATYPE); + configNameAttributeValue.getContent().add("Configuration"); + assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); + + advice.getAttributeAssignmentExpression().add(assignment1); + + // For Config file Url if configurations are provided. + if (policyAdapter.getConfigType() != null) { + AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); + assignment2.setAttributeId("URLID"); + assignment2.setCategory(CATEGORY_RESOURCE); + assignment2.setIssuer(""); + + AttributeValueType AttributeValue = new AttributeValueType(); + AttributeValue.setDataType(URI_DATATYPE); + String content = "$URL" + "/Config/" + getConfigFile(policyName); + AttributeValue.getContent().add(content); + assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); + + advice.getAttributeAssignmentExpression().add(assignment2); + AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); + assignment3.setAttributeId("PolicyName"); + assignment3.setCategory(CATEGORY_RESOURCE); + assignment3.setIssuer(""); + + AttributeValueType attributeValue3 = new AttributeValueType(); + attributeValue3.setDataType(STRING_DATATYPE); + + fileName = FilenameUtils.removeExtension(fileName); + fileName = fileName + ".xml"; + String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); + } + attributeValue3.getContent().add(name); + assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); + advice.getAttributeAssignmentExpression().add(assignment3); + + AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); + assignment4.setAttributeId("VersionNumber"); + assignment4.setCategory(CATEGORY_RESOURCE); + assignment4.setIssuer(""); + + AttributeValueType configNameAttributeValue4 = new AttributeValueType(); + configNameAttributeValue4.setDataType(STRING_DATATYPE); + configNameAttributeValue4.getContent().add(Integer.toString(version)); + assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); + + advice.getAttributeAssignmentExpression().add(assignment4); + + AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); + assignment5.setAttributeId("matching:" + ONAPID); + assignment5.setCategory(CATEGORY_RESOURCE); + assignment5.setIssuer(""); + + AttributeValueType configNameAttributeValue5 = new AttributeValueType(); + configNameAttributeValue5.setDataType(STRING_DATATYPE); + configNameAttributeValue5.getContent().add(policyAdapter.getOnapName()); + assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); + + advice.getAttributeAssignmentExpression().add(assignment5); + + AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); + assignment6.setAttributeId("matching:" + CONFIGID); + assignment6.setCategory(CATEGORY_RESOURCE); + assignment6.setIssuer(""); + + AttributeValueType configNameAttributeValue6 = new AttributeValueType(); + configNameAttributeValue6.setDataType(STRING_DATATYPE); + configNameAttributeValue6.getContent().add(policyAdapter.getConfigName()); + assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); + + advice.getAttributeAssignmentExpression().add(assignment6); + + Map dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes(); + for (String keyField : dynamicFieldConfigAttributes.keySet()) { + String key = keyField; + String value = dynamicFieldConfigAttributes.get(key); + AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); + assignment7.setAttributeId("matching:" + key); + assignment7.setCategory(CATEGORY_RESOURCE); + assignment7.setIssuer(""); + + AttributeValueType configNameAttributeValue7 = new AttributeValueType(); + configNameAttributeValue7.setDataType(STRING_DATATYPE); + configNameAttributeValue7.getContent().add(value); + assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); + + advice.getAttributeAssignmentExpression().add(assignment7); + } + } + + //Risk Attributes + AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); + assignment8.setAttributeId("RiskType"); + assignment8.setCategory(CATEGORY_RESOURCE); + assignment8.setIssuer(""); + + AttributeValueType configNameAttributeValue8 = new AttributeValueType(); + configNameAttributeValue8.setDataType(STRING_DATATYPE); + configNameAttributeValue8.getContent().add(policyAdapter.getRiskType()); + assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8)); + + advice.getAttributeAssignmentExpression().add(assignment8); + + AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); + assignment9.setAttributeId("RiskLevel"); + assignment9.setCategory(CATEGORY_RESOURCE); + assignment9.setIssuer(""); + + AttributeValueType configNameAttributeValue9 = new AttributeValueType(); + configNameAttributeValue9.setDataType(STRING_DATATYPE); + configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel()); + assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); + + advice.getAttributeAssignmentExpression().add(assignment9); + + AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); + assignment10.setAttributeId("guard"); + assignment10.setCategory(CATEGORY_RESOURCE); + assignment10.setIssuer(""); + + AttributeValueType configNameAttributeValue10 = new AttributeValueType(); + configNameAttributeValue10.setDataType(STRING_DATATYPE); + configNameAttributeValue10.getContent().add(policyAdapter.getGuard()); + assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10)); + + advice.getAttributeAssignmentExpression().add(assignment10); + + AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType(); + assignment11.setAttributeId("TTLDate"); + assignment11.setCategory(CATEGORY_RESOURCE); + assignment11.setIssuer(""); + + AttributeValueType configNameAttributeValue11 = new AttributeValueType(); + configNameAttributeValue11.setDataType(STRING_DATATYPE); + configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate()); + assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11)); + + advice.getAttributeAssignmentExpression().add(assignment11); + + advices.getAdviceExpression().add(advice); + return advices; + } + + @Override + public Object getCorrectPolicyDataObject() { + return policyAdapter.getPolicyData(); + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java new file mode 100644 index 000000000..7c0d2683c --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + +import java.util.HashMap; +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.dao.CommonClassDao; +import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.utils.PolicyUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service +public class CreateBRMSRuleTemplate { + private static final Logger LOGGER = FlexLogger.getLogger(CreateBRMSRuleTemplate.class); + private static CommonClassDao commonClassDao; + + @Autowired + public CreateBRMSRuleTemplate(CommonClassDao commonClassDao){ + CreateBRMSRuleTemplate.commonClassDao = commonClassDao; + } + + public CreateBRMSRuleTemplate() {} + + public Map addRule(String rule, String ruleName, String description, String userID) { + Map responseMap = new HashMap<>(); + if(rule!=null && !PolicyUtils.brmsRawValidate(rule).contains("[ERR")){ + List duplicateData = commonClassDao.checkDuplicateEntry(ruleName, "ruleName", BRMSParamTemplate.class); + if(duplicateData!=null && !duplicateData.isEmpty()){ + LOGGER.error("Import new service failed. Service already exists"); + responseMap.put("DBError", "EXISTS"); + return responseMap; + }else{ + BRMSParamTemplate brmsParamTemplate = new BRMSParamTemplate(); + brmsParamTemplate.setDescription(description); + brmsParamTemplate.setRuleName(ruleName); + brmsParamTemplate.setRule(rule); + UserInfo userCreatedBy = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", userID); + brmsParamTemplate.setUserCreatedBy(userCreatedBy); + commonClassDao.save(brmsParamTemplate); + LOGGER.info("Template created with " + ruleName + " by " + userID); + } + responseMap.put("success", "success"); + }else{ + LOGGER.debug("Error during validating the rule for creating record for BRMS Param Template"); + responseMap.put("error", "VALIDATION"); + } + return responseMap; + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java new file mode 100644 index 000000000..047342ad0 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java @@ -0,0 +1,692 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.BRMSParamTemplate; + +import com.att.research.xacml.std.IdentifierImpl; + +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.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +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; + +public class CreateBrmsParamPolicy extends Policy { + + private static final Logger LOGGER = FlexLogger.getLogger(CreateBrmsParamPolicy.class); + + public CreateBrmsParamPolicy() { + super(); + } + + public CreateBrmsParamPolicy(PolicyRestAdapter policyAdapter) { + this.policyAdapter = policyAdapter; + this.policyAdapter.setConfigType(policyAdapter.getConfigType()); + + } + + public String expandConfigBody(String ruleContents, Map brmsParamBody) { + + Map copyMap=new HashMap<>(); + copyMap.putAll(brmsParamBody); + copyMap.put("policyName", policyName.substring(0, policyName.replace(".xml", "").lastIndexOf("."))); + copyMap.put("policyScope", policyAdapter.getDomainDir()); + copyMap.put("policyVersion",policyAdapter.getHighestVersion().toString()); + copyMap.put("unique", ("p"+policyName+UUID.randomUUID().toString()).replaceAll("[^A-Za-z0-9]", "")); + + //Finding all the keys in the Map data-structure. + Iterator iterator = copyMap.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(ruleContents); + //Replacing the value with the inputs provided by the user in the editor. + String finalInput = copyMap.get(input); + if(finalInput.contains("$")){ + finalInput = finalInput.replace("$", "\\$"); + } + ruleContents=m.replaceAll(finalInput); + } + return ruleContents; + } + + + + // Utility to read json data from the existing file to a string + static String readFile(String path, Charset encoding) throws IOException { + + byte[] encoded = Files.readAllBytes(Paths.get(path)); + return new String(encoded, encoding); + + } + + // Saving the Configurations file at server location for config policy. + protected void saveConfigurations(String policyName, String ruleBody) { + try { + if (policyName.endsWith(".xml")) { + policyName = policyName.substring(0, + policyName.lastIndexOf(".xml")); + } + PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt"); + String expandedBody=expandConfigBody(ruleBody,policyAdapter.getBrmsParamBody()); + out.println(expandedBody); + policyAdapter.setJsonBody(expandedBody); + policyAdapter.setConfigBodyData(expandedBody); + out.close(); + + + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving configuration file"); + } + } + + + // Here we are adding the extension for the configurations file based on the + // config type selection for saving. + private String getConfigFile(String filename) { + filename = FilenameUtils.removeExtension(filename); + if (filename.endsWith(".txt")) { + filename = filename.substring(0, filename.length() - 3); + } + + filename = filename + ".txt"; + return filename; + } + + // Validations for Config form + public boolean validateConfigForm() { + + // Validating mandatory Fields. + isValidForm = true; + return isValidForm; + + } + + @Override + public Map savePolicies() throws Exception { + + Map successMap = new HashMap<>(); + if(isPolicyExists()){ + successMap.put("EXISTS", "This Policy already exist on the PAP"); + return successMap; + } + + if (!isPreparedToSave()) { + prepareToSave(); + } + // Until here we prepared the data and here calling the method to create + // xml. + Path newPolicyPath = null; + newPolicyPath = Paths.get(policyAdapter.getNewFileName()); + successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + if(successMap == null){ + successMap = new HashMap<>(); + PolicyLogger.error("Failed to Update the Database Dictionary Tables."); + successMap.put("error", "DB UPDATE"); + } + return successMap; + } + + private String getValueFromDictionary(String templateName){ + String ruleTemplate = null; + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); + String queryString="from BRMSParamTemplate where param_template_name= '"+templateName+"'"; + List result = dbConnection.getDataByQuery(queryString); + if(!result.isEmpty()){ + BRMSParamTemplate template = (BRMSParamTemplate) result.get(0); + ruleTemplate = template.getRule(); + } + return ruleTemplate; + } + + protected Map findType(String rule) { + Map mapFieldType= new HashMap<>(); + if(rule!=null){ + try { + String params = ""; + 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("//")) { + if(!(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) { + line = line.split("\\/\\*")[0]; + } + } else { + line = line.split("\\/\\*")[0]; + } + } + if (line.contains("*/")) { + comment = false; + try { + line = line.split("\\*\\/")[1].replace("*/", ""); + } catch (Exception e) { + line = ""; + } + } + if (comment) { + continue; + } + if (flag) { + params = params + line; + } + if (line.contains("declare Params")) { + params = params + line; + flag = true; + } + if (line.contains("end") && flag) { + break; + } + } + params = params.replace("declare Params", "").replace("end", "") + .replaceAll("\\s+", ""); + String[] components = params.split(":"); + String caption = ""; + for (int i = 0; i < components.length; i++) { + String type = ""; + if (i == 0) { + caption = components[i]; + } + if(caption.equals("")){ + break; + } + String nextComponent = ""; + try { + nextComponent = components[i + 1]; + } catch (Exception e) { + nextComponent = components[i]; + } + //If the type is of type String then we add the UI Item and type to the map. + if (nextComponent.startsWith("String")) { + type = "String"; + mapFieldType.put(caption, type); + caption = nextComponent.replace("String", ""); + } else if (nextComponent.startsWith("int")) { + type = "int"; + mapFieldType.put(caption, type); + caption = nextComponent.replace("int", ""); + } + } + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CreateBrmsParamPolicy", "Exception parsing file in findType"); + } + } + return mapFieldType; + } + + // This is the method for preparing the policy for saving. We have broken it + // out + // separately because the fully configured policy is used for multiple + // things + @Override + public boolean prepareToSave() throws Exception { + + if (isPreparedToSave()) { + // we have already done this + return true; + } + + int version = 0; + String policyID = policyAdapter.getPolicyID(); + version = policyAdapter.getHighestVersion(); + + // Create the Instance for pojo, PolicyType object is used in + // marshalling. + if (policyAdapter.getPolicyType().equals("Config")) { + PolicyType policyConfig = new PolicyType(); + + policyConfig.setVersion(Integer.toString(version)); + policyConfig.setPolicyId(policyID); + policyConfig.setTarget(new TargetType()); + policyAdapter.setData(policyConfig); + } + + policyName = policyAdapter.getNewFileName(); + + if (policyAdapter.getData() != null) { + Map ruleAndUIValue= policyAdapter.getBrmsParamBody(); + String tempateValue= ruleAndUIValue.get("templateName"); + String valueFromDictionary= getValueFromDictionary(tempateValue); + + //Get the type of the UI Fields. + Map typeOfUIField=findType(valueFromDictionary); + String generatedRule=null; + String body = ""; + + try { + + try { + body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " + + "<$%BRMSParamTemplate=" + tempateValue + "%$> \n */ \n"; + body = body + valueFromDictionary + "\n"; + generatedRule = "rule \"" +policyName.substring(0, policyName.replace(".xml", "").lastIndexOf(".")) +".Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();"; + + //We first read the map data structure(ruleAndUIValue) received from the PAP-ADMIN + //We ignore if the key is "templateName as we are interested only in the UI fields and its value. + //We have one more map data structure(typeOfUIField) created by parsing the Drools rule. + //From the type of the UI field(String/int) we structure whether to put the "" or not. + for (Map.Entry entry : ruleAndUIValue.entrySet()) { + if(entry.getKey()!="templateName") + { + for(Map.Entry fieldType:typeOfUIField.entrySet()) + { + if(fieldType.getKey().equalsIgnoreCase(entry.getKey())) + { + String key = entry.getKey().substring(0, 1).toUpperCase() + entry.getKey().substring(1); + if(fieldType.getValue()=="String") + { + //Type is String + generatedRule = generatedRule + "\n\t\tparams.set" + + key + "(\"" + + entry.getValue() + "\");"; + } + else{ + generatedRule = generatedRule + "\n\t\tparams.set" + + key + "(" + + entry.getValue() + ");"; + } + } + } + } + } + + generatedRule = generatedRule + + "\n\t\tinsert(params);\nend"; + LOGGER.info("New rule generated with :" + generatedRule); + body = body + generatedRule; + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy"); + } + } + catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy"); + } + + saveConfigurations(policyName,body); + + // Make sure the filename ends with an extension + if (policyName.endsWith(".xml") == false) { + policyName = policyName + ".xml"; + } + + PolicyType configPolicy = (PolicyType) policyAdapter.getData(); + + configPolicy.setDescription(policyAdapter.getPolicyDescription()); + + configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); + + AllOfType allOfOne = new AllOfType(); + + String fileName = policyAdapter.getNewFileName(); + String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf("/") + 1, + fileName.length()); + } + allOfOne.getMatch().add(createMatch("PolicyName", name)); + + + AllOfType allOf = new AllOfType(); + + // Match for ONAPName + allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); + allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName())); + // Match for riskType + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); + // Match for riskLevel + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + // Match for riskguard + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); + // Match for ttlDate + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + AnyOfType anyOf = new AnyOfType(); + anyOf.getAllOf().add(allOfOne); + anyOf.getAllOf().add(allOf); + + TargetType target = new TargetType(); + ((TargetType) target).getAnyOf().add(anyOf); + + // Adding the target to the policy element + configPolicy.setTarget((TargetType) target); + + RuleType rule = new RuleType(); + rule.setRuleId(policyAdapter.getRuleID()); + + rule.setEffect(EffectType.PERMIT); + + // Create Target in Rule + AllOfType allOfInRule = new AllOfType(); + + // Creating match for ACCESS in rule target + MatchType accessMatch = new MatchType(); + AttributeValueType accessAttributeValue = new AttributeValueType(); + accessAttributeValue.setDataType(STRING_DATATYPE); + accessAttributeValue.getContent().add("ACCESS"); + accessMatch.setAttributeValue(accessAttributeValue); + AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); + URI accessURI = null; + try { + accessURI = new URI(ACTION_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy", "Exception creating ACCESS URI"); + } + accessAttributeDesignator.setCategory(CATEGORY_ACTION); + accessAttributeDesignator.setDataType(STRING_DATATYPE); + accessAttributeDesignator.setAttributeId(new IdentifierImpl( + accessURI).stringValue()); + accessMatch.setAttributeDesignator(accessAttributeDesignator); + accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + // Creating Config Match in rule Target + MatchType configMatch = new MatchType(); + AttributeValueType configAttributeValue = new AttributeValueType(); + configAttributeValue.setDataType(STRING_DATATYPE); + + configAttributeValue.getContent().add("Config"); + + configMatch.setAttributeValue(configAttributeValue); + AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType(); + URI configURI = null; + try { + configURI = new URI(RESOURCE_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy", "Exception creating Config URI"); + } + + configAttributeDesignator.setCategory(CATEGORY_RESOURCE); + configAttributeDesignator.setDataType(STRING_DATATYPE); + configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue()); + configMatch.setAttributeDesignator(configAttributeDesignator); + configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + allOfInRule.getMatch().add(accessMatch); + allOfInRule.getMatch().add(configMatch); + + AnyOfType anyOfInRule = new AnyOfType(); + anyOfInRule.getAllOf().add(allOfInRule); + + TargetType targetInRule = new TargetType(); + targetInRule.getAnyOf().add(anyOfInRule); + + rule.setTarget(targetInRule); + rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); + + configPolicy + .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() + .add(rule); + policyAdapter.setPolicyData(configPolicy); + + } else { + PolicyLogger.error("Unsupported data object." + + policyAdapter.getData().getClass().getCanonicalName()); + } + setPreparedToSave(true); + return true; + } + + // Data required for Advice part is setting here. + private AdviceExpressionsType getAdviceExpressions(int version, + String fileName) { + + //Policy Config ID Assignment + AdviceExpressionsType advices = new AdviceExpressionsType(); + AdviceExpressionType advice = new AdviceExpressionType(); + advice.setAdviceId("BRMSPARAMID"); + advice.setAppliesTo(EffectType.PERMIT); + // For Configuration + AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); + assignment1.setAttributeId("type"); + assignment1.setCategory(CATEGORY_RESOURCE); + assignment1.setIssuer(""); + AttributeValueType configNameAttributeValue = new AttributeValueType(); + configNameAttributeValue.setDataType(STRING_DATATYPE); + configNameAttributeValue.getContent().add("Configuration"); + assignment1.setExpression(new ObjectFactory() + .createAttributeValue(configNameAttributeValue)); + advice.getAttributeAssignmentExpression().add(assignment1); + + // For Config file Url if configurations are provided. + // URL ID Assignment + AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); + assignment2.setAttributeId("URLID"); + assignment2.setCategory(CATEGORY_RESOURCE); + assignment2.setIssuer(""); + AttributeValueType AttributeValue = new AttributeValueType(); + AttributeValue.setDataType(URI_DATATYPE); + + String content = CONFIG_URL + "/Config/"+ getConfigFile(policyName); + + AttributeValue.getContent().add(content); + assignment2.setExpression(new ObjectFactory() + .createAttributeValue(AttributeValue)); + advice.getAttributeAssignmentExpression().add(assignment2); + + // Policy Name Assignment + AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); + assignment3.setAttributeId("PolicyName"); + assignment3.setCategory(CATEGORY_RESOURCE); + assignment3.setIssuer(""); + AttributeValueType attributeValue3 = new AttributeValueType(); + attributeValue3.setDataType(STRING_DATATYPE); + fileName = FilenameUtils.removeExtension(fileName); + fileName = fileName + ".xml"; + String name = fileName.substring(fileName.lastIndexOf("\\") + 1, + fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf("/") + 1, + fileName.length()); + } + attributeValue3.getContent().add(name); + assignment3.setExpression(new ObjectFactory() + .createAttributeValue(attributeValue3)); + advice.getAttributeAssignmentExpression().add(assignment3); + + // Version Number Assignment + AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); + assignment4.setAttributeId("VersionNumber"); + assignment4.setCategory(CATEGORY_RESOURCE); + assignment4.setIssuer(""); + AttributeValueType configNameAttributeValue4 = new AttributeValueType(); + configNameAttributeValue4.setDataType(STRING_DATATYPE); + configNameAttributeValue4.getContent().add(Integer.toString(version)); + assignment4.setExpression(new ObjectFactory() + .createAttributeValue(configNameAttributeValue4)); + advice.getAttributeAssignmentExpression().add(assignment4); + + // Onap Name Assignment + AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); + assignment5.setAttributeId("matching:" + ONAPID); + assignment5.setCategory(CATEGORY_RESOURCE); + assignment5.setIssuer(""); + AttributeValueType configNameAttributeValue5 = new AttributeValueType(); + configNameAttributeValue5.setDataType(STRING_DATATYPE); + configNameAttributeValue5.getContent().add(policyAdapter.getOnapName()); + assignment5.setExpression(new ObjectFactory() + .createAttributeValue(configNameAttributeValue5)); + advice.getAttributeAssignmentExpression().add(assignment5); + + + //Config Name Assignment + AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); + assignment6.setAttributeId("matching:" +CONFIGID); + assignment6.setCategory(CATEGORY_RESOURCE); + assignment6.setIssuer(""); + AttributeValueType configNameAttributeValue6 = new AttributeValueType(); + configNameAttributeValue6.setDataType(STRING_DATATYPE); + configNameAttributeValue6.getContent().add(policyAdapter.getConfigName()); + assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); + advice.getAttributeAssignmentExpression().add(assignment6); + // Adding Controller Information. + if(policyAdapter.getBrmsController()!=null){ + BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); + advice.getAttributeAssignmentExpression().add( + createResponseAttributes("controller:"+ policyAdapter.getBrmsController(), + brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController())); + } + + // Adding Dependencies. + if(policyAdapter.getBrmsDependency()!=null){ + BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); + ArrayList dependencies = new ArrayList<>(); + StringBuilder key = new StringBuilder(); + for(String dependencyName: policyAdapter.getBrmsDependency()){ + dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency()); + key.append(dependencyName + ","); + } + advice.getAttributeAssignmentExpression().add( + createResponseAttributes("dependencies:"+key.toString(), dependencies.toString())); + } + + // Dynamic Field Config Attributes. + Map dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes(); + for (String keyField : dynamicFieldConfigAttributes.keySet()) { + advice.getAttributeAssignmentExpression().add(createResponseAttributes("key:"+keyField, dynamicFieldConfigAttributes.get(keyField))); + } + + //Risk Attributes + AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); + assignment8.setAttributeId("RiskType"); + assignment8.setCategory(CATEGORY_RESOURCE); + assignment8.setIssuer(""); + + AttributeValueType configNameAttributeValue8 = new AttributeValueType(); + configNameAttributeValue8.setDataType(STRING_DATATYPE); + configNameAttributeValue8.getContent().add(policyAdapter.getRiskType()); + assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8)); + + advice.getAttributeAssignmentExpression().add(assignment8); + + AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); + assignment9.setAttributeId("RiskLevel"); + assignment9.setCategory(CATEGORY_RESOURCE); + assignment9.setIssuer(""); + + AttributeValueType configNameAttributeValue9 = new AttributeValueType(); + configNameAttributeValue9.setDataType(STRING_DATATYPE); + configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel()); + assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); + + advice.getAttributeAssignmentExpression().add(assignment9); + + AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); + assignment10.setAttributeId("guard"); + assignment10.setCategory(CATEGORY_RESOURCE); + assignment10.setIssuer(""); + + AttributeValueType configNameAttributeValue10 = new AttributeValueType(); + configNameAttributeValue10.setDataType(STRING_DATATYPE); + configNameAttributeValue10.getContent().add(policyAdapter.getGuard()); + assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10)); + + advice.getAttributeAssignmentExpression().add(assignment10); + + AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType(); + assignment11.setAttributeId("TTLDate"); + assignment11.setCategory(CATEGORY_RESOURCE); + assignment11.setIssuer(""); + + AttributeValueType configNameAttributeValue11 = new AttributeValueType(); + configNameAttributeValue11.setDataType(STRING_DATATYPE); + configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate()); + assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11)); + + advice.getAttributeAssignmentExpression().add(assignment11); + + advices.getAdviceExpression().add(advice); + return advices; + } + + @Override + public Object getCorrectPolicyDataObject() { + return policyAdapter.getData(); + } + + private AttributeAssignmentExpressionType createResponseAttributes(String key, String value){ + AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); + assignment7.setAttributeId(key); + assignment7.setCategory(CATEGORY_RESOURCE); + assignment7.setIssuer(""); + AttributeValueType configNameAttributeValue7 = new AttributeValueType(); + configNameAttributeValue7.setDataType(STRING_DATATYPE); + configNameAttributeValue7.getContent().add(value); + assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); + return assignment7; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java new file mode 100644 index 000000000..4bcb05788 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java @@ -0,0 +1,489 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; +import org.onap.policy.rest.adapter.PolicyRestAdapter; + +import com.att.research.xacml.std.IdentifierImpl; + +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.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +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; + + +public class CreateBrmsRawPolicy extends Policy { + + public CreateBrmsRawPolicy() { + super(); + } + + public CreateBrmsRawPolicy(PolicyRestAdapter policyAdapter) { + this.policyAdapter = policyAdapter; + this.policyAdapter.setConfigType(policyAdapter.getConfigType()); + + } + + // Saving the Configurations file at server location for CreateBrmsRawPolicy policy. + protected void saveConfigurations(String policyName, String jsonBody) { + try { + if (policyName.endsWith(".xml")) { + policyName = policyName.substring(0, + policyName.lastIndexOf(".xml")); + } + PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt"); + out.println(jsonBody); + out.close(); + + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsRawPolicy", "Exception saving configurations file"); + } + } + + // Utility to read json data from the existing file to a string + static String readFile(String path, Charset encoding) throws IOException { + + byte[] encoded = Files.readAllBytes(Paths.get(path)); + return new String(encoded, encoding); + + } + + // Here we are adding the extension for the configurations file based on the + // config type selection for saving. + private String getConfigFile(String filename) { + filename = FilenameUtils.removeExtension(filename); + if (filename.endsWith(".txt")) { + filename = filename.substring(0, filename.length() - 3); + } + + filename = filename + ".txt"; + return filename; + } + + // Validations for Config form + public boolean validateConfigForm() { + + // Validating mandatory Fields. + isValidForm = true; + return isValidForm; + + } + + @Override + public Map savePolicies() throws Exception { + + Map successMap = new HashMap<>(); + if(isPolicyExists()){ + successMap.put("EXISTS", "This Policy already exist on the PAP"); + return successMap; + } + + if (!isPreparedToSave()) { + prepareToSave(); + } + // Until here we prepared the data and here calling the method to create + // xml. + Path newPolicyPath = null; + newPolicyPath = Paths.get(policyAdapter.getNewFileName()); + + successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); + if (successMap == null) { + successMap = new HashMap<>(); + PolicyLogger.error("Failed to Update the Database Dictionary Tables."); + successMap.put("error", "DB UPDATE"); + } + + return successMap; + } + + // This is the method for preparing the policy for saving. We have broken it + // out + // separately because the fully configured policy is used for multiple + // things + @Override + public boolean prepareToSave() throws Exception { + + if (isPreparedToSave()) { + // we have already done this + return true; + } + + int version = 0; + String policyID = policyAdapter.getPolicyID(); + version = policyAdapter.getHighestVersion(); + + // Create the Instance for pojo, PolicyType object is used in + // marshalling. + if (policyAdapter.getPolicyType().equals("Config")) { + PolicyType policyConfig = new PolicyType(); + + policyConfig.setVersion(Integer.toString(version)); + policyConfig.setPolicyId(policyID); + policyConfig.setTarget(new TargetType()); + policyAdapter.setData(policyConfig); + } + + policyName = policyAdapter.getNewFileName(); + + if (policyAdapter.getData() != null) { + //String jsonBody = policyAdapter.getJsonBody(); + String configBody=policyAdapter.getConfigBodyData(); + saveConfigurations(policyName, configBody); + + // Make sure the filename ends with an extension + if (policyName.endsWith(".xml") == false) { + policyName = policyName + ".xml"; + } + + PolicyType configPolicy = (PolicyType) policyAdapter.getData(); + + configPolicy.setDescription(policyAdapter.getPolicyDescription()); + + configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); + + AllOfType allOfOne = new AllOfType(); + String fileName = policyAdapter.getNewFileName(); + String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf("/") + 1, + fileName.length()); + } + allOfOne.getMatch().add(createMatch("PolicyName", name)); + + + AllOfType allOf = new AllOfType(); + + // Match for ONAPName + allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); + allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName())); + // Match for riskType + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); + // Match for riskLevel + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + // Match for riskguard + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); + // Match for ttlDate + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + AnyOfType anyOf = new AnyOfType(); + anyOf.getAllOf().add(allOfOne); + anyOf.getAllOf().add(allOf); + + TargetType target = new TargetType(); + ((TargetType) target).getAnyOf().add(anyOf); + + // Adding the target to the policy element + configPolicy.setTarget((TargetType) target); + + RuleType rule = new RuleType(); + rule.setRuleId(policyAdapter.getRuleID()); + + rule.setEffect(EffectType.PERMIT); + + // Create Target in Rule + AllOfType allOfInRule = new AllOfType(); + + // Creating match for ACCESS in rule target + MatchType accessMatch = new MatchType(); + AttributeValueType accessAttributeValue = new AttributeValueType(); + accessAttributeValue.setDataType(STRING_DATATYPE); + accessAttributeValue.getContent().add("ACCESS"); + accessMatch.setAttributeValue(accessAttributeValue); + AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); + URI accessURI = null; + try { + accessURI = new URI(ACTION_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy", "Exception creating ACCESS URI"); + } + accessAttributeDesignator.setCategory(CATEGORY_ACTION); + accessAttributeDesignator.setDataType(STRING_DATATYPE); + accessAttributeDesignator.setAttributeId(new IdentifierImpl( + accessURI).stringValue()); + accessMatch.setAttributeDesignator(accessAttributeDesignator); + accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + // Creating Config Match in rule Target + MatchType configMatch = new MatchType(); + AttributeValueType configAttributeValue = new AttributeValueType(); + configAttributeValue.setDataType(STRING_DATATYPE); + + configAttributeValue.getContent().add("Config"); + + configMatch.setAttributeValue(configAttributeValue); + AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType(); + URI configURI = null; + try { + configURI = new URI(RESOURCE_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy", "Exception creating Config URI"); + } + + configAttributeDesignator.setCategory(CATEGORY_RESOURCE); + configAttributeDesignator.setDataType(STRING_DATATYPE); + configAttributeDesignator.setAttributeId(new IdentifierImpl( + configURI).stringValue()); + configMatch.setAttributeDesignator(configAttributeDesignator); + configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + allOfInRule.getMatch().add(accessMatch); + allOfInRule.getMatch().add(configMatch); + + AnyOfType anyOfInRule = new AnyOfType(); + anyOfInRule.getAllOf().add(allOfInRule); + + TargetType targetInRule = new TargetType(); + targetInRule.getAnyOf().add(anyOfInRule); + + rule.setTarget(targetInRule); + rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); + + configPolicy + .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() + .add(rule); + policyAdapter.setPolicyData(configPolicy); + + } else { + PolicyLogger.error("Unsupported data object." + + policyAdapter.getData().getClass().getCanonicalName()); + } + setPreparedToSave(true); + return true; + } + + // Data required for Advice part is setting here. + private AdviceExpressionsType getAdviceExpressions(int version, + String fileName) { + + // Policy Config ID Assignment + AdviceExpressionsType advices = new AdviceExpressionsType(); + AdviceExpressionType advice = new AdviceExpressionType(); + advice.setAdviceId("BRMSRAWID"); + advice.setAppliesTo(EffectType.PERMIT); + // For Configuration + AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); + assignment1.setAttributeId("type"); + assignment1.setCategory(CATEGORY_RESOURCE); + assignment1.setIssuer(""); + AttributeValueType configNameAttributeValue = new AttributeValueType(); + configNameAttributeValue.setDataType(STRING_DATATYPE); + configNameAttributeValue.getContent().add("Configuration"); + assignment1.setExpression(new ObjectFactory() + .createAttributeValue(configNameAttributeValue)); + advice.getAttributeAssignmentExpression().add(assignment1); + + // For Config file Url if configurations are provided. + // URL ID Assignment + AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); + assignment2.setAttributeId("URLID"); + assignment2.setCategory(CATEGORY_RESOURCE); + assignment2.setIssuer(""); + AttributeValueType AttributeValue = new AttributeValueType(); + AttributeValue.setDataType(URI_DATATYPE); + + String content = CONFIG_URL + "/Config/" + getConfigFile(policyName); + + AttributeValue.getContent().add(content); + assignment2.setExpression(new ObjectFactory() + .createAttributeValue(AttributeValue)); + advice.getAttributeAssignmentExpression().add(assignment2); + + // Policy Name Assignment + AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); + assignment3.setAttributeId("PolicyName"); + assignment3.setCategory(CATEGORY_RESOURCE); + assignment3.setIssuer(""); + AttributeValueType attributeValue3 = new AttributeValueType(); + attributeValue3.setDataType(STRING_DATATYPE); + fileName = FilenameUtils.removeExtension(fileName); + fileName = fileName + ".xml"; + System.out.println(fileName); + String name = fileName.substring(fileName.lastIndexOf("\\") + 1, + fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf("/") + 1, + fileName.length()); + } + System.out.println(name); + attributeValue3.getContent().add(name); + assignment3.setExpression(new ObjectFactory() + .createAttributeValue(attributeValue3)); + advice.getAttributeAssignmentExpression().add(assignment3); + + // Version Number Assignment + AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); + assignment4.setAttributeId("VersionNumber"); + assignment4.setCategory(CATEGORY_RESOURCE); + assignment4.setIssuer(""); + AttributeValueType configNameAttributeValue4 = new AttributeValueType(); + configNameAttributeValue4.setDataType(STRING_DATATYPE); + configNameAttributeValue4.getContent().add(Integer.toString(version)); + assignment4.setExpression(new ObjectFactory() + .createAttributeValue(configNameAttributeValue4)); + advice.getAttributeAssignmentExpression().add(assignment4); + + // Onap Name Assignment + AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); + assignment5.setAttributeId("matching:" + ONAPID); + assignment5.setCategory(CATEGORY_RESOURCE); + assignment5.setIssuer(""); + AttributeValueType configNameAttributeValue5 = new AttributeValueType(); + configNameAttributeValue5.setDataType(STRING_DATATYPE); + configNameAttributeValue5.getContent().add(policyAdapter.getOnapName()); + assignment5.setExpression(new ObjectFactory() + .createAttributeValue(configNameAttributeValue5)); + advice.getAttributeAssignmentExpression().add(assignment5); + + + //Config Name Assignment + AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); + assignment6.setAttributeId("matching:" + CONFIGID); + assignment6.setCategory(CATEGORY_RESOURCE); + assignment6.setIssuer(""); + AttributeValueType configNameAttributeValue6 = new AttributeValueType(); + configNameAttributeValue6.setDataType(STRING_DATATYPE); + configNameAttributeValue6.getContent().add(policyAdapter.getConfigName()); + assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); + advice.getAttributeAssignmentExpression().add(assignment6); + + // Adding Controller Information. + if(policyAdapter.getBrmsController()!=null){ + BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); + advice.getAttributeAssignmentExpression().add( + createResponseAttributes("controller:"+ policyAdapter.getBrmsController(), + brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController())); + } + + // Adding Dependencies. + if(policyAdapter.getBrmsDependency()!=null){ + BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); + ArrayList dependencies = new ArrayList<>(); + StringBuilder key = new StringBuilder(); + for(String dependencyName: policyAdapter.getBrmsDependency()){ + dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency()); + key.append(dependencyName + ","); + } + advice.getAttributeAssignmentExpression().add( + createResponseAttributes("dependencies:"+key.toString(), dependencies.toString())); + } + + // Dynamic Field Config Attributes. + Map dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes(); + for (String keyField : dynamicFieldConfigAttributes.keySet()) { + advice.getAttributeAssignmentExpression().add(createResponseAttributes("key:"+keyField, dynamicFieldConfigAttributes.get(keyField))); + } + + //Risk Attributes + AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); + assignment8.setAttributeId("RiskType"); + assignment8.setCategory(CATEGORY_RESOURCE); + assignment8.setIssuer(""); + + AttributeValueType configNameAttributeValue8 = new AttributeValueType(); + configNameAttributeValue8.setDataType(STRING_DATATYPE); + configNameAttributeValue8.getContent().add(policyAdapter.getRiskType()); + assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8)); + + advice.getAttributeAssignmentExpression().add(assignment8); + + AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); + assignment9.setAttributeId("RiskLevel"); + assignment9.setCategory(CATEGORY_RESOURCE); + assignment9.setIssuer(""); + + AttributeValueType configNameAttributeValue9 = new AttributeValueType(); + configNameAttributeValue9.setDataType(STRING_DATATYPE); + configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel()); + assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); + + advice.getAttributeAssignmentExpression().add(assignment9); + + AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); + assignment10.setAttributeId("guard"); + assignment10.setCategory(CATEGORY_RESOURCE); + assignment10.setIssuer(""); + + AttributeValueType configNameAttributeValue10 = new AttributeValueType(); + configNameAttributeValue10.setDataType(STRING_DATATYPE); + configNameAttributeValue10.getContent().add(policyAdapter.getGuard()); + assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10)); + + advice.getAttributeAssignmentExpression().add(assignment10); + + AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType(); + assignment11.setAttributeId("TTLDate"); + assignment11.setCategory(CATEGORY_RESOURCE); + assignment11.setIssuer(""); + + AttributeValueType configNameAttributeValue11 = new AttributeValueType(); + configNameAttributeValue11.setDataType(STRING_DATATYPE); + configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate()); + assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11)); + + advice.getAttributeAssignmentExpression().add(assignment11); + + advices.getAdviceExpression().add(advice); + return advices; + } + + @Override + public Object getCorrectPolicyDataObject() { + return policyAdapter.getData(); + } + + private AttributeAssignmentExpressionType createResponseAttributes(String key, String value){ + AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); + assignment7.setAttributeId(key); + assignment7.setCategory(CATEGORY_RESOURCE); + assignment7.setIssuer(""); + AttributeValueType configNameAttributeValue7 = new AttributeValueType(); + configNameAttributeValue7.setDataType(STRING_DATATYPE); + configNameAttributeValue7.getContent().add(value); + assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); + return assignment7; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java new file mode 100644 index 000000000..ada704465 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java @@ -0,0 +1,412 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + + +import java.io.File; +import java.io.PrintWriter; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; + +import com.att.research.xacml.std.IdentifierImpl; + +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.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +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; + +public class CreateClosedLoopPerformanceMetrics extends Policy { + + private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPerformanceMetrics.class); + + public CreateClosedLoopPerformanceMetrics() { + super(); + } + + public CreateClosedLoopPerformanceMetrics(PolicyRestAdapter policyAdapter){ + this.policyAdapter = policyAdapter; + } + + //save configuration of the policy based on the policyname + private void saveConfigurations(String policyName, String jsonBody) { + try { + String body = null; + try { + body = jsonBody; + } catch (Exception e) { + LOGGER.error("Exception Occured"+e); + } + if(policyName.endsWith(".xml")){ + policyName = policyName.substring(0, policyName.lastIndexOf(".xml")); + } + PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + "."+ policyName +".json"); + out.println(body); + policyAdapter.setJsonBody(body); + policyAdapter.setConfigBodyData(body); + out.close(); + + } catch (Exception e) { + LOGGER.error("Exception Occured"+e); + } + } + + //getting the policy name and setting to configuration on adding .json + private String getConfigFile(String filename) { + filename = FilenameUtils.removeExtension(filename); + if (filename.endsWith(".xml")) { + filename = filename.substring(0, filename.length() - 4); + } + filename = filename +".json"; + return filename; + } + + @Override + public Map savePolicies() throws Exception { + + Map successMap = new HashMap<>(); + if(isPolicyExists()){ + successMap.put("EXISTS", "This Policy already exist on the PAP"); + return successMap; + } + + if(!isPreparedToSave()){ + //Prep and configure the policy for saving + prepareToSave(); + } + + // Until here we prepared the data and here calling the method to create xml. + Path newPolicyPath = null; + newPolicyPath = Paths.get(policyAdapter.getNewFileName()); + + successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + + return successMap; + } + + //This is the method for preparing the policy for saving. We have broken it out + //separately because the fully configured policy is used for multiple things + @Override + public boolean prepareToSave() throws Exception{ + + if(isPreparedToSave()){ + //we have already done this + return true; + } + + int version = 0; + String policyID = policyAdapter.getPolicyID(); + version = policyAdapter.getHighestVersion(); + + // Create the Instance for pojo, PolicyType object is used in marshalling. + if (policyAdapter.getPolicyType().equals("Config")) { + PolicyType policyConfig = new PolicyType(); + + policyConfig.setVersion(Integer.toString(version)); + policyConfig.setPolicyId(policyID); + policyConfig.setTarget(new TargetType()); + policyAdapter.setData(policyConfig); + } + policyName = policyAdapter.getNewFileName(); + if (policyAdapter.getData() != null) { + // Save the Configurations file with the policy name with extention based on selection. + String jsonBody = policyAdapter.getJsonBody(); + saveConfigurations(policyName, jsonBody); + + // Make sure the filename ends with an extension + if (policyName.endsWith(".xml") == false) { + policyName = policyName + ".xml"; + } + + + PolicyType configPolicy = (PolicyType) policyAdapter.getData(); + + configPolicy.setDescription(policyAdapter.getPolicyDescription()); + + configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); + + AllOfType allOfOne = new AllOfType(); + String fileName = policyAdapter.getNewFileName(); + String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); + } + allOfOne.getMatch().add(createMatch("PolicyName", name)); + AllOfType allOf = new AllOfType(); + + // Adding the matches to AllOfType element Match for Onap + allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); + // Match for riskType + allOf.getMatch().add( + createDynamicMatch("RiskType", policyAdapter.getRiskType())); + // Match for riskLevel + allOf.getMatch().add( + createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + // Match for riskguard + allOf.getMatch().add( + createDynamicMatch("guard", policyAdapter.getGuard())); + // Match for ttlDate + allOf.getMatch().add( + createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + // Match for ServiceType + allOf.getMatch().add(createMatch("ServiceType", policyAdapter.getServiceType())); + + AnyOfType anyOf = new AnyOfType(); + anyOf.getAllOf().add(allOfOne); + anyOf.getAllOf().add(allOf); + + TargetType target = new TargetType(); + ((TargetType) target).getAnyOf().add(anyOf); + + // Adding the target to the policy element + configPolicy.setTarget((TargetType) target); + + RuleType rule = new RuleType(); + rule.setRuleId(policyAdapter.getRuleID()); + + rule.setEffect(EffectType.PERMIT); + + // Create Target in Rule + AllOfType allOfInRule = new AllOfType(); + + // Creating match for ACCESS in rule target + MatchType accessMatch = new MatchType(); + AttributeValueType accessAttributeValue = new AttributeValueType(); + accessAttributeValue.setDataType(STRING_DATATYPE); + accessAttributeValue.getContent().add("ACCESS"); + accessMatch.setAttributeValue(accessAttributeValue); + AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); + URI accessURI = null; + try { + accessURI = new URI(ACTION_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating ACCESS URI"); + } + accessAttributeDesignator.setCategory(CATEGORY_ACTION); + accessAttributeDesignator.setDataType(STRING_DATATYPE); + accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); + accessMatch.setAttributeDesignator(accessAttributeDesignator); + accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + // Creating Config Match in rule Target + MatchType configMatch = new MatchType(); + AttributeValueType configAttributeValue = new AttributeValueType(); + configAttributeValue.setDataType(STRING_DATATYPE); + configAttributeValue.getContent().add("Config"); + configMatch.setAttributeValue(configAttributeValue); + AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType(); + URI configURI = null; + try { + configURI = new URI(RESOURCE_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating Config URI"); + } + configAttributeDesignator.setCategory(CATEGORY_RESOURCE); + configAttributeDesignator.setDataType(STRING_DATATYPE); + configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue()); + configMatch.setAttributeDesignator(configAttributeDesignator); + configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + allOfInRule.getMatch().add(accessMatch); + allOfInRule.getMatch().add(configMatch); + + AnyOfType anyOfInRule = new AnyOfType(); + anyOfInRule.getAllOf().add(allOfInRule); + + TargetType targetInRule = new TargetType(); + targetInRule.getAnyOf().add(anyOfInRule); + + rule.setTarget(targetInRule); + rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); + + configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); + policyAdapter.setPolicyData(configPolicy); + + } else { + PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); + } + setPreparedToSave(true); + return true; + } + + // Data required for Advice part is setting here. + @SuppressWarnings("static-access") + private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { + AdviceExpressionsType advices = new AdviceExpressionsType(); + AdviceExpressionType advice = new AdviceExpressionType(); + advice.setAdviceId("PMID"); + advice.setAppliesTo(EffectType.PERMIT); + // For Configuration + AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); + assignment1.setAttributeId("type"); + assignment1.setCategory(CATEGORY_RESOURCE); + assignment1.setIssuer(""); + + AttributeValueType configNameAttributeValue = new AttributeValueType(); + configNameAttributeValue.setDataType(STRING_DATATYPE); + configNameAttributeValue.getContent().add("Configuration"); + assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); + + advice.getAttributeAssignmentExpression().add(assignment1); + // For Config file Url if configurations are provided. + AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); + assignment2.setAttributeId("URLID"); + assignment2.setCategory(CATEGORY_RESOURCE); + assignment2.setIssuer(""); + + AttributeValueType AttributeValue = new AttributeValueType(); + AttributeValue.setDataType(URI_DATATYPE); + String content = CONFIG_URL +"/Config/"+ getConfigFile(policyName); + AttributeValue.getContent().add(content); + assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); + + advice.getAttributeAssignmentExpression().add(assignment2); + AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); + assignment3.setAttributeId("PolicyName"); + assignment3.setCategory(CATEGORY_RESOURCE); + assignment3.setIssuer(""); + + AttributeValueType attributeValue3 = new AttributeValueType(); + attributeValue3.setDataType(STRING_DATATYPE); + fileName = FilenameUtils.removeExtension(fileName); + fileName = fileName + ".xml"; + String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); + } + attributeValue3.getContent().add(name); + assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); + advice.getAttributeAssignmentExpression().add(assignment3); + + AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); + assignment4.setAttributeId("VersionNumber"); + assignment4.setCategory(CATEGORY_RESOURCE); + assignment4.setIssuer(""); + + AttributeValueType configNameAttributeValue4 = new AttributeValueType(); + configNameAttributeValue4.setDataType(STRING_DATATYPE); + configNameAttributeValue4.getContent().add(Integer.toString(version)); + assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); + + advice.getAttributeAssignmentExpression().add(assignment4); + + AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); + assignment5.setAttributeId("matching:" + this.ONAPID); + assignment5.setCategory(CATEGORY_RESOURCE); + assignment5.setIssuer(""); + + AttributeValueType configNameAttributeValue5 = new AttributeValueType(); + configNameAttributeValue5.setDataType(STRING_DATATYPE); + configNameAttributeValue5.getContent().add(policyAdapter.getOnapName()); + assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); + + advice.getAttributeAssignmentExpression().add(assignment5); + + AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); + assignment6.setAttributeId("matching:" + this.CLOSEDLOOPID); + assignment6.setCategory(CATEGORY_RESOURCE); + assignment6.setIssuer(""); + + AttributeValueType configNameAttributeValue6 = new AttributeValueType(); + configNameAttributeValue6.setDataType(STRING_DATATYPE); + configNameAttributeValue6.getContent().add(policyAdapter.getServiceType()); + assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); + + advice.getAttributeAssignmentExpression().add(assignment6); + + //Risk Attributes + AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); + assignment7.setAttributeId("RiskType"); + assignment7.setCategory(CATEGORY_RESOURCE); + assignment7.setIssuer(""); + + AttributeValueType configNameAttributeValue7 = new AttributeValueType(); + configNameAttributeValue7.setDataType(STRING_DATATYPE); + configNameAttributeValue7.getContent().add(policyAdapter.getRiskType()); + assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); + + advice.getAttributeAssignmentExpression().add(assignment7); + + AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); + assignment8.setAttributeId("RiskLevel"); + assignment8.setCategory(CATEGORY_RESOURCE); + assignment8.setIssuer(""); + + AttributeValueType configNameAttributeValue8 = new AttributeValueType(); + configNameAttributeValue8.setDataType(STRING_DATATYPE); + configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel()); + assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8)); + + advice.getAttributeAssignmentExpression().add(assignment8); + + AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); + assignment9.setAttributeId("guard"); + assignment9.setCategory(CATEGORY_RESOURCE); + assignment9.setIssuer(""); + + AttributeValueType configNameAttributeValue9 = new AttributeValueType(); + configNameAttributeValue9.setDataType(STRING_DATATYPE); + configNameAttributeValue9.getContent().add(policyAdapter.getGuard()); + assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); + + advice.getAttributeAssignmentExpression().add(assignment9); + + AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); + assignment10.setAttributeId("TTLDate"); + assignment10.setCategory(CATEGORY_RESOURCE); + assignment10.setIssuer(""); + + AttributeValueType configNameAttributeValue10 = new AttributeValueType(); + configNameAttributeValue10.setDataType(STRING_DATATYPE); + configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate()); + assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10)); + + advice.getAttributeAssignmentExpression().add(assignment10); + + advices.getAdviceExpression().add(advice); + return advices; + } + + @Override + public Object getCorrectPolicyDataObject() { + return policyAdapter.getPolicyData(); + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java new file mode 100644 index 000000000..fd9e49c7e --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java @@ -0,0 +1,248 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang.StringUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.rest.jpa.MicroServiceModels; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.rest.util.MSAttributeObject; +import org.onap.policy.rest.util.MSModelUtils; +import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE; + +public class CreateNewMicroServiceModel { + private static final Logger logger = FlexLogger.getLogger(CreateNewMicroServiceModel.class); + private MicroServiceModels newModel = null; + private HashMap classMap = new HashMap<>(); + + + MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); + + public CreateNewMicroServiceModel(String fileName, String serviceName, String string, String version) { + super(); + } + + public CreateNewMicroServiceModel(String importFile, String modelName, String description, String version, String randomID) { + + this.newModel = new MicroServiceModels(); + this.newModel.setVersion(version); + this.newModel.setModelName(modelName); + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId("API"); + this.newModel.setUserCreatedBy(userInfo); + String cleanUpFile = null; + + HashMap tempMap = new HashMap<>(); + //Need to delete the file + if (importFile.contains(".zip")){ + extractFolder(randomID + ".zip"); + File directory = new File("ExtractDir" + File.separator + randomID); + List fileList = listModelFiles(directory.toString()); + //get all the files from a director + for (File file : fileList){ + if (file.isFile()){ + tempMap = utils.processEpackage(file.getAbsolutePath(), MODEL_TYPE.XMI); + classMap.putAll(tempMap); + } + } + cleanUpFile = "ExtractDir" + File.separator + randomID + ".zip"; + try { + FileUtils.deleteDirectory(new File("ExtractDir" + File.separator + randomID)); + FileUtils.deleteDirectory(new File(randomID)); + File deleteFile = new File(cleanUpFile); + FileUtils.forceDelete(deleteFile); + } catch (IOException e) { + logger.error("Failed to unzip model file " + randomID); + } + }else { + tempMap = utils.processEpackage("ExtractDir" + File.separator + randomID+".xmi", MODEL_TYPE.XMI); + classMap.putAll(tempMap); + cleanUpFile = "ExtractDir" + File.separator + randomID+".xmi"; + File deleteFile = new File(cleanUpFile); + deleteFile.delete(); + } + } + + 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()) { + resultList.addAll(listModelFiles(file.getAbsolutePath())); + } + } + return resultList; + } + + @SuppressWarnings("rawtypes") + private void extractFolder(String zipFile) { + int BUFFER = 2048; + File file = new File(zipFile); + + ZipFile zip = null; + try { + zip = new ZipFile("ExtractDir" + File.separator +file); + String newPath = zipFile.substring(0, zipFile.length() - 4); + 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("ExtractDir" + File.separator + newPath + 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 + e); + }finally{ + if(zip != null){ + try { + zip.close(); + } catch (Exception e) { + logger.error("Exception Occured while closing the zip file"+e); + } + } + } + } + + public Map addValuesToNewModel() { + + Map successMap = new HashMap<>(); + MSAttributeObject mainClass = null; + ArrayList dependency = null; + String subAttribute = null; + + if (!classMap.containsKey(this.newModel.getModelName())){ + logger.error("Model Provided does not contain the service name provided in request. Unable to import new model"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", "Unable to pull out required values, file missing service name provided in request"); + successMap.put("error", "MISSING"); + return successMap; + } + mainClass = classMap.get(this.newModel.getModelName()); + String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""}); + this.newModel.setDependency(dependTemp); + if (!this.newModel.getDependency().equals("")){ + dependency = new ArrayList(Arrays.asList(dependTemp.split(","))); + dependency = utils.getFullDependencyList(dependency, classMap); + if (!dependency.isEmpty()){ + for (String element : dependency){ + MSAttributeObject temp = new MSAttributeObject(); + if (classMap.containsKey(element)){ + temp = classMap.get(element); + mainClass.addAllRefAttribute(temp.getRefAttribute()); + mainClass.addAllAttribute(temp.getAttribute()); + } + } + } + } + subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName()); + + this.newModel.setSub_attributes(subAttribute); + this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", "")); + this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", "")); + this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); + this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); + successMap.put("success", "success"); + return successMap; + + } + + public Map saveImportService(){ + String modelName = this.newModel.getModelName(); + String imported_by = "API"; + String version = this.newModel.getVersion(); + Map successMap = new HashMap<>(); + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); + List result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+version); + if(result.isEmpty()){ + MicroServiceModels model = new MicroServiceModels(); + model.setModelName(modelName); + model.setVersion(version); + model.setAttributes(this.newModel.getAttributes()); + model.setAnnotation(this.newModel.getAnnotation()); + model.setDependency(this.newModel.getDependency()); + model.setDescription(this.newModel.getDescription()); + model.setEnumValues(this.newModel.getEnumValues()); + model.setRef_attributes(this.newModel.getRef_attributes()); + model.setSub_attributes(this.newModel.getSub_attributes()); + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(imported_by); + userInfo.setUserName(imported_by); + model.setUserCreatedBy(userInfo); + dbConnection.save(model); + successMap.put("success", "success"); + }else{ + successMap.put("DBError", "EXISTS"); + logger.error("Import new service failed. Service already exists"); + } + return successMap; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java new file mode 100644 index 000000000..fe9c581e9 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java @@ -0,0 +1,793 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +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.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.persistence.EntityManager; +import javax.persistence.Query; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.controlloop.policy.builder.BuilderException; +import org.onap.policy.controlloop.policy.builder.Results; +import org.onap.policy.controlloop.policy.guard.Constraint; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; +import org.onap.policy.controlloop.policy.guard.Guard; +import org.onap.policy.controlloop.policy.guard.GuardPolicy; +import org.onap.policy.controlloop.policy.guard.MatchParameters; +import org.onap.policy.controlloop.policy.guard.builder.ControlLoopGuardBuilder; +import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.pap.xacml.rest.util.JPAUtils; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.Datatype; +import org.onap.policy.rest.jpa.DecisionSettings; +import org.onap.policy.rest.jpa.FunctionDefinition; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine; +import org.onap.policy.xacml.util.XACMLPolicyScanner; + +import com.att.research.xacml.std.IdentifierImpl; + +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.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.ObjectFactory; +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; + +public class DecisionPolicy extends Policy { + + private static final Logger LOGGER = FlexLogger.getLogger(DecisionPolicy.class); + + public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not"; + private static final String AAFPROVIDER = "AAF"; + public static final String GUARD_YAML = "GUARD_YAML"; + public static final String GUARD_BL_YAML = "GUARD_BL_YAML"; + public static final String RAINY_DAY = "Rainy_Day"; + private static final String XACML_GUARD_TEMPLATE = "Decision_GuardPolicyTemplate.xml"; + private static final String XACML_BLGUARD_TEMPLATE = "Decision_GuardBLPolicyTemplate.xml"; + + private static final String ONAPNAME = "ONAPName"; + private static final String POLICY_NAME = "PolicyName"; + private static final String DESCRIPTION = "description"; + + + List dynamicLabelRuleAlgorithms = new LinkedList<>(); + List dynamicFieldComboRuleAlgorithms = new LinkedList<>(); + List dynamicFieldOneRuleAlgorithms = new LinkedList<>(); + List dynamicFieldTwoRuleAlgorithms = new LinkedList<>(); + List dataTypeList = new LinkedList<>(); + + protected Map dropDownMap = new HashMap<>(); + + + public DecisionPolicy() { + super(); + } + + public DecisionPolicy(PolicyRestAdapter policyAdapter){ + this.policyAdapter = policyAdapter; + } + + @Override + public Map savePolicies() throws Exception { + + Map successMap = new HashMap<>(); + if(isPolicyExists()){ + successMap.put("EXISTS", "This Policy already exist on the PAP"); + return successMap; + } + + if(!isPreparedToSave()){ + //Prep and configure the policy for saving + prepareToSave(); + } + + // Until here we prepared the data and here calling the method to create xml. + Path newPolicyPath = null; + newPolicyPath = Paths.get(policyAdapter.getNewFileName()); + + successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + return successMap; + } + + //This is the method for preparing the policy for saving. We have broken it out + //separately because the fully configured policy is used for multiple things + @Override + public boolean prepareToSave() throws Exception{ + + if(isPreparedToSave()){ + //we have already done this + return true; + } + + int version = 0; + String policyID = policyAdapter.getPolicyID(); + version = policyAdapter.getHighestVersion(); + + // Create the Instance for pojo, PolicyType object is used in marshalling. + if ("Decision".equals(policyAdapter.getPolicyType())) { + PolicyType policyConfig = new PolicyType(); + + policyConfig.setVersion(Integer.toString(version)); + policyConfig.setPolicyId(policyID); + policyConfig.setTarget(new TargetType()); + policyAdapter.setData(policyConfig); + } + policyName = policyAdapter.getNewFileName(); + + if(policyAdapter.getRuleProvider().equals(GUARD_YAML) || policyAdapter.getRuleProvider().equals(GUARD_BL_YAML)){ + Map yamlParams = new HashMap<>(); + yamlParams.put(DESCRIPTION, (policyAdapter.getPolicyDescription()!=null)? policyAdapter.getPolicyDescription(): "YAML Guard Policy"); + String fileName = policyAdapter.getNewFileName(); + String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length()); + if ((name == null) || ("".equals(name))) { + name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length()); + } + yamlParams.put(POLICY_NAME, name); + yamlParams.put(ONAPNAME, policyAdapter.getOnapName()); + Map params = policyAdapter.getDynamicFieldConfigAttributes(); + yamlParams.putAll(params); + // Call YAML to XACML + PolicyType decisionPolicy = getGuardPolicy(yamlParams, policyAdapter.getRuleProvider()); + decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); + decisionPolicy.setVersion(Integer.toString(version)); + policyAdapter.setPolicyData(decisionPolicy); + policyAdapter.setData(decisionPolicy); + }else if (policyAdapter.getData() != null) { + PolicyType decisionPolicy = (PolicyType) policyAdapter.getData(); + + decisionPolicy.setDescription(policyAdapter.getPolicyDescription()); + + decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); + AllOfType allOfOne = new AllOfType(); + String fileName = policyAdapter.getNewFileName(); + String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length()); + if ((name == null) || ("".equals(name))) { + name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length()); + } + allOfOne.getMatch().add(createMatch(POLICY_NAME, name)); + + AllOfType allOf = new AllOfType(); + + // Match for Onap + allOf.getMatch().add(createMatch(ONAPNAME, (policyAdapter.getOnapName()))); + + Map dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes(); + if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){ + dynamicFieldComponentAttributes = new HashMap<>(); + } + + // If there is any dynamic field attributes create the matches here + for (String keyField : dynamicFieldComponentAttributes.keySet()) { + String key = keyField; + String value = dynamicFieldComponentAttributes.get(key); + MatchType dynamicMatch = createDynamicMatch(key, value); + allOf.getMatch().add(dynamicMatch); + } + + AnyOfType anyOf = new AnyOfType(); + anyOf.getAllOf().add(allOfOne); + anyOf.getAllOf().add(allOf); + + TargetType target = new TargetType(); + target.getAnyOf().add(anyOf); + decisionPolicy.setTarget(target); + + Map dynamicFieldDecisionSettings = policyAdapter.getDynamicSettingsMap(); + if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){ + dynamicFieldDecisionSettings = new HashMap<>(); + } + + // settings are dynamic so check how many rows are added and add all + for (String keyField : dynamicFieldDecisionSettings.keySet()) { + String key = keyField; + String value = dynamicFieldDecisionSettings.get(key); + String dataType = getDataType(key); + VariableDefinitionType dynamicVariable = createDynamicVariable(key, value, dataType); + decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(dynamicVariable); + } + Map dynamicFieldTreatmentAttributes = policyAdapter.getRainydayMap(); + + if(policyAdapter.getRuleProvider().equals(RAINY_DAY)){ + for(String keyField : dynamicFieldTreatmentAttributes.keySet()) { + String errorcode = keyField; + String treatment = dynamicFieldTreatmentAttributes.get(errorcode); + createRainydayRule(decisionPolicy, errorcode, treatment, true); + } + } else { + createRule(decisionPolicy, true); + createRule(decisionPolicy, false); + } + + } + setPreparedToSave(true); + return true; + } + + public PolicyType getGuardPolicy(Map yamlParams, String ruleProvider) throws BuilderException{ + try { + ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard()); + MatchParameters matchParameters = new MatchParameters(yamlParams.get("actor"), yamlParams.get("recipe")); + matchParameters.setControlLoopName(yamlParams.get("clname")); + if(yamlParams.containsKey("targets")){ + String targetString = yamlParams.get("targets"); + List targets = null; + if(targetString!=null && !targetString.isEmpty()){ + if (targetString.contains(",")){ + targets = Arrays.asList(targetString.split(",")); + } + else{ + targets = new ArrayList<>(); + targets.add(targetString); + } + } + matchParameters.setTargets(targets); + } + GuardPolicy policy1 = new GuardPolicy((policyAdapter.getUuid()!=null? policyAdapter.getUuid(): UUID.randomUUID().toString()) ,yamlParams.get(POLICY_NAME), yamlParams.get(DESCRIPTION), matchParameters); + builder = builder.addGuardPolicy(policy1); + Map activeTimeRange = new HashMap<>(); + activeTimeRange.put("start", yamlParams.get("guardActiveStart")); + activeTimeRange.put("end", yamlParams.get("guardActiveEnd")); + String blackListString = yamlParams.get("blackList"); + List blackList = null; + if(blackListString!=null){ + if (blackListString.contains(",")){ + blackList = Arrays.asList(blackListString.split(",")); + } + else{ + blackList = new ArrayList<>(); + blackList.add(blackListString); + } + } + File templateFile; + Path xacmlTemplatePath; + ClassLoader classLoader = getClass().getClassLoader(); + Constraint cons = new Constraint(); + switch (ruleProvider){ + case GUARD_BL_YAML: + templateFile = new File(classLoader.getResource(XACML_BLGUARD_TEMPLATE).getFile()); + xacmlTemplatePath = templateFile.toPath(); + cons.setActive_time_range(activeTimeRange); + cons.setBlacklist(blackList); + break; + default: + templateFile = new File(classLoader.getResource(XACML_GUARD_TEMPLATE).getFile()); + xacmlTemplatePath = templateFile.toPath(); + Map timeWindow = new HashMap<>(); + if(!PolicyUtils.isInteger(yamlParams.get("timeWindow"))){ + throw new BuilderException("time window is not in Integer format."); + } + String timeUnits = yamlParams.get("timeUnits"); + if(timeUnits==null || !(timeUnits.equalsIgnoreCase("minute") || timeUnits.equalsIgnoreCase("hour") || timeUnits.equalsIgnoreCase("day") + || timeUnits.equalsIgnoreCase("week") || timeUnits.equalsIgnoreCase("month")||timeUnits.equalsIgnoreCase("year"))){ + throw new BuilderException("time Units is not in proper format."); + } + timeWindow.put("value", yamlParams.get("timeWindow")); + timeWindow.put("units", yamlParams.get("timeUnits")); + cons = new Constraint(Integer.parseInt(yamlParams.get("limit")),timeWindow,activeTimeRange); + break; + } + builder = builder.addLimitConstraint(policy1.getId(), cons); + // Build the specification + Results results = builder.buildSpecification(); + // YAML TO XACML + ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification()); + String xacmlTemplateContent; + try { + xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath)); + HashMap yamlSpecs = new HashMap<>(); + yamlSpecs.put(POLICY_NAME, yamlParams.get(POLICY_NAME)); + yamlSpecs.put(DESCRIPTION, yamlParams.get(DESCRIPTION)); + yamlSpecs.put(ONAPNAME, yamlParams.get(ONAPNAME)); + yamlSpecs.put("actor", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor()); + yamlSpecs.put("recipe", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe()); + yamlSpecs.put("clname", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName()); + if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()!=null){ + yamlSpecs.put("limit", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target().toString()); + } + if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()!=null){ + yamlSpecs.put("twValue", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("value")); + yamlSpecs.put("twUnits", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("units")); + } + yamlSpecs.put("guardActiveStart", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("start")); + yamlSpecs.put("guardActiveEnd", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("end")); + String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs, yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist(), yamlGuardObject.getGuards().getFirst().getMatch_parameters().getTargets()); + // Convert the Policy into Stream input to Policy Adapter. + Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8))); + return (PolicyType) policy; + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() , e); + } + } catch (BuilderException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() ,e); + throw e; + } + return null; + } + + private DecisionSettings findDecisionSettingsBySettingId(String settingId) { + DecisionSettings decisionSetting = null; + + EntityManager em = XACMLPapServlet.getEmf().createEntityManager(); + Query getDecisionSettings = em.createNamedQuery("DecisionSettings.findAll"); + List decisionSettingsList = getDecisionSettings.getResultList(); + + for (Object id : decisionSettingsList) { + decisionSetting = (DecisionSettings) id; + if (decisionSetting.getXacmlId().equals(settingId)) { + break; + } + } + return decisionSetting; + } + + private void createRule(PolicyType decisionPolicy, boolean permitRule) { + RuleType rule = new RuleType(); + + rule.setRuleId(policyAdapter.getRuleID()); + + if (permitRule) { + rule.setEffect(EffectType.PERMIT); + } else { + rule.setEffect(EffectType.DENY); + } + rule.setTarget(new TargetType()); + + // Create Target in Rule + AllOfType allOfInRule = new AllOfType(); + + // Creating match for ACCESS in rule target + MatchType accessMatch = new MatchType(); + AttributeValueType accessAttributeValue = new AttributeValueType(); + accessAttributeValue.setDataType(STRING_DATATYPE); + accessAttributeValue.getContent().add("DECIDE"); + accessMatch.setAttributeValue(accessAttributeValue); + AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); + URI accessURI = null; + try { + accessURI = new URI(ACTION_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI"); + } + accessAttributeDesignator.setCategory(CATEGORY_ACTION); + accessAttributeDesignator.setDataType(STRING_DATATYPE); + accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); + accessMatch.setAttributeDesignator(accessAttributeDesignator); + accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels(); + dynamicFieldComboRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo(); + dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1(); + dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2(); + dropDownMap = createDropDownMap(); + + if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){ + // Values for AAF Provider are here for XML Creation. + ConditionType condition = new ConditionType(); + ApplyType decisionApply = new ApplyType(); + String selectedFunction = "boolean-equal"; + + AttributeValueType value1 = new AttributeValueType(); + value1.setDataType(BOOLEAN_DATATYPE); + value1.getContent().add("true"); + + AttributeDesignatorType value2 = new AttributeDesignatorType(); + value2.setAttributeId(AAFEngine.AAF_RESULT); + value2.setCategory(CATEGORY_RESOURCE); + value2.setDataType(BOOLEAN_DATATYPE); + value2.setMustBePresent(false); + + ApplyType innerDecisionApply = new ApplyType(); + innerDecisionApply.setFunctionId(FUNCTION_BOOLEAN_ONE_AND_ONLY); + innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(value2)); + + decisionApply.setFunctionId(dropDownMap.get(selectedFunction)); + decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(value1)); + decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply)); + condition.setExpression(new ObjectFactory().createApply(decisionApply)); + if (!permitRule) { + ApplyType notOuterApply = new ApplyType(); + notOuterApply.setFunctionId(FUNCTION_NOT); + notOuterApply.getExpression().add(condition.getExpression()); + condition.setExpression(new ObjectFactory().createApply(notOuterApply)); + } + rule.setCondition(condition); + allOfInRule.getMatch().add(accessMatch); + + AnyOfType anyOfInRule = new AnyOfType(); + anyOfInRule.getAllOf().add(allOfInRule); + + TargetType targetInRule = new TargetType(); + targetInRule.getAnyOf().add(anyOfInRule); + + rule.setTarget(targetInRule); + if(!permitRule){ + AdviceExpressionsType adviceExpressions = new AdviceExpressionsType(); + AdviceExpressionType adviceExpression = new AdviceExpressionType(); + adviceExpression.setAdviceId(AAFPROVIDER); + adviceExpression.setAppliesTo(EffectType.DENY); + AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType(); + assignment.setAttributeId("aaf.response"); + assignment.setCategory(CATEGORY_RESOURCE); + AttributeDesignatorType value = new AttributeDesignatorType(); + value.setAttributeId(AAFEngine.AAF_RESPONSE); + value.setCategory(CATEGORY_RESOURCE); + value.setDataType(STRING_DATATYPE); + value.setMustBePresent(false); + assignment.setExpression(new ObjectFactory().createAttributeDesignator(value)); + adviceExpression.getAttributeAssignmentExpression().add(assignment); + adviceExpressions.getAdviceExpression().add(adviceExpression); + rule.setAdviceExpressions(adviceExpressions); + } + decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); + policyAdapter.setPolicyData(decisionPolicy); + + }else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) { + boolean isCompound = false; + ConditionType condition = new ConditionType(); + int index = dynamicFieldOneRuleAlgorithms.size() - 1; + + for (String labelAttr : dynamicLabelRuleAlgorithms) { + // if the rule algorithm as a label means it is a compound + if (dynamicFieldOneRuleAlgorithms.get(index).equals(labelAttr)) { + ApplyType decisionApply = new ApplyType(); + + String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index); + String value1 = dynamicFieldOneRuleAlgorithms.get(index); + String value2 = dynamicFieldTwoRuleAlgorithms.get(index); + decisionApply.setFunctionId(dropDownMap.get(selectedFunction)); + decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1))); + decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2))); + condition.setExpression(new ObjectFactory().createApply(decisionApply)); + isCompound = true; + } + + // if rule algorithm not a compound + if (!isCompound) { + condition.setExpression(new ObjectFactory().createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index)))); + } + } + if (!permitRule) { + ApplyType notOuterApply = new ApplyType(); + notOuterApply.setFunctionId(FUNCTION_NOT); + notOuterApply.getExpression().add(condition.getExpression()); + condition.setExpression(new ObjectFactory().createApply(notOuterApply)); + } + rule.setCondition(condition); + allOfInRule.getMatch().add(accessMatch); + + AnyOfType anyOfInRule = new AnyOfType(); + anyOfInRule.getAllOf().add(allOfInRule); + + TargetType targetInRule = new TargetType(); + targetInRule.getAnyOf().add(anyOfInRule); + + rule.setTarget(targetInRule); + + decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); + policyAdapter.setPolicyData(decisionPolicy); + + } else { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."+ policyAdapter.getData().getClass().getCanonicalName()); + } + + } + + private void createRainydayRule(PolicyType decisionPolicy, String errorcode, String treatment, boolean permitRule) { + RuleType rule = new RuleType(); + + rule.setRuleId(UUID.randomUUID().toString()); + + if (permitRule) { + rule.setEffect(EffectType.PERMIT); + } else { + rule.setEffect(EffectType.DENY); + } + rule.setTarget(new TargetType()); + + // Create Target in Rule + AllOfType allOfInRule = new AllOfType(); + + // Creating match for DECIDE in rule target + MatchType accessMatch = new MatchType(); + AttributeValueType accessAttributeValue = new AttributeValueType(); + accessAttributeValue.setDataType(STRING_DATATYPE); + accessAttributeValue.getContent().add("DECIDE"); + accessMatch.setAttributeValue(accessAttributeValue); + AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); + URI accessURI = null; + try { + accessURI = new URI(ACTION_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI"); + } + accessAttributeDesignator.setCategory(CATEGORY_ACTION); + accessAttributeDesignator.setDataType(STRING_DATATYPE); + accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); + accessMatch.setAttributeDesignator(accessAttributeDesignator); + accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + allOfInRule.getMatch().add(accessMatch); + + // Creating match for ErrorCode in rule target + MatchType errorcodeMatch = new MatchType(); + AttributeValueType errorcodeAttributeValue = new AttributeValueType(); + errorcodeAttributeValue.setDataType(STRING_DATATYPE); + errorcodeAttributeValue.getContent().add(errorcode); + errorcodeMatch.setAttributeValue(errorcodeAttributeValue); + AttributeDesignatorType errorcodeAttributeDesignator = new AttributeDesignatorType(); + errorcodeAttributeDesignator.setCategory(CATEGORY_RESOURCE); + errorcodeAttributeDesignator.setDataType(STRING_DATATYPE); + errorcodeAttributeDesignator.setAttributeId("ErrorCode"); + errorcodeMatch.setAttributeDesignator(errorcodeAttributeDesignator); + errorcodeMatch.setMatchId(FUNCTION_STRING_REGEXP_MATCH); + + allOfInRule.getMatch().add(errorcodeMatch); + + AnyOfType anyOfInRule = new AnyOfType(); + anyOfInRule.getAllOf().add(allOfInRule); + + TargetType targetInRule = new TargetType(); + targetInRule.getAnyOf().add(anyOfInRule); + + rule.setTarget(targetInRule); + + AdviceExpressionsType adviceExpressions = new AdviceExpressionsType(); + AdviceExpressionType adviceExpression = new AdviceExpressionType(); + adviceExpression.setAdviceId(RAINY_DAY); + adviceExpression.setAppliesTo(EffectType.PERMIT); + + AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType(); + assignment.setAttributeId("treatment"); + assignment.setCategory(CATEGORY_RESOURCE); + + AttributeValueType treatmentAttributeValue = new AttributeValueType(); + treatmentAttributeValue.setDataType(STRING_DATATYPE); + treatmentAttributeValue.getContent().add(treatment); + assignment.setExpression(new ObjectFactory().createAttributeValue(treatmentAttributeValue)); + + adviceExpression.getAttributeAssignmentExpression().add(assignment); + adviceExpressions.getAdviceExpression().add(adviceExpression); + rule.setAdviceExpressions(adviceExpressions); + decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); + policyAdapter.setPolicyData(decisionPolicy); + + } + + // if compound setting the inner apply here + protected ApplyType getInnerDecisionApply(String value1Label) { + ApplyType decisionApply = new ApplyType(); + int index = 0; + // check the index for the label. + for (String labelAttr : dynamicLabelRuleAlgorithms) { + if (labelAttr.equals(value1Label)) { + String value1 = dynamicFieldOneRuleAlgorithms.get(index); + populateDataTypeList(value1); + + // check if the row contains label again + for (String labelValue : dynamicLabelRuleAlgorithms) { + if (labelValue.equals(value1)) { + return getCompoundDecisionApply(index); + } + } + + // Getting the values from the form. + String functionKey = dynamicFieldComboRuleAlgorithms.get(index); + String value2 = dynamicFieldTwoRuleAlgorithms.get(index); + decisionApply.setFunctionId(dropDownMap.get(functionKey)); + // if two text field are rule attributes. + if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) { + ApplyType innerDecisionApply1 = new ApplyType(); + ApplyType innerDecisionApply2 = new ApplyType(); + AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType(); + AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType(); + //If selected function is Integer function set integer functionID + if(functionKey.toLowerCase().contains("integer")){ + innerDecisionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY ); + innerDecisionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY); + attributeDesignator1.setDataType(INTEGER_DATATYPE); + attributeDesignator2.setDataType(INTEGER_DATATYPE); + } else{ + //If selected function is not a Integer function set String functionID + innerDecisionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY); + innerDecisionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY); + attributeDesignator1.setDataType(STRING_DATATYPE); + attributeDesignator2.setDataType(STRING_DATATYPE); + } + attributeDesignator1.setCategory(CATEGORY_RESOURCE); + attributeDesignator2.setCategory(CATEGORY_RESOURCE); + //Here set actual field values + attributeDesignator1.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8)); + attributeDesignator2.setAttributeId(value1. contains("resource:")?value1.substring( 9):value1.substring(8)); + innerDecisionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator1)); + innerDecisionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator2)); + decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply1)); + decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply2)); + } else { + // if either of one text field is rule attribute. + if (!value1.startsWith("S_")) { + ApplyType innerDecisionApply = new ApplyType(); + AttributeDesignatorType attributeDesignator = new AttributeDesignatorType(); + AttributeValueType decisionConditionAttributeValue = new AttributeValueType(); + + if (functionKey.toLowerCase().contains("integer")) { + innerDecisionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY); + decisionConditionAttributeValue.setDataType(INTEGER_DATATYPE); + attributeDesignator.setDataType(INTEGER_DATATYPE); + } else { + innerDecisionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY); + decisionConditionAttributeValue.setDataType(STRING_DATATYPE); + attributeDesignator.setDataType(STRING_DATATYPE); + } + + String attributeId = null; + String attributeValue = null; + + // Find which textField has rule attribute and set it as + // attributeId and the other as attributeValue. + attributeId = value1; + attributeValue = value2; + + if (attributeId != null) { + attributeDesignator.setCategory(CATEGORY_RESOURCE); + attributeDesignator.setAttributeId(attributeId); + } + decisionConditionAttributeValue.getContent().add(attributeValue); + innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator)); + decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue)); + decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply)); + } else { + value1 = value1.substring(2, value1.length()); + VariableReferenceType variableReferenceType = new VariableReferenceType(); + variableReferenceType.setVariableId(value1); + + String dataType = dataTypeList.get(index); + + AttributeValueType decisionConditionAttributeValue = new AttributeValueType(); + decisionConditionAttributeValue.setDataType(dataType); + decisionConditionAttributeValue.getContent().add(value2); + decisionApply.getExpression().add(new ObjectFactory().createVariableReference(variableReferenceType)); + decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue)); + } + } + } + index++; + } + return decisionApply; + } + + // if the rule algorithm is multiple compound one setting the apply + protected ApplyType getCompoundDecisionApply(int index) { + ApplyType decisionApply = new ApplyType(); + String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index); + String value1 = dynamicFieldOneRuleAlgorithms.get(index); + String value2 = dynamicFieldTwoRuleAlgorithms.get(index); + decisionApply.setFunctionId(dropDownMap.get(selectedFunction)); + decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1))); + decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2))); + return decisionApply; + } + + private VariableDefinitionType createDynamicVariable(String key, String value, String dataType) { + VariableDefinitionType dynamicVariable = new VariableDefinitionType(); + AttributeValueType dynamicAttributeValue = new AttributeValueType(); + + dynamicAttributeValue.setDataType(dataType); + dynamicAttributeValue.getContent().add(value); + + dynamicVariable.setVariableId(key); + dynamicVariable.setExpression(new ObjectFactory().createAttributeValue(dynamicAttributeValue)); + + return dynamicVariable; + + } + + private void populateDataTypeList(String value1) { + String dataType = null; + if(value1.contains("S_")) { + value1 = value1.substring(2, value1.length()); + DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1.substring(2, value1.length())); + if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) { + dataType = STRING_DATATYPE; + } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) { + dataType = BOOLEAN_DATATYPE; + } else { + dataType = INTEGER_DATATYPE; + } + } else { + dataType = "OTHER"; + } + + dataTypeList.add(dataType); + } + + private Map createDropDownMap(){ + JPAUtils jpaUtils = null; + try { + jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf()); + } catch (Exception e) { + LOGGER.error("Exception Occured"+e); + } + Map dropDownOptions = new HashMap<>(); + if(jpaUtils!=null){ + Map> functionMap = jpaUtils.getFunctionDatatypeMap(); + for (Map.Entry> map: functionMap.entrySet()) { + for (FunctionDefinition functionDef : map.getValue()) { + dropDownOptions.put(functionDef.getShortname(),functionDef.getXacmlid()); + } + } + } + return dropDownOptions; + } + + private String getDataType(String key) { + + DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key); + String dataType = null; + + if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) { + dataType = STRING_DATATYPE; + } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) { + dataType = BOOLEAN_DATATYPE; + } else { + dataType = INTEGER_DATATYPE; + } + + return dataType; + } + + @Override + public Object getCorrectPolicyDataObject() { + return policyAdapter.getData(); + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java new file mode 100644 index 000000000..0c8784c81 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java @@ -0,0 +1,1305 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.StringReader; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.json.Json; +import javax.json.JsonArray; +import javax.json.JsonObject; +import javax.json.JsonReader; +import javax.persistence.EntityManager; +import javax.persistence.Query; + +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.ActionList; +import org.onap.policy.rest.jpa.AddressGroup; +import org.onap.policy.rest.jpa.GroupServiceList; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.jpa.PortList; +import org.onap.policy.rest.jpa.PrefixList; +import org.onap.policy.rest.jpa.ProtocolList; +import org.onap.policy.rest.jpa.ServiceList; +import org.onap.policy.rest.jpa.TermList; +import org.onap.policy.rest.jpa.UserInfo; + +import com.att.research.xacml.std.IdentifierImpl; +import com.fasterxml.jackson.databind.JsonNode; +import com.github.fge.jackson.JsonLoader; +import com.github.fge.jsonpatch.diff.JsonDiff; + +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.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +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; + +public class FirewallConfigPolicy extends Policy { + + private static final Logger LOGGER = FlexLogger.getLogger(FirewallConfigPolicy.class); + + public FirewallConfigPolicy() { + super(); + } + + public FirewallConfigPolicy(PolicyRestAdapter policyAdapter) { + this.policyAdapter = policyAdapter; + this.policyAdapter.setConfigType(policyAdapter.getConfigType()); + } + + // Saving the Configurations file at server location for config policy. + protected void saveConfigurations(String policyName, String jsonBody) { + String configurationName = policyName; + FileWriter fw = null; + try{ + if(configurationName.endsWith(".xml")){ + configurationName = configurationName.replace(".xml", ""); + } + fw = new FileWriter(CONFIG_HOME + File.separator + configurationName + ".json"); + BufferedWriter bw = new BufferedWriter(fw); + bw.write(jsonBody); + bw.close(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Configuration is succesfully saved"); + } + } catch (IOException e) { + LOGGER.error("Exception Occured"+e); + }finally{ + try{ + if(fw != null){ + fw.close(); + } + }catch(Exception e){ + LOGGER.error("Exception Occured"+e); + } + } + } + + //Utility to read json data from the existing file to a string + static String readFile(String path, Charset encoding) throws IOException { + byte[] encoded = Files.readAllBytes(Paths.get(path)); + return new String(encoded, encoding); + } + + @Override + public Map savePolicies() throws Exception { + Map successMap = new HashMap<>(); + if(isPolicyExists()){ + successMap.put("EXISTS", "This Policy already exist on the PAP"); + return successMap; + } + if(!isPreparedToSave()){ + prepareToSave(); + } + + // Until here we prepared the data and here calling the method to create xml. + Path newPolicyPath = null; + newPolicyPath = Paths.get(policyAdapter.getNewFileName()); + Boolean dbIsUpdated = false; + if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())){ + if (policyAdapter.isEditPolicy()) { + dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody()); + } else { + dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody()); + } + } else { + dbIsUpdated = true; + } + + if(dbIsUpdated) { + successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + } else { + PolicyLogger.error("Failed to Update the Database Dictionary Tables."); + + //remove the new json file + String jsonBody = policyAdapter.getPrevJsonBody(); + if (jsonBody!=null){ + saveConfigurations(policyName, jsonBody); + } else { + saveConfigurations(policyName, ""); + } + successMap.put("fwdberror", "DB UPDATE"); + } + + return successMap; + } + + //This is the method for preparing the policy for saving. We have broken it out + //separately because the fully configured policy is used for multiple things + @Override + public boolean prepareToSave() throws Exception{ + + if(isPreparedToSave()){ + //we have already done this + return true; + } + + int version = 0; + String policyID = policyAdapter.getPolicyID(); + version = policyAdapter.getHighestVersion(); + + // Create the Instance for pojo, PolicyType object is used in marshaling. + if ("Config".equals(policyAdapter.getPolicyType())) { + PolicyType policyConfig = new PolicyType(); + + policyConfig.setVersion(Integer.toString(version)); + policyConfig.setPolicyId(policyID); + policyConfig.setTarget(new TargetType()); + policyAdapter.setData(policyConfig); + } + policyName = policyAdapter.getNewFileName(); + + //String oldPolicyName = policyName.replace(".xml", ""); + String scope = policyName.substring(0, policyName.indexOf('.')); + String dbPolicyName = policyName.substring(policyName.indexOf('.')+1).replace(".xml", ""); + + int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.')+1)); + dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.')+1); + if(oldversion > 1){ + oldversion = oldversion - 1; + dbPolicyName = dbPolicyName + oldversion + ".xml"; + } + EntityManager em = XACMLPapServlet.getEmf().createEntityManager(); + Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName"); + createPolicyQuery.setParameter("scope", scope); + createPolicyQuery.setParameter("policyName", dbPolicyName); + List createPolicyQueryList = createPolicyQuery.getResultList(); + if(!createPolicyQueryList.isEmpty()){ + PolicyEntity entitydata = (PolicyEntity) createPolicyQueryList.get(0); + policyAdapter.setPrevJsonBody(entitydata.getConfigurationData().getConfigBody()); + } + em.close(); + if (policyAdapter.getData() != null) { + String jsonBody = policyAdapter.getJsonBody(); + saveConfigurations(policyName, jsonBody); + + // Make sure the filename ends with an extension + if (!policyName.endsWith(".xml")) { + policyName = policyName + ".xml"; + } + + PolicyType configPolicy = (PolicyType) policyAdapter.getData(); + + configPolicy.setDescription(policyAdapter.getPolicyDescription()); + + configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); + + AllOfType allOfOne = new AllOfType(); + String fileName = policyAdapter.getNewFileName(); + String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length()); + } + allOfOne.getMatch().add(createMatch("PolicyName", name)); + AllOfType allOf = new AllOfType(); + + // Match for ConfigName + allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName())); + // Match for riskType + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); + // Match for riskLevel + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + // Match for riskguard + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); + // Match for ttlDate + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + AnyOfType anyOf = new AnyOfType(); + anyOf.getAllOf().add(allOfOne); + anyOf.getAllOf().add(allOf); + + TargetType target = new TargetType(); + target.getAnyOf().add(anyOf); + + // Adding the target to the policy element + configPolicy.setTarget((TargetType) target); + + RuleType rule = new RuleType(); + rule.setRuleId(policyAdapter.getRuleID()); + rule.setEffect(EffectType.PERMIT); + + // Create Target in Rule + AllOfType allOfInRule = new AllOfType(); + + // Creating match for ACCESS in rule target + MatchType accessMatch = new MatchType(); + AttributeValueType accessAttributeValue = new AttributeValueType(); + accessAttributeValue.setDataType(STRING_DATATYPE); + accessAttributeValue.getContent().add("ACCESS"); + accessMatch.setAttributeValue(accessAttributeValue); + AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); + URI accessURI = null; + try { + accessURI = new URI(ACTION_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating ACCESS URI"); + } + accessAttributeDesignator.setCategory(CATEGORY_ACTION); + accessAttributeDesignator.setDataType(STRING_DATATYPE); + accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); + accessMatch.setAttributeDesignator(accessAttributeDesignator); + accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + // Creating Config Match in rule Target + MatchType configMatch = new MatchType(); + AttributeValueType configAttributeValue = new AttributeValueType(); + configAttributeValue.setDataType(STRING_DATATYPE); + + configAttributeValue.getContent().add("Config"); + + configMatch.setAttributeValue(configAttributeValue); + AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType(); + URI configURI = null; + try { + configURI = new URI(RESOURCE_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI"); + } + + configAttributeDesignator.setCategory(CATEGORY_RESOURCE); + configAttributeDesignator.setDataType(STRING_DATATYPE); + configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue()); + configMatch.setAttributeDesignator(configAttributeDesignator); + configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + allOfInRule.getMatch().add(accessMatch); + allOfInRule.getMatch().add(configMatch); + + AnyOfType anyOfInRule = new AnyOfType(); + anyOfInRule.getAllOf().add(allOfInRule); + + TargetType targetInRule = new TargetType(); + targetInRule.getAnyOf().add(anyOfInRule); + + rule.setTarget(targetInRule); + rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); + + configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); + policyAdapter.setPolicyData(configPolicy); + + } else { + PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); + } + setPreparedToSave(true); + return true; + } + + // Data required for Advice part is setting here. + private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { + + //Firewall Config ID Assignment + AdviceExpressionsType advices = new AdviceExpressionsType(); + AdviceExpressionType advice = new AdviceExpressionType(); + advice.setAdviceId("firewallConfigID"); + advice.setAppliesTo(EffectType.PERMIT); + // For Configuration + AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); + assignment1.setAttributeId("type"); + assignment1.setCategory(CATEGORY_RESOURCE); + assignment1.setIssuer(""); + AttributeValueType configNameAttributeValue = new AttributeValueType(); + configNameAttributeValue.setDataType(STRING_DATATYPE); + configNameAttributeValue.getContent().add("Configuration"); + assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); + advice.getAttributeAssignmentExpression().add(assignment1); + + // For Config file Url if configurations are provided. + //URL ID Assignment + AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); + assignment2.setAttributeId("URLID"); + assignment2.setCategory(CATEGORY_RESOURCE); + assignment2.setIssuer(""); + AttributeValueType AttributeValue = new AttributeValueType(); + AttributeValue.setDataType(URI_DATATYPE); + if (policyName.endsWith(".xml")) { + policyName = policyName.substring(0, policyName.lastIndexOf(".xml")); + } + String content = CONFIG_URL + "/Config/" + policyName + ".json"; + + AttributeValue.getContent().add(content); + assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); + advice.getAttributeAssignmentExpression().add(assignment2); + + //Policy Name Assignment + AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); + assignment3.setAttributeId("PolicyName"); + assignment3.setCategory(CATEGORY_RESOURCE); + assignment3.setIssuer(""); + AttributeValueType attributeValue3 = new AttributeValueType(); + attributeValue3.setDataType(STRING_DATATYPE); + fileName = FilenameUtils.removeExtension(fileName); + fileName = fileName + ".xml"; + String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); + } + attributeValue3.getContent().add(name); + assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); + advice.getAttributeAssignmentExpression().add(assignment3); + + //Version Number Assignment + AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); + assignment4.setAttributeId("VersionNumber"); + assignment4.setCategory(CATEGORY_RESOURCE); + assignment4.setIssuer(""); + AttributeValueType configNameAttributeValue4 = new AttributeValueType(); + configNameAttributeValue4.setDataType(STRING_DATATYPE); + configNameAttributeValue4.getContent().add(Integer.toString(version)); + assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); + advice.getAttributeAssignmentExpression().add(assignment4); + + //Onap Name Assignment + AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); + assignment5.setAttributeId("matching:" + ONAPID); + assignment5.setCategory(CATEGORY_RESOURCE); + assignment5.setIssuer(""); + AttributeValueType configNameAttributeValue5 = new AttributeValueType(); + configNameAttributeValue5.setDataType(STRING_DATATYPE); + assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); + advice.getAttributeAssignmentExpression().add(assignment5); + + //Config Name Assignment + AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); + assignment6.setAttributeId("matching:" + CONFIGID); + assignment6.setCategory(CATEGORY_RESOURCE); + assignment6.setIssuer(""); + AttributeValueType configNameAttributeValue6 = new AttributeValueType(); + configNameAttributeValue6.setDataType(STRING_DATATYPE); + configNameAttributeValue6.getContent().add(policyAdapter.getConfigName()); + assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); + advice.getAttributeAssignmentExpression().add(assignment6); + + //Risk Attributes + AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); + assignment7.setAttributeId("RiskType"); + assignment7.setCategory(CATEGORY_RESOURCE); + assignment7.setIssuer(""); + + AttributeValueType configNameAttributeValue7 = new AttributeValueType(); + configNameAttributeValue7.setDataType(STRING_DATATYPE); + configNameAttributeValue7.getContent().add(policyAdapter.getRiskType()); + assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); + + advice.getAttributeAssignmentExpression().add(assignment7); + + AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); + assignment8.setAttributeId("RiskLevel"); + assignment8.setCategory(CATEGORY_RESOURCE); + assignment8.setIssuer(""); + + AttributeValueType configNameAttributeValue8 = new AttributeValueType(); + configNameAttributeValue8.setDataType(STRING_DATATYPE); + configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel()); + assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8)); + + advice.getAttributeAssignmentExpression().add(assignment8); + + AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); + assignment9.setAttributeId("guard"); + assignment9.setCategory(CATEGORY_RESOURCE); + assignment9.setIssuer(""); + + AttributeValueType configNameAttributeValue9 = new AttributeValueType(); + configNameAttributeValue9.setDataType(STRING_DATATYPE); + configNameAttributeValue9.getContent().add(policyAdapter.getGuard()); + assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); + + advice.getAttributeAssignmentExpression().add(assignment9); + + AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); + assignment10.setAttributeId("TTLDate"); + assignment10.setCategory(CATEGORY_RESOURCE); + assignment10.setIssuer(""); + + AttributeValueType configNameAttributeValue10 = new AttributeValueType(); + configNameAttributeValue10.setDataType(STRING_DATATYPE); + configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate()); + assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10)); + + advice.getAttributeAssignmentExpression().add(assignment10); + advices.getAdviceExpression().add(advice); + return advices; + } + + + private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException { + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); + JsonObject json = null; + if (jsonBody != null) { + + //Read jsonBody to JsonObject + json = stringToJson(jsonBody); + + JsonArray firewallRules = null; + JsonArray serviceGroup = null; + JsonArray addressGroup = null; + //insert data into tables + try { + firewallRules = json.getJsonArray("firewallRuleList"); + serviceGroup = json.getJsonArray("serviceGroups"); + addressGroup = json.getJsonArray("addressGroups"); + /* + * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables + */ + if (firewallRules != null) { + for(int i = 0;i result = dbConnection.getDataById(TermList.class, "termName", ruleName); + if(result != null && !result.isEmpty()){ + TermList termEntry = (TermList) result.get(0); + dbConnection.delete(termEntry); + } + + //getting fromZone Array field from the firewallRulesList + JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones"); + String fromZoneString = null; + + for (int fromZoneIndex = 0;fromZoneIndex p1.id AND protocollist.protocolname = p1.protocolname;"; + dbConnection.updateQuery(protoDelete); + + //PortList Table + String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 " + + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; "; + dbConnection.updateQuery(portListDelete); + + //PrefixList Table + String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 " + + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND " + + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; "; + dbConnection.updateQuery(prefixListDelete); + + //GroupServiceList + String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 " + + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND " + + "groupservicelist.serviceList = g1.serviceList; "; + dbConnection.updateQuery(groupServiceDelete); + }catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values"); + return false; + } + return true; + + } else { + return false; + } + + } + + + private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) { + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); + JsonObject oldJson = null; + JsonObject newJson = null; + + if (jsonBody != null || prevJsonBody != null) { + + oldJson = stringToJson(prevJsonBody); + newJson = stringToJson(jsonBody); + + //if no changes to the json then return true + if (oldJson != null && oldJson.equals(newJson)) { + return true; + } + + JsonArray firewallRules = null; + JsonArray serviceGroup = null; + JsonArray addressGroup = null; + + firewallRules = newJson.getJsonArray("firewallRuleList"); + serviceGroup = newJson.getJsonArray("serviceGroups"); + addressGroup = newJson.getJsonArray("addressGroups"); + + //insert data into tables + try { + JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody); + + for (int i = 0; i result = dbConnection.getDataById(TermList.class, "termName", ruleName); + if(result != null && !result.isEmpty()){ + TermList termEntry = (TermList) result.get(0); + dbConnection.delete(termEntry); + } + + //getting fromZone Array field from the firewallRulesList + JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones"); + String fromZoneString = null; + + for (int fromZoneIndex = 0; fromZoneIndex actionResult = dbConnection.getDataById(ActionList.class, "actionName", action); + if(actionResult == null || actionResult.isEmpty()){ + ActionList actionEntry = new ActionList(); + actionEntry.setActionName(action); + actionEntry.setDescription(action); + dbConnection.save(actionEntry); + } + } + } + + if (path.contains("serviceGroups")) { + /* + * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables + */ + for(int si = 0; si < serviceGroup.size(); si++) { + /* + * Populate ArrayLists with values from the JSON + */ + //create the JSON object from the JSON Array for each iteration through the for loop + JsonObject svcGroupListobj = serviceGroup.getJsonObject(si); + + String groupName = svcGroupListobj.get("name").toString().replace('"', '\''); + + String description = null; + if (svcGroupListobj.containsKey("description")){ + description = svcGroupListobj.get("description").toString().replace('"', '\''); + } + + JsonArray membersArray = svcGroupListobj.getJsonArray("members"); + + Boolean isServiceGroup = false; + if (membersArray!=null){ + String membersType = membersArray.getJsonObject(0).get("type").toString(); + if (membersType.contains("REFERENCE")) { + isServiceGroup = true; + } + } + + //Insert values into GROUPSERVICELIST table if name begins with Group + if (isServiceGroup) { + List result = dbConnection.getDataById(GroupServiceList.class, "name", groupName); + if(result != null && !result.isEmpty()){ + GroupServiceList groupEntry = (GroupServiceList) result.get(0); + dbConnection.delete(groupEntry); + } + + String name = null; + for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) { + JsonObject membersObj = membersArray.getJsonObject(membersIndex); + String type = membersObj.get("type").toString().replace("\"", ""); + + String value = null; + if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){ + value = membersObj.get("name").toString(); + } else if (type.equalsIgnoreCase("ANY")){ + value = null; + } else { + value = membersObj.get("value").toString(); + } + + if(value != null){ + value = value.replace("\"", ""); + } + + if (name != null) { + name = name.concat(",").concat(value); + } else { + name = value; + } + } + String nameInsert = "'"+name+"'"; + GroupServiceList groupServiceEntry = new GroupServiceList(); + groupServiceEntry.setGroupName(groupName); + groupServiceEntry.setServiceList(nameInsert); + dbConnection.save(groupServiceEntry); + } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table + String type = svcGroupListobj.get("type").toString().replace('"', '\''); + String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\''); + String ports = svcGroupListobj.get("ports").toString().replace('"', '\''); + + List result = dbConnection.getDataById(ServiceList.class, "name", groupName); + if(result != null && !result.isEmpty()){ + ServiceList serviceEntry = (ServiceList) result.get(0); + dbConnection.delete(serviceEntry); + } + + ServiceList serviceListEntry = new ServiceList(); + serviceListEntry.setServiceName(groupName); + serviceListEntry.setServiceDescription(description); + serviceListEntry.setServiceType(type); + serviceListEntry.setServiceTransProtocol(transportProtocol); + serviceListEntry.setServiceAppProtocol("null"); + serviceListEntry.setServicePorts(ports); + dbConnection.save(serviceListEntry); + + List protocolResult = dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol); + if(protocolResult == null || protocolResult.isEmpty()){ + ProtocolList protocolEntry = new ProtocolList(); + protocolEntry.setProtocolName(transportProtocol); + protocolEntry.setDescription(transportProtocol); + dbConnection.save(protocolEntry); + } + + List portResult = dbConnection.getDataById(PortList.class, "portName", ports); + if(portResult == null || portResult.isEmpty()){ + PortList portEntry = new PortList(); + portEntry.setPortName(ports); + portEntry.setDescription(ports); + dbConnection.save(portEntry); + } + } + } + } + + if (path.contains("addressGroups")) { + /* + * Inserting addressGroup data into the ADDRESSGROUP table + */ + for(int ai=0; ai < addressGroup.size() ; ai++) { + + /* + * Populate ArrayLists with values from the JSON + */ + //create the JSON object from the JSON Array for each iteration through the for loop + JsonObject addressGroupObj = addressGroup.getJsonObject(ai); + + //create JSON array for members + JsonArray membersArray = addressGroupObj.getJsonArray("members"); + String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\''); + + String description = null; + if (addressGroupObj.containsKey("description")){ + description = addressGroupObj.get("description").toString().replace('"', '\''); + } + + String prefixIP = null; + String type = null; + for (int membersIndex=0; membersIndex < membersArray.size(); membersIndex++) { + JsonObject membersObj = membersArray.getJsonObject(membersIndex); + type = membersObj.get("type").toString().replace("\"", ""); + + String value = null; + if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){ + value = membersObj.get("name").toString(); + } else if (type.equalsIgnoreCase("ANY")){ + value = null; + } else { + value = membersObj.get("value").toString(); + } + + if(value != null){ + value = value.replace("\"", ""); + } + + if (prefixIP != null) { + prefixIP = prefixIP.concat(",").concat(value); + } else { + prefixIP = value; + } + } + + String prefixList = "'"+prefixIP+"'"; + Boolean isAddressGroup = type.contains("REFERENCE"); + + if (isAddressGroup) { + List result = dbConnection.getDataById(AddressGroup.class, "name", addressGroupName); + if(result != null && !result.isEmpty()){ + AddressGroup addressGroupEntry = (AddressGroup) result.get(0); + dbConnection.delete(addressGroupEntry); + } + AddressGroup newAddressGroup = new AddressGroup(); + newAddressGroup.setGroupName(addressGroupName); + newAddressGroup.setDescription(description); + newAddressGroup.setServiceList(prefixList); + dbConnection.save(newAddressGroup); + } else { + List result = dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName); + if(result != null && !result.isEmpty()){ + PrefixList prefixListEntry = (PrefixList) result.get(0); + dbConnection.delete(prefixListEntry); + } + PrefixList newPrefixList = new PrefixList(); + newPrefixList.setPrefixListName(addressGroupName); + newPrefixList.setDescription(description); + newPrefixList.setPrefixListValue(prefixList); + dbConnection.save(newPrefixList); + } + } + } + } + + /* + * Remove duplicate values from 'lookup' dictionary tables + */ + //ProtocolList Table + String protoDelete = "DELETE FROM protocollist USING protocollist, protocollist p1 " + + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;"; + dbConnection.updateQuery(protoDelete); + + //PortList Table + String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 " + + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; "; + dbConnection.updateQuery(portListDelete); + + //PrefixList Table + String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 " + + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND " + + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; "; + dbConnection.updateQuery(prefixListDelete); + + //GroupServiceList + String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 " + + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND " + + "groupservicelist.serviceList = g1.serviceList; "; + dbConnection.updateQuery(groupServiceDelete); + }catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries"); + return false; + } + return true; + } else { + return false; + } + + } + + private JsonObject stringToJson(String jsonString) { + JsonObject json = null; + if (jsonString != null) { + //Read jsonBody to JsonObject + StringReader in = null; + in = new StringReader(jsonString); + + JsonReader jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + jsonReader.close(); + } + return json; + } + + private JsonNode createPatch(String json, String oldJson) { + JsonNode oldJason = null; + JsonNode updatedJason = null; + + try { + oldJason = JsonLoader.fromString(oldJson); + updatedJason = JsonLoader.fromString(json); + } catch (IOException e) { + LOGGER.error("Exception Occured"+e); + } + return JsonDiff.asJson(oldJason, updatedJason); + } + + @Override + public Object getCorrectPolicyDataObject() { + return policyAdapter.getPolicyData(); + } + +} \ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java new file mode 100644 index 000000000..0297f30c0 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java @@ -0,0 +1,555 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + +import java.io.File; +import java.io.PrintWriter; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang.StringUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.MicroServiceModels; + +import com.att.research.xacml.std.IdentifierImpl; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Splitter; + +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.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +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; + +public class MicroServiceConfigPolicy extends Policy { + + private static final Logger LOGGER = FlexLogger.getLogger(MicroServiceConfigPolicy.class); + + private static Map mapAttribute = new HashMap<>(); + private static Map matchMap = new HashMap<>(); + + public MicroServiceConfigPolicy() { + super(); + } + + public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter){ + this.policyAdapter = policyAdapter; + } + + //save configuration of the policy based on the policyname + private void saveConfigurations(String policyName, String jsonBody) { + try { + if(policyName.endsWith(".xml")){ + policyName = policyName.replace(".xml", ""); + } + PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json"); + out.println(jsonBody); + out.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured While writing Configuration data"+e); + } + } + + + @Override + public Map savePolicies() throws Exception { + + Map successMap = new HashMap<>(); + if(isPolicyExists()){ + successMap.put("EXISTS", "This Policy already exist on the PAP"); + return successMap; + } + + if(!isPreparedToSave()){ + //Prep and configure the policy for saving + prepareToSave(); + } + + // Until here we prepared the data and here calling the method to create xml. + Path newPolicyPath = null; + newPolicyPath = Paths.get(policyAdapter.getNewFileName()); + + successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + + return successMap; + } + + //This is the method for preparing the policy for saving. We have broken it out + //separately because the fully configured policy is used for multiple things + @Override + public boolean prepareToSave() throws Exception{ + + if(isPreparedToSave()){ + //we have already done this + return true; + } + + int version = 0; + String policyID = policyAdapter.getPolicyID(); + version = policyAdapter.getHighestVersion(); + + // Create the Instance for pojo, PolicyType object is used in marshalling. + if (policyAdapter.getPolicyType().equals("Config")) { + PolicyType policyConfig = new PolicyType(); + + policyConfig.setVersion(Integer.toString(version)); + policyConfig.setPolicyId(policyID); + policyConfig.setTarget(new TargetType()); + policyAdapter.setData(policyConfig); + } + policyName = policyAdapter.getNewFileName(); + if (policyAdapter.getData() != null) { + // Save the Configurations file with the policy name with extention based on selection. + String jsonBody = policyAdapter.getJsonBody(); + saveConfigurations(policyName, jsonBody); + + // Make sure the filename ends with an extension + if (policyName.endsWith(".xml") == false) { + policyName = policyName + ".xml"; + } + + + PolicyType configPolicy = (PolicyType) policyAdapter.getData(); + + configPolicy.setDescription(policyAdapter.getPolicyDescription()); + + configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId()); + + AllOfType allOfOne = new AllOfType(); + String fileName = policyAdapter.getNewFileName(); + String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); + } + + //setup values for pulling out matching attributes + ObjectMapper mapper = new ObjectMapper(); + JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody()); + String matching = null; + + if (policyAdapter.getTtlDate()==null){ + policyAdapter.setTtlDate("NA"); + } + if (policyAdapter.getServiceType().contains("-v")){ + matching = getValueFromDictionary(policyAdapter.getServiceType()); + } else { + String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""}); + matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion); + } + + if (matching != null && !matching.isEmpty()){ + matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching); + if(policyAdapter.getJsonBody() != null){ + pullMatchValue(rootNode); + } + } + + // Match for policyName + allOfOne.getMatch().add(createMatch("PolicyName", name)); + + AllOfType allOf = new AllOfType(); + + // Adding the matches to AllOfType element Match for Onap + allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); + if (matchMap==null || matchMap.isEmpty()){ + // Match for ConfigName + allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName())); + // Match for Service + allOf.getMatch().add(createDynamicMatch("service", policyAdapter.getServiceType())); + // Match for uuid + allOf.getMatch().add(createDynamicMatch("uuid", policyAdapter.getUuid())); + // Match for location + allOf.getMatch().add(createDynamicMatch("location", policyAdapter.getLocation())); + }else { + for (Entry matchValue : matchMap.entrySet()){ + String value = matchValue.getValue(); + String key = matchValue.getKey().trim(); + if (value.contains("matching-true")){ + if (mapAttribute.containsKey(key)){ + allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key))); + } + } + } + } + // Match for riskType + allOf.getMatch().add( + createDynamicMatch("RiskType", policyAdapter.getRiskType())); + // Match for riskLevel + allOf.getMatch().add( + createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + // Match for riskguard + allOf.getMatch().add( + createDynamicMatch("guard", policyAdapter.getGuard())); + // Match for ttlDate + allOf.getMatch().add( + createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + + AnyOfType anyOf = new AnyOfType(); + anyOf.getAllOf().add(allOfOne); + anyOf.getAllOf().add(allOf); + + TargetType target = new TargetType(); + ((TargetType) target).getAnyOf().add(anyOf); + + // Adding the target to the policy element + configPolicy.setTarget((TargetType) target); + + RuleType rule = new RuleType(); + rule.setRuleId(policyAdapter.getRuleID()); + + rule.setEffect(EffectType.PERMIT); + + // Create Target in Rule + AllOfType allOfInRule = new AllOfType(); + + // Creating match for ACCESS in rule target + MatchType accessMatch = new MatchType(); + AttributeValueType accessAttributeValue = new AttributeValueType(); + accessAttributeValue.setDataType(STRING_DATATYPE); + accessAttributeValue.getContent().add("ACCESS"); + accessMatch.setAttributeValue(accessAttributeValue); + AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType(); + URI accessURI = null; + try { + accessURI = new URI(ACTION_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating ACCESS URI"); + } + accessAttributeDesignator.setCategory(CATEGORY_ACTION); + accessAttributeDesignator.setDataType(STRING_DATATYPE); + accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); + accessMatch.setAttributeDesignator(accessAttributeDesignator); + accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + // Creating Config Match in rule Target + MatchType configMatch = new MatchType(); + AttributeValueType configAttributeValue = new AttributeValueType(); + configAttributeValue.setDataType(STRING_DATATYPE); + configAttributeValue.getContent().add("Config"); + configMatch.setAttributeValue(configAttributeValue); + AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType(); + URI configURI = null; + try { + configURI = new URI(RESOURCE_ID); + } catch (URISyntaxException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating Config URI"); + } + configAttributeDesignator.setCategory(CATEGORY_RESOURCE); + configAttributeDesignator.setDataType(STRING_DATATYPE); + configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue()); + configMatch.setAttributeDesignator(configAttributeDesignator); + configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); + + allOfInRule.getMatch().add(accessMatch); + allOfInRule.getMatch().add(configMatch); + + AnyOfType anyOfInRule = new AnyOfType(); + anyOfInRule.getAllOf().add(allOfInRule); + + TargetType targetInRule = new TargetType(); + targetInRule.getAnyOf().add(anyOfInRule); + + rule.setTarget(targetInRule); + rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); + + configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); + policyAdapter.setPolicyData(configPolicy); + + } else { + PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); + } + setPreparedToSave(true); + return true; + } + + private void pullMatchValue(JsonNode rootNode) { + Iterator> fieldsIterator = rootNode.fields(); + String newValue = null; + while (fieldsIterator.hasNext()) { + Map.Entry field = fieldsIterator.next(); + final String key = field.getKey(); + final JsonNode value = field.getValue(); + if (value.isContainerNode() && !value.isArray()) { + pullMatchValue(value); // RECURSIVE CALL + } else { + newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""}); + mapAttribute.put(key, newValue); + } + } + + } + + private String getValueFromDictionary(String service){ + String ruleTemplate=null; + String modelName = service.split("-v")[0]; + String modelVersion = service.split("-v")[1]; + + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); + List result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+modelVersion); + if(result != null && !result.isEmpty()){ + MicroServiceModels model = (MicroServiceModels) result.get(0); + ruleTemplate = model.getAnnotation(); + } + return ruleTemplate; + } + + // Data required for Advice part is setting here. + private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { + AdviceExpressionsType advices = new AdviceExpressionsType(); + AdviceExpressionType advice = new AdviceExpressionType(); + advice.setAdviceId("MSID"); + advice.setAppliesTo(EffectType.PERMIT); + // For Configuration + AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType(); + assignment1.setAttributeId("type"); + assignment1.setCategory(CATEGORY_RESOURCE); + assignment1.setIssuer(""); + + AttributeValueType configNameAttributeValue = new AttributeValueType(); + configNameAttributeValue.setDataType(STRING_DATATYPE); + configNameAttributeValue.getContent().add("Configuration"); + assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); + + advice.getAttributeAssignmentExpression().add(assignment1); + // For Config file Url if configurations are provided. + AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); + assignment2.setAttributeId("URLID"); + assignment2.setCategory(CATEGORY_RESOURCE); + assignment2.setIssuer(""); + + AttributeValueType AttributeValue = new AttributeValueType(); + AttributeValue.setDataType(URI_DATATYPE); + String configName; + if(policyName.endsWith(".xml")){ + configName = policyName.replace(".xml", ""); + }else{ + configName = policyName; + } + String content = CONFIG_URL +"/Config/" + configName + ".json"; + AttributeValue.getContent().add(content); + assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); + + advice.getAttributeAssignmentExpression().add(assignment2); + AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); + assignment3.setAttributeId("PolicyName"); + assignment3.setCategory(CATEGORY_RESOURCE); + assignment3.setIssuer(""); + + AttributeValueType attributeValue3 = new AttributeValueType(); + attributeValue3.setDataType(STRING_DATATYPE); + fileName = FilenameUtils.removeExtension(fileName); + fileName = fileName + ".xml"; + String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length()); + if ((name == null) || (name.equals(""))) { + name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); + } + attributeValue3.getContent().add(name); + assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); + advice.getAttributeAssignmentExpression().add(assignment3); + + AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); + assignment4.setAttributeId("VersionNumber"); + assignment4.setCategory(CATEGORY_RESOURCE); + assignment4.setIssuer(""); + + AttributeValueType configNameAttributeValue4 = new AttributeValueType(); + configNameAttributeValue4.setDataType(STRING_DATATYPE); + configNameAttributeValue4.getContent().add(Integer.toString(version)); + assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); + + advice.getAttributeAssignmentExpression().add(assignment4); + + AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); + assignment5.setAttributeId("matching:" + ONAPID); + assignment5.setCategory(CATEGORY_RESOURCE); + assignment5.setIssuer(""); + + AttributeValueType configNameAttributeValue5 = new AttributeValueType(); + configNameAttributeValue5.setDataType(STRING_DATATYPE); + configNameAttributeValue5.getContent().add(policyAdapter.getOnapName()); + assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); + + advice.getAttributeAssignmentExpression().add(assignment5); + + AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); + assignment7.setAttributeId("matching:service"); + assignment7.setCategory(CATEGORY_RESOURCE); + assignment7.setIssuer(""); + + AttributeValueType configNameAttributeValue7 = new AttributeValueType(); + configNameAttributeValue7.setDataType(STRING_DATATYPE); + configNameAttributeValue7.getContent().add(policyAdapter.getServiceType()); + assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); + + advice.getAttributeAssignmentExpression().add(assignment7); + + if (matchMap==null || matchMap.isEmpty()){ + AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); + assignment6.setAttributeId("matching:" + CONFIGID); + assignment6.setCategory(CATEGORY_RESOURCE); + assignment6.setIssuer(""); + + AttributeValueType configNameAttributeValue6 = new AttributeValueType(); + configNameAttributeValue6.setDataType(STRING_DATATYPE); + configNameAttributeValue6.getContent().add(policyAdapter.getConfigName()); + assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); + + advice.getAttributeAssignmentExpression().add(assignment6); + + + AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); + assignment8.setAttributeId("matching:uuid"); + assignment8.setCategory(CATEGORY_RESOURCE); + assignment8.setIssuer(""); + + AttributeValueType configNameAttributeValue8 = new AttributeValueType(); + configNameAttributeValue8.setDataType(STRING_DATATYPE); + configNameAttributeValue8.getContent().add(policyAdapter.getUuid()); + assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8)); + + advice.getAttributeAssignmentExpression().add(assignment8); + + AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); + assignment9.setAttributeId("matching:Location"); + assignment9.setCategory(CATEGORY_RESOURCE); + assignment9.setIssuer(""); + + AttributeValueType configNameAttributeValue9 = new AttributeValueType(); + configNameAttributeValue9.setDataType(STRING_DATATYPE); + configNameAttributeValue9.getContent().add(policyAdapter.getLocation()); + assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); + + advice.getAttributeAssignmentExpression().add(assignment9); + } else { + for (Entry matchValue : matchMap.entrySet()){ + String value = matchValue.getValue(); + String key = matchValue.getKey().trim(); + if (value.contains("matching-true")){ + if (mapAttribute.containsKey(key)){ + AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); + assignment9.setAttributeId("matching:" + key); + assignment9.setCategory(CATEGORY_RESOURCE); + assignment9.setIssuer(""); + + AttributeValueType configNameAttributeValue9 = new AttributeValueType(); + configNameAttributeValue9.setDataType(STRING_DATATYPE); + configNameAttributeValue9.getContent().add(mapAttribute.get(key)); + assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); + + advice.getAttributeAssignmentExpression().add(assignment9); + + } + } + } + } + + AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); + assignment10.setAttributeId("Priority"); + assignment10.setCategory(CATEGORY_RESOURCE); + assignment10.setIssuer(""); + + AttributeValueType configNameAttributeValue10 = new AttributeValueType(); + configNameAttributeValue10.setDataType(STRING_DATATYPE); + configNameAttributeValue10.getContent().add(policyAdapter.getPriority()); + assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10)); + + advice.getAttributeAssignmentExpression().add(assignment10); + + //Risk Attributes + AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType(); + assignment11.setAttributeId("RiskType"); + assignment11.setCategory(CATEGORY_RESOURCE); + assignment11.setIssuer(""); + + AttributeValueType configNameAttributeValue11 = new AttributeValueType(); + configNameAttributeValue11.setDataType(STRING_DATATYPE); + configNameAttributeValue11.getContent().add(policyAdapter.getRiskType()); + assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11)); + + advice.getAttributeAssignmentExpression().add(assignment11); + + AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType(); + assignment12.setAttributeId("RiskLevel"); + assignment12.setCategory(CATEGORY_RESOURCE); + assignment12.setIssuer(""); + + AttributeValueType configNameAttributeValue12 = new AttributeValueType(); + configNameAttributeValue12.setDataType(STRING_DATATYPE); + configNameAttributeValue12.getContent().add(policyAdapter.getRiskLevel()); + assignment12.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue12)); + + advice.getAttributeAssignmentExpression().add(assignment12); + + AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType(); + assignment13.setAttributeId("guard"); + assignment13.setCategory(CATEGORY_RESOURCE); + assignment13.setIssuer(""); + + AttributeValueType configNameAttributeValue13 = new AttributeValueType(); + configNameAttributeValue13.setDataType(STRING_DATATYPE); + configNameAttributeValue13.getContent().add(policyAdapter.getGuard()); + assignment13.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue13)); + + advice.getAttributeAssignmentExpression().add(assignment13); + + AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType(); + assignment14.setAttributeId("TTLDate"); + assignment14.setCategory(CATEGORY_RESOURCE); + assignment14.setIssuer(""); + + AttributeValueType configNameAttributeValue14 = new AttributeValueType(); + configNameAttributeValue14.setDataType(STRING_DATATYPE); + configNameAttributeValue14.getContent().add(policyAdapter.getTtlDate()); + assignment14.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue14)); + + advice.getAttributeAssignmentExpression().add(assignment14); + + advices.getAdviceExpression().add(advice); + return advices; + } + + @Override + public Object getCorrectPolicyDataObject() { + return policyAdapter.getPolicyData(); + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java new file mode 100644 index 000000000..6d0a0c79b --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java @@ -0,0 +1,416 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; + +import javax.json.Json; +import javax.json.JsonReader; + +import org.apache.commons.io.FilenameUtils; +import org.json.JSONObject; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.xacml.util.XACMLPolicyWriter; + +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.util.XACMLProperties; +import com.att.research.xacmlatt.pdp.policy.PolicyDef; +import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef; + +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; + +public abstract class Policy { + + private static final Logger LOGGER = FlexLogger.getLogger(Policy.class); + + + /** + * Common Fields + */ + public static final String GET_INT_TYPE = "Integer"; + public static final String GET_STRING_TYPE = "String"; + + public static final String ONAPID = "ONAPName"; + public static final String CONFIGID = "ConfigName"; + public static final String CLOSEDLOOPID = "ServiceType"; + + public static final String CONFIG_POLICY = "Config"; + public static final String ACTION_POLICY = "Action"; + public static final String DECISION_POLICY = "Decision"; + + protected String policyName = null; + + protected boolean isValidForm = true; + + private Path finalPolicyPath = null; + + private boolean preparedToSave = false; + + private boolean policyExists = false; + + public Path getFinalPolicyPath() { + return finalPolicyPath; + } + + public void setFinalPolicyPath(Path finalPolicyPath) { + this.finalPolicyPath = finalPolicyPath; + } + + // 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_BOOLEAN_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:boolean-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_REGEXP_MATCH = "urn:oasis:names:tc:xacml:1.0:function:string-regexp-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 final String String = null; + + public static String CONFIG_HOME = null; + public static String ACTION_HOME = null; + public static String CONFIG_URL = null; + + protected Map performer = new HashMap<>(); + + private static String actionHome = null; + private static String configHome = null; + + public PolicyRestAdapter policyAdapter = null; + String ruleID = ""; + + public Policy() { + CONFIG_HOME = getConfigHome(); + ACTION_HOME = getActionHome(); + CONFIG_URL = "$URL"; + performer.put("PDP", "PDPAction"); + performer.put("PEP", "PEPAction"); + } + + //Each policy type seems to either use policyData or data field policy adapter when + //getting the xml to save the policy. Instead of keep this hardcoded in the save method, + //this method makes it usable outside. + /** + * Return the data field of the PolicyAdapter that will be used when saving this policy + * with the savePolicies method. + * @return Either the PolicyAdapter.getData() or PolicyAdapter.getPolicyData() + */ + public abstract Object getCorrectPolicyDataObject(); + public abstract Map savePolicies() throws Exception; + + //This is the method for preparing the policy for saving. We have broken it out + //separately because the fully configured policy is used for multiple things + public abstract boolean prepareToSave() throws Exception; + + + // create match for onap and config name + protected MatchType createMatch(String key, String value) { + MatchType match = new MatchType(); + + AttributeValueType attributeValue = new AttributeValueType(); + attributeValue.setDataType(STRING_DATATYPE); + attributeValue.getContent().add(value); + match.setAttributeValue(attributeValue); + AttributeDesignatorType attributeDesignator = new AttributeDesignatorType(); + URI uri = null; + try { + uri = new URI(key); + } catch (URISyntaxException e) { + LOGGER.error("Exception Occured"+e); + } + attributeDesignator.setCategory(CATEGORY_ACCESS_SUBJECT); + attributeDesignator.setDataType(STRING_DATATYPE); + attributeDesignator.setAttributeId(new IdentifierImpl(uri).stringValue()); + match.setAttributeDesignator(attributeDesignator); + match.setMatchId(FUNCTION_STRING_REGEX_MATCH); + return match; + } + + // Creating the match for dynamically added components. + protected MatchType createDynamicMatch(String key, String value) { + MatchType dynamicMatch = new MatchType(); + AttributeValueType dynamicAttributeValue = new AttributeValueType(); + String dataType = null; + dataType = STRING_DATATYPE; + dynamicAttributeValue.setDataType(dataType); + dynamicAttributeValue.getContent().add(value); + dynamicMatch.setAttributeValue(dynamicAttributeValue); + + AttributeDesignatorType dynamicAttributeDesignator = new AttributeDesignatorType(); + + URI dynamicURI = null; + try { + dynamicURI = new URI(key); + } catch (URISyntaxException e) { + LOGGER.error("Exception Occured"+e);// log msg + } + dynamicAttributeDesignator.setCategory(CATEGORY_RESOURCE); + dynamicAttributeDesignator.setDataType(dataType); + dynamicAttributeDesignator.setAttributeId(new IdentifierImpl(dynamicURI).stringValue()); + dynamicMatch.setAttributeDesignator(dynamicAttributeDesignator); + dynamicMatch.setMatchId(FUNCTION_STRING_REGEX_MATCH); + + return dynamicMatch; + } + + //validation for numeric + protected boolean isNumeric(String str){ + for (char c : str.toCharArray()){ + if (!Character.isDigit(c)) return false; + } + return true; + } + + // 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 reading json"+e); + return false; + }finally{ + if(jsonReader != null){ + jsonReader.close(); + } + } + return true; + } + + // the Policy Name as Unique One throws error + @SuppressWarnings("static-access") + protected Path getNextFilename(Path parent, String policyType, String polcyFileName, Integer version) { + policyType = FilenameUtils.removeExtension(policyType); + polcyFileName = FilenameUtils.removeExtension(polcyFileName); + Path newFile = null; + String policyDir = EMPTY_STRING; + String absolutePath = parent.toString(); + if (absolutePath != null && !absolutePath.equals(EMPTY_STRING)) { + policyDir = absolutePath.substring(absolutePath.lastIndexOf("\\") + 1, absolutePath.length()); + if (policyDir == null || policyDir.equals(EMPTY_STRING)) { + policyDir = absolutePath.substring(absolutePath.lastIndexOf("/") + 1, absolutePath.length()); + } + } + + String fileName = "default"; + if (policyDir != null && !policyDir.equals(EMPTY_STRING)) { + fileName = policyType + "_" + String.format(polcyFileName) + "." + version + ".xml"; + } + if (fileName != null) { + newFile = Paths.get(parent.toString(), fileName); + } + if (Files.notExists(newFile)) { + return newFile; + } + return null; + } + + protected Path getNextLoopFilename(Path parentPath, String policyType, String policyConfigType, String policyFileName, Integer version) { + policyType = FilenameUtils.removeExtension(policyType); + policyConfigType = FilenameUtils.removeExtension(policyConfigType); + policyFileName = FilenameUtils.removeExtension(policyFileName); + Path newFile = null; + String policyDir = EMPTY_STRING; + String absolutePath = parentPath.toString(); + if (absolutePath != null && !absolutePath.equals(EMPTY_STRING)) { + policyDir = absolutePath.substring(absolutePath.lastIndexOf("\\") + 1, absolutePath.length()); + if (policyDir == null || policyDir.equals(EMPTY_STRING)) { + policyDir = absolutePath.substring(absolutePath.lastIndexOf("/") + 1, absolutePath.length()); + } + } + + String fileName = "default"; + if (policyDir != null && !policyDir.equals(EMPTY_STRING)) { + if(policyConfigType.equals("ClosedLoop_PM")){ + fileName = policyType + "_" + "PM" + "_" +java.lang.String.format(policyFileName) + "." +version +".xml"; + }else if(policyConfigType.equals("ClosedLoop_Fault")){ + fileName = policyType + "_" + "Fault" + "_" +java.lang.String.format(policyFileName) + "." + version + ".xml"; + }else if(policyConfigType.equals("ClosedLoop_Fault")){ + fileName = policyType + "_" + "Fault" + "_" +java.lang.String.format(policyFileName) + "." + version + ".xml"; + }else if(policyConfigType.equals("Micro Service")){ + fileName = policyType + "_" + "MS" + "_" + java.lang.String.format(policyFileName) + "." + version + ".xml"; + } + } + if (fileName != null) { + newFile = Paths.get(parentPath.toString(), fileName); + } + if (Files.notExists(newFile)) { + return newFile; + } + return null; + } + + + //create policy once all the validations are completed + protected Map createPolicy(final Path policyPath, final Object policyData) { + Map success = new HashMap<>(); + // + // Is the root a PolicySet or Policy? + // + + if (policyData instanceof PolicyType) { + // + // Write it out + // + //Does not need to be XACMLPolicyWriterWithPapNotify since it is already in the PAP + //and this transaction is intercepted up stream. + InputStream inputStream = null; + try { + inputStream = XACMLPolicyWriter.getXmlAsInputStream((PolicyType) policyData); + PolicyDef policyDef = DOMPolicyDef.load(inputStream); + if (policyDef == null) { + success.put("validation", "PolicyDef Validation Failed"); + }else{ + success.put("success", "success"); + } + } catch (Exception e) { + LOGGER.error("PolicyDef Validation failed"+e); + success.put("error", "Validation Failed"); + }finally{ + try { + if(inputStream != null) + inputStream.close(); + } catch (IOException e) { + LOGGER.error("Exception Occured while closing the input stream"+e); + } + } + } else { + PolicyLogger.error("Unknown data type sent back."); + return success; + } + return success; + } + + public static String getConfigHome(){ + try { + loadWebapps(); + } catch (Exception e) { + return null; + } + return configHome; + } + + public static String getActionHome(){ + try { + loadWebapps(); + } catch (Exception e) { + return null; + } + return actionHome; + } + + private static void loadWebapps() throws Exception{ + if(actionHome == null || configHome == null){ + Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); + //Sanity Check + if (webappsPath == null) { + PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); + throw new Exception("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); + } + Path webappsPathConfig; + Path webappsPathAction; + if(webappsPath.toString().contains("\\")){ + webappsPathConfig = Paths.get(webappsPath.toString()+"\\Config"); + webappsPathAction = Paths.get(webappsPath.toString()+"\\Action"); + }else{ + webappsPathConfig = Paths.get(webappsPath.toString()+"/Config"); + webappsPathAction = Paths.get(webappsPath.toString()+"/Action"); + } + if(Files.notExists(webappsPathConfig)){ + try { + Files.createDirectories(webappsPathConfig); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", "Failed to create config directory"); + } + } + if(Files.notExists(webappsPathAction)){ + try { + Files.createDirectories(webappsPathAction); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", "Failed to create config directory"); + } + } + actionHome = webappsPathAction.toString(); + configHome = webappsPathConfig.toString(); + } + } + + public boolean validateConfigForm() { + return true; + } + + /** + * @return the preparedToSave + */ + public boolean isPreparedToSave() { + return preparedToSave; + } + + /** + * @param preparedToSave the preparedToSave to set + */ + protected void setPreparedToSave(boolean preparedToSave) { + this.preparedToSave = preparedToSave; + } + + public boolean isPolicyExists() { + return policyExists; + } + + public void setPolicyExists(boolean policyExists) { + this.policyExists = policyExists; + } + + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java new file mode 100644 index 000000000..98c8137de --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java @@ -0,0 +1,2798 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.ProtocolException; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.InvalidPathException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.Key; +import java.util.Base64; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.LockModeType; +import javax.persistence.PersistenceException; +import javax.persistence.Query; +import javax.persistence.RollbackException; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathFactory; + +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.IOUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +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.DatabaseLockEntity; +import org.onap.policy.rest.jpa.GroupEntity; +import org.onap.policy.rest.jpa.PdpEntity; +import org.onap.policy.rest.jpa.PolicyDBDaoEntity; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.util.Webapps; +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.StdPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; +import org.onap.policy.xacml.util.XACMLPolicyWriter; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDP; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.util.XACMLProperties; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + +public class PolicyDBDao { + private static final Logger logger = FlexLogger.getLogger(PolicyDBDao.class); + private List otherServers; + private EntityManagerFactory emf; + private static PolicyDBDao currentInstance = null; + private PAPPolicyEngine papEngine; + + public static final String JSON_CONFIG = "JSON"; + public static final String XML_CONFIG = "XML"; + public static final String PROPERTIES_CONFIG = "PROPERTIES"; + public static final String OTHER_CONFIG = "OTHER"; + public static final String AUDIT_USER = "audit"; + + /** + * Get an instance of a PolicyDBDao. It creates one if it does not exist. + * Only one instance is allowed to be created per server. + * @param emf The EntityFactoryManager to be used for database connections + * @return The new instance of PolicyDBDao or throw exception if the given emf is null. + * @throws IllegalStateException if a PolicyDBDao has already been constructed. Call getPolicyDBDaoInstance() to get this. + */ + public static PolicyDBDao getPolicyDBDaoInstance(EntityManagerFactory emf) throws Exception{ + logger.debug("getPolicyDBDaoInstance(EntityManagerFactory emf) as getPolicyDBDaoInstance("+emf+") called"); + if(currentInstance == null){ + if(emf != null){ + currentInstance = new PolicyDBDao(emf); + return currentInstance; + } + throw new IllegalStateException("The EntityManagerFactory is Null"); + } + return currentInstance; + } + + /** + * Gets the current instance of PolicyDBDao. + * @return The instance of PolicyDBDao or throws exception if the given instance is null. + * @throws IllegalStateException if a PolicyDBDao instance is null. Call createPolicyDBDaoInstance(EntityManagerFactory emf) to get this. + */ + public static PolicyDBDao getPolicyDBDaoInstance() throws Exception{ + logger.debug("getPolicyDBDaoInstance() as getPolicyDBDaoInstance() called"); + if(currentInstance != null){ + return currentInstance; + } + throw new IllegalStateException("The PolicyDBDao.currentInstance is Null. Use getPolicyDBDao(EntityManagerFactory emf)"); + } + public void setPapEngine(PAPPolicyEngine papEngine2){ + this.papEngine = (PAPPolicyEngine) papEngine2; + } + private PolicyDBDao(EntityManagerFactory emf){ + logger.debug("PolicyDBDao(EntityManagerFactory emf) as PolicyDBDao("+emf+") called"); + this.emf = emf; + + //not needed in this release + if(!register()){ + PolicyLogger.error("This server's PolicyDBDao instance could not be registered and may not reveive updates"); + } + + otherServers = getRemotePolicyDBDaoList(); + if(logger.isDebugEnabled()){ + logger.debug("Number of remote PolicyDBDao instances: "+otherServers.size()); + } + if(otherServers.isEmpty()){ + logger.warn("List of PolicyDBDao servers is empty or could not be retrieved"); + } + } + + //not static because we are going to be using the instance's emf + //waitTime in ms to wait for lock, or -1 to wait forever (no) + private void startTransactionSynced(EntityManager entityMgr,int waitTime){ + logger.debug("\n\nstartTransactionSynced(EntityManager entityMgr,int waitTime) as " + + "\n startTransactionSynced("+entityMgr+","+waitTime+") called\n\n"); + DatabaseLockEntity lock = null; + + entityMgr.setProperty("javax.persistence.query.timeout", waitTime); + entityMgr.getTransaction().begin(); + + if(logger.isDebugEnabled()){ + Map properties = entityMgr.getProperties(); + logger.debug("\n\nstartTransactionSynced():" + + "\n entityManager.getProperties() = " + properties + + "\n\n"); + } + try{ + if(logger.isDebugEnabled()){ + logger.debug("\n\nstartTransactionSynced():" + + "\n ATTEMPT to get the DB lock" + + "\n\n"); + } + lock = entityMgr.find(DatabaseLockEntity.class, 1, LockModeType.PESSIMISTIC_WRITE); + if(logger.isDebugEnabled()){ + logger.debug("\n\nstartTransactionSynced():" + + "\n GOT the DB lock" + + "\n\n"); + } + } catch(Exception e){ + System.out.println("Could not get lock entity"); + logger.error("Exception Occured"+e); + } + if(lock == null){ + throw new IllegalStateException("The lock row does not exist in the table. Please create a primary key with value = 1."); + } + + } + /** + * Gets the list of other registered PolicyDBDaos from the database + * @return List (type PolicyDBDaoEntity) of other PolicyDBDaos + */ + private List getRemotePolicyDBDaoList(){ + logger.debug("getRemotePolicyDBDaoList() as getRemotePolicyDBDaoList() called"); + List policyDBDaoEntityList = new LinkedList<>(); + EntityManager em = emf.createEntityManager(); + startTransactionSynced(em, 1000); + try{ + Query getPolicyDBDaoEntityQuery = em.createNamedQuery("PolicyDBDaoEntity.findAll"); + policyDBDaoEntityList = getPolicyDBDaoEntityQuery.getResultList(); + + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Exception querying for other registered PolicyDBDaos"); + logger.warn("List of remote PolicyDBDaos will be empty"); + } + try{ + em.getTransaction().commit(); + } catch(Exception e){ + try{ + em.getTransaction().rollback(); + } catch(Exception e2){ + + } + } + em.close(); + return policyDBDaoEntityList; + } + + public PolicyDBDaoTransaction getNewTransaction(){ + logger.debug("getNewTransaction() as getNewTransaction() called"); + return (PolicyDBDaoTransaction)(new PolicyDBDaoTransactionInstance()); + } + + /* + * Because the normal transactions are not used in audits, we can use the same transaction + * mechanism to get a transaction and obtain the emlock and the DB lock. We just need to + * provide different transaction timeout values in ms because the audit will run longer + * than normal transactions. + */ + public PolicyDBDaoTransaction getNewAuditTransaction(){ + logger.debug("getNewAuditTransaction() as getNewAuditTransaction() called"); + //Use the standard transaction wait time in ms + int auditWaitMs = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); + //Use the (extended) audit timeout time in ms + int auditTimeoutMs = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); + return (PolicyDBDaoTransaction)(new PolicyDBDaoTransactionInstance(auditTimeoutMs, auditWaitMs)); + } + + + /** + * Checks if two strings are equal. Null strings ARE allowed. + * @param one A String or null to compare + * @param two A String or null to compare + */ + private static boolean stringEquals(String one, String two){ + logger.debug("stringEquals(String one, String two) as stringEquals("+one+", "+two+") called"); + if(one == null && two == null){ + return true; + } + if(one == null || two == null){ + return false; + } + return one.equals(two); + } + + /** + * Computes the scope in dotted format based on an absolute path and a path that divides the scope. + * @param fullPath An absolute path including scope folders and other folders(does not have to be absolute, must just contain scope and other folders before) + * @param pathToExclude The path that acts as a division between the scope and the other folders + * @return The scope in dotted format (org.onap) + */ + private static String computeScope(String fullPath, String pathToExclude){ + logger.debug("computeScope(String fullPath, String pathToExclude) as computeScope("+fullPath+", "+pathToExclude+") called"); + int excludeIndex = fullPath.indexOf(pathToExclude); + String scopePath = fullPath.substring(excludeIndex+pathToExclude.length()); + String scope = scopePath.replace('\\', '.'); + scope = scope.replace('/', '.'); + if(scope.charAt(0) == '.'){ + scope = scope.substring(1); + } + if(scope.charAt(scope.length()-1) == '.'){ + scope = scope.substring(0, scope.length()-1); + } + return scope; + } + + /** + * Returns the url of this local pap server, removing the username and password, if they are present + * @return The url of this local pap server + */ + private String[] getPapUrlUserPass(){ + logger.debug("getPapUrl() as getPapUrl() called"); + String url = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + if(url == null){ + return null; + } + return splitPapUrlUserPass(url); + + + } + private String[] splitPapUrlUserPass(String url){ + String[] urlUserPass = new String[3]; + String[] commaSplit = url.split(","); + urlUserPass[0] = commaSplit[0]; + if(commaSplit.length > 2){ + urlUserPass[1] = commaSplit[1]; + urlUserPass[2] = commaSplit[2]; + } + if(urlUserPass[1] == null || urlUserPass[1].equals("")){ + String usernamePropertyValue = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + if(usernamePropertyValue != null){ + urlUserPass[1] = usernamePropertyValue; + } + } + if(urlUserPass[2] == null || urlUserPass[2].equals("")){ + String passwordPropertyValue = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + if(passwordPropertyValue != null){ + urlUserPass[2] = passwordPropertyValue; + } + } + //if there is no comma, for some reason there is no username and password, so don't try to cut them off + return urlUserPass; + } + + private static String encryptPassword(String password) throws Exception{ + Cipher cipher = Cipher.getInstance("AES"); + cipher.init(Cipher.ENCRYPT_MODE, aesKey()); + byte[] encryption = cipher.doFinal(password.getBytes("UTF-8")); + System.out.println(encryption); + return new String(Base64.getMimeEncoder().encode(encryption),"UTF-8"); + } + + private static String decryptPassword(String encryptedPassword) throws Exception{ + Cipher cipher = Cipher.getInstance("AES"); + cipher.init(Cipher.DECRYPT_MODE, aesKey()); + byte[] password = cipher.doFinal(Base64.getDecoder().decode(encryptedPassword.getBytes("UTF-8"))); + return new String(password,"UTF-8"); + } + private static Key aesKey(){ + byte[] aesValue = (new String("njrmbklcxtoplawf")).getBytes(); + return new SecretKeySpec(aesValue,"AES"); + } + /** + * Register the PolicyDBDao instance in the PolicyDBDaoEntity table + * @return Boolean, were we able to register? + */ + private boolean register(){ + logger.debug("register() as register() called"); + String[] url = getPapUrlUserPass(); + EntityManager em = emf.createEntityManager(); + try{ + startTransactionSynced(em, 1000); + } catch(IllegalStateException e){ + logger.debug ("\nPolicyDBDao.register() caught an IllegalStateException: \n" +e + "\n"); + DatabaseLockEntity lock; + lock = em.find(DatabaseLockEntity.class, 1); + if(lock==null){ + lock = new DatabaseLockEntity(); + em.persist(lock); + lock.setKey(1); + try{ + em.flush(); + em.getTransaction().commit(); + em.close(); + } catch(Exception e2){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "COULD NOT CREATE DATABASELOCK ROW. WILL TRY ONE MORE TIME"); + } + em = null; + em = emf.createEntityManager(); + try{ + startTransactionSynced(em, 1000); + } catch(Exception e3){ + String msg = "DATABASE LOCKING NOT WORKING. CONCURRENCY CONTROL NOT WORKING"; + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e3, "PolicyDBDao", msg); + throw new IllegalStateException("msg" + "\n" + e3); + } + } + } + logger.debug("\nPolicyDBDao.register. Database locking and concurrency control is initialized\n"); + PolicyDBDaoEntity foundPolicyDBDaoEntity = em.find(PolicyDBDaoEntity.class, url[0]); + Query getPolicyDBDaoEntityQuery = em.createQuery("SELECT e FROM PolicyDBDaoEntity e WHERE e.policyDBDaoUrl=:url"); + getPolicyDBDaoEntityQuery.setParameter("url", url[0]); + if(foundPolicyDBDaoEntity == null){ + PolicyDBDaoEntity newPolicyDBDaoEntity = new PolicyDBDaoEntity(); + em.persist(newPolicyDBDaoEntity); + newPolicyDBDaoEntity.setPolicyDBDaoUrl(url[0]); + newPolicyDBDaoEntity.setDescription("PAP server at "+url[0]); + newPolicyDBDaoEntity.setUsername(url[1]); + try{ + newPolicyDBDaoEntity.setPassword(encryptPassword(url[2])); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not encrypt PAP password"); + } + try{ + em.getTransaction().commit(); + } catch(Exception e){ + try{ + em.getTransaction().rollback(); + } catch(Exception e2){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "Could not add new PolicyDBDao to the database"); + } + } + } else { + //just want to update in order to change modified date + String encryptedPassword = null; + try{ + encryptedPassword = encryptPassword(url[2]); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not encrypt PAP password"); + } + if(url[1] != null && !stringEquals(url[1], foundPolicyDBDaoEntity.getUsername())){ + foundPolicyDBDaoEntity.setUsername(url[1]); + } + if(encryptedPassword != null && !stringEquals(encryptedPassword, foundPolicyDBDaoEntity.getPassword())){ + foundPolicyDBDaoEntity.setPassword(encryptedPassword); + } + foundPolicyDBDaoEntity.preUpdate(); + try{ + em.getTransaction().commit(); + } catch(Exception e){ + try{ + em.getTransaction().rollback(); + } catch(Exception e2){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "Could not update PolicyDBDao in the database"); + } + } + } + em.close(); + logger.debug("\nPolicyDBDao.register(). Success!!\n"); + return true; + } + public void notifyOthers(long entityId,String entityType){ + notifyOthers(entityId,entityType,null); + } + public void notifyOthers(long entityId, String entityType, String newGroupId){ + logger.debug("notifyOthers(long entityId, String entityType, long newGroupId) as notifyOthers("+entityId+","+entityType+","+newGroupId+") called"); + LinkedList notifyThreads = new LinkedList<>(); + + //we're going to run notifications in parallel threads to speed things up + for(Object obj : otherServers){ + + Thread newNotifyThread = new Thread(new NotifyOtherThread(obj, entityId, entityType, newGroupId)); + + newNotifyThread.start(); + + notifyThreads.add(newNotifyThread); + + } + //we want to wait for all notifications to complete or timeout before we unlock the interface and allow more changes + for(Thread t : notifyThreads){ + try { + t.join(); + } catch (Exception e) { + logger.warn("Could not join a notifcation thread" + e); + } + } + + + } + + private class NotifyOtherThread implements Runnable { + public NotifyOtherThread(Object obj, long entityId, String entityType, String newGroupId){ + this.obj = obj; + this.entityId = entityId; + this.entityType = entityType; + this.newGroupId = newGroupId; + } + private Object obj; + private long entityId; + private String entityType; + private String newGroupId; + @Override + public void run(){ + //naming of 'o' is for backwards compatibility with the rest of the function + PolicyDBDaoEntity dbdEntity = (PolicyDBDaoEntity)obj; + String o = dbdEntity.getPolicyDBDaoUrl(); + String username = dbdEntity.getUsername(); + String password; + try{ + password = decryptPassword(dbdEntity.getPassword()); + } catch(Exception e){ + //if we can't decrypt, might as well try it anyway + password = dbdEntity.getPassword(); + } + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8)); + HttpURLConnection connection = null; + UUID requestID = UUID.randomUUID(); + URL url; + try { + String papUrl = getPapUrlUserPass()[0]; + if(papUrl == null){ + papUrl = "undefined"; + } + logger.debug("We are going to try to notify "+o); + //is this our own url? + String ourUrl = o; + try{ + ourUrl = splitPapUrlUserPass((String)o)[0]; + }catch(Exception e){ + ourUrl = o; + } + if(o == null){ + o = "undefined"; + } + if(papUrl.equals(ourUrl)){ + logger.debug(((String)o)+" is our url, skipping notify"); + return; + } + if(newGroupId == null){ + url = new URL(((String)o)+"?policydbdaourl="+papUrl+"&entityid="+entityId+"&entitytype="+entityType); + } else { + url = new URL(((String)o)+"?policydbdaourl="+papUrl+"&entityid="+entityId+"&entitytype="+entityType+"&extradata="+newGroupId); + } + } catch (MalformedURLException e) { + logger.warn("Caught MalformedURLException on: new URL()", e); + return; + } + // + // Open up the connection + // + logger.debug("Connecting with url: "+url); + try { + connection = (HttpURLConnection)url.openConnection(); + } catch (Exception e) { + logger.warn("Caught exception on: url.openConnection()",e); + return; + } + // + // Setup our method and headers + // + try { + connection.setRequestMethod("PUT"); + } catch (ProtocolException e) { + //why would this error ever occur? + logger.warn("Caught ProtocolException on connection.setRequestMethod(\"PUT\");",e); + return; + } + 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()); + int readTimeout; + try{ + readTimeout = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_NOTIFY_TIMEOUT)); + + } catch(Exception e){ + logger.error("xacml.rest.pap.notify.timeoutms property not set, using a default."); + readTimeout = 10000; + } + connection.setReadTimeout(readTimeout); + connection.setConnectTimeout(readTimeout); + 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 (Exception e) { + logger.warn("Caught exception on: connection.connect()",e); + return; + } + try { + if (connection.getResponseCode() == 200) { + logger.info("Received response 200 from pap server on notify"); + //notified = true; + } else { + logger.warn("connection response code not 200, received: "+connection.getResponseCode()); + } + } catch (Exception e) { + logger.warn("Caught Exception on: connection.getResponseCode() ", e); + } + + + connection.disconnect(); + } + } + + private static String evaluateXPath(String expression, String xml) { + InputSource source = new InputSource(new StringReader(xml)); + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + String description = ""; + try{ + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db.parse(source); + + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPath xpath = xpathFactory.newXPath(); + + + description = xpath.evaluate(expression, document); + }catch(Exception e){ + logger.error("Exception Occured while evaluating path"+e); + } + + return description; + } + + private static String getDescriptionFromXacml(String xacmlData){ + String openTag = ""; + String closeTag = ""; + int descIndex = xacmlData.indexOf(openTag); + int endDescIndex = xacmlData.indexOf(closeTag); + String desc = xacmlData.substring(descIndex+openTag.length(),endDescIndex); + return desc; + } + + private final String POLICY_NOTIFICATION = "policy"; + private final String PDP_NOTIFICATION = "pdp"; + private final String GROUP_NOTIFICATION = "group"; + public void handleIncomingHttpNotification(String url, String entityId, String entityType, String extraData, XACMLPapServlet xacmlPapServlet){ + logger.info("DBDao url: " + url + " has reported an update on "+entityType+" entity "+entityId); + PolicyDBDaoTransaction transaction = this.getNewTransaction(); + //although its named retries, this is the total number of tries + int retries; + try{ + retries = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INCOMINGNOTIFICATION_TRIES)); + + } catch(Exception e){ + logger.error("xacml.rest.pap.incomingnotification.tries property not set, using a default of 3."+e); + retries = 3; + } + //if someone sets it to some dumb value, we need to make sure it will try at least once + if(retries < 1){ + retries = 1; + } + int pauseBetweenRetries = 1000; + switch(entityType){ + + case POLICY_NOTIFICATION: + for(int i=0; i pdpsInGroup = transaction.getPdpsInGroup(Long.parseLong(groupRecord.getGroupId())); + for(Object pdpO : pdpsInGroup){ + PdpEntity pdp = (PdpEntity)pdpO; + try { + papEngine.newPDP(pdp.getPdpId(), localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort()); + } catch (NullPointerException | PAPException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to get create pdp with papEngine.newPDP(pdp.getPdpId(), localGroup, pdp.getPdpName(), pdp.getDescription(), pdp.getJmxPort());"); + throw new PAPException("Could not create pdp "+pdp); + } + } + //add possible policies to group (filesystem only, apparently) + } else { + if(!(localGroup instanceof StdPDPGroup)){ + throw new PAPException("group is not a StdPDPGroup"); + } + //clone the object + //because it will be comparing the new group to its own version + StdPDPGroup localGroupClone = new StdPDPGroup(localGroup.getId(),localGroup.isDefaultGroup(),localGroup.getName(),localGroup.getDescription(),((StdPDPGroup)localGroup).getDirectory()); + localGroupClone.setOnapPdps(localGroup.getOnapPdps()); + localGroupClone.setPipConfigs(localGroup.getPipConfigs()); + localGroupClone.setStatus(localGroup.getStatus()); + //we are updating a group or adding a policy or changing default + //set default if it should be + if(!localGroupClone.isDefaultGroup() && groupRecord.isDefaultGroup()){ + try { + papEngine.SetDefaultGroup(localGroup); + return; + } catch (PAPException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to set default group with papEngine.SetDefaultGroup("+localGroupClone+");"); + throw new PAPException("Could not set default group to "+localGroupClone); + } + } + boolean needToUpdate = false; + if(updateGroupPoliciesInFileSystem(localGroupClone,localGroup, groupRecord, transaction)){ + needToUpdate = true; + } + if(!stringEquals(localGroupClone.getId(),groupRecord.getGroupId()) || !stringEquals(localGroupClone.getName(),groupRecord.getgroupName())){ + //changing ids + //we do not want to change the id, the papEngine will do this for us, it needs to know the old id + localGroupClone.setName(groupRecord.getgroupName()); + needToUpdate = true; + } + if(!stringEquals(localGroupClone.getDescription(),groupRecord.getDescription())){ + localGroupClone.setDescription(groupRecord.getDescription()); + needToUpdate = true; + } + if(needToUpdate){ + try { + + papEngine.updateGroup(localGroupClone); + } catch (PAPException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to update group with papEngine.updateGroup("+localGroupClone+");"); + throw new PAPException("Could not update group "+localGroupClone); + } + } + + } + //call command that corresponds to the change that was made + } + //this will also handle removes, since incoming pdpGroup has no policies internally, we are just going to add them all in from the db + private boolean updateGroupPoliciesInFileSystem(OnapPDPGroup pdpGroup,OnapPDPGroup oldPdpGroup, GroupEntity groupRecord, PolicyDBDaoTransaction transaction) throws PAPException{ + if(!(pdpGroup instanceof StdPDPGroup)){ + throw new PAPException("group is not a StdPDPGroup"); + } + StdPDPGroup group = (StdPDPGroup)pdpGroup; + //this must always be true since we don't explicitly know when a delete is occuring + boolean didUpdate = true; + HashMap currentPolicySet = new HashMap(oldPdpGroup.getPolicies().size()); + HashSet newPolicySet = new HashSet<>(); + for(PDPPolicy pdpPolicy : oldPdpGroup.getPolicies()){ + currentPolicySet.put(pdpPolicy.getId(), pdpPolicy); + } + for(PolicyEntity policy : groupRecord.getPolicies()){ + String pdpPolicyName = getPdpPolicyName(policy.getPolicyName(), policy.getScope()); + if(group.getPolicy(pdpPolicyName) == null){ + didUpdate = true; + if(currentPolicySet.containsKey(pdpPolicyName)){ + newPolicySet.add(currentPolicySet.get(pdpPolicyName)); + } else{ + InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes()); + group.copyPolicyToFile(pdpPolicyName,policyStream); + ((StdPDPPolicy)(group.getPolicy(pdpPolicyName))).setName(removeExtensionAndVersionFromPolicyName(policy.getPolicyName())); + try { + policyStream.close(); + } catch (IOException e) { + didUpdate = false; + PolicyLogger.error(e.getMessage() +e); + } + } + } + } + if(didUpdate){ + newPolicySet.addAll(group.getPolicies()); + group.setPolicies(newPolicySet); + } + return didUpdate; + + } + private String removeExtensionAndVersionFromPolicyName(String originalPolicyName){ + return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0]; + } + + /** + * Splits apart the policy name and version from a policy file path + * @param originalPolicyName: a policy file name ex: Config_policy.2.xml + * @return An array [0]: The policy name, [1]: the policy version, as a string + */ + private String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName){ + String policyName = originalPolicyName; + String[] nameAndVersion = new String[2]; + try{ + policyName = removeFileExtension(policyName); + nameAndVersion[0] = policyName.substring(0,policyName.lastIndexOf('.')); + if(isNullOrEmpty(nameAndVersion[0])){ + throw new Exception(); + } + } catch(Exception e){ + nameAndVersion[0] = originalPolicyName; + } + try{ + nameAndVersion[1] = policyName.substring(policyName.lastIndexOf('.')+1); + if(isNullOrEmpty(nameAndVersion[1])){ + throw new Exception(); + } + } catch(Exception e){ + nameAndVersion[1] = "1"; + } + return nameAndVersion; + } + + private void handleIncomingPdpChange(String url, String pdpId, PolicyDBDaoTransaction transaction) throws PAPException{ + //get pdp + long pdpIdLong = -1; + try{ + pdpIdLong = Long.parseLong(pdpId); + }catch(NumberFormatException e){ + throw new IllegalArgumentException("pdpId "+pdpId+" cannot be parsed into a long"); + } + PdpEntity pdpRecord = null; + try{ + pdpRecord = transaction.getPdp(pdpIdLong); + }catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get pdp record with transaction.getPdp("+pdpIdLong+");"); + throw new PAPException("Could not get local pdp "+pdpIdLong); + } + if(pdpRecord == null){ + throw new PersistenceException("The pdpRecord returned is null"); + } + PDP localPdp = null; + try { + localPdp = papEngine.getPDP(pdpRecord.getPdpId()); + } catch (PAPException e) { + logger.warn("Caught PAPException trying to get local pdp with papEngine.getPDP("+pdpId+");",e); + } + if(localPdp != null && pdpRecord.isDeleted()){ + try { + papEngine.removePDP((OnapPDP) localPdp); + } catch (PAPException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to get remove pdp with papEngine.removePDP("+localPdp+");"); + throw new PAPException("Could not remove pdp "+pdpId); + } + } + else if(localPdp == null){ + //add new pdp + //get group + OnapPDPGroup localGroup = null; + try { + localGroup = papEngine.getGroup(pdpRecord.getGroup().getGroupId()); + } catch (PAPException e1) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "Caught PAPException trying to get local group to add pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); + throw new PAPException("Could not get local group"); + } + try { + papEngine.newPDP(pdpRecord.getPdpId(), localGroup, pdpRecord.getPdpName(), pdpRecord.getDescription(), pdpRecord.getJmxPort()); + } catch (NullPointerException | PAPException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to create pdp with papEngine.newPDP("+pdpRecord.getPdpId()+", "+localGroup+", "+pdpRecord.getPdpName()+", "+pdpRecord.getDescription()+", "+pdpRecord.getJmxPort()+");"); + throw new PAPException("Could not create pdp "+pdpRecord); + } + } else { + boolean needToUpdate = false; + if(!stringEquals(localPdp.getId(),pdpRecord.getPdpId()) || !stringEquals(localPdp.getName(),pdpRecord.getPdpName())){ + //again, we don't want to change the id, the papEngine will do this + localPdp.setName(pdpRecord.getPdpName()); + needToUpdate = true; + } + if(!stringEquals(localPdp.getDescription(),pdpRecord.getDescription())){ + localPdp.setDescription(pdpRecord.getDescription()); + needToUpdate = true; + } + String localPdpGroupId = null; + try{ + localPdpGroupId = papEngine.getPDPGroup((OnapPDP) localPdp).getId(); + } catch(PAPException e){ + //could be null or something, just warn at this point + logger.warn("Caught PAPException trying to get id of local group that pdp is in with localPdpGroupId = papEngine.getPDPGroup(localPdp).getId();",e); + } + if(!stringEquals(localPdpGroupId,pdpRecord.getGroup().getGroupId())){ + OnapPDPGroup newPdpGroup = null; + try{ + newPdpGroup = papEngine.getGroup(pdpRecord.getGroup().getGroupId()); + }catch(PAPException e){ + //ok, now we have an issue. Time to stop things + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to get id of local group to move pdp to with papEngine.getGroup(pdpRecord.getGroup().getGroupId());"); + throw new PAPException("Could not get local group"); + } + try{ + papEngine.movePDP((OnapPDP) localPdp, newPdpGroup); + }catch(PAPException e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to move pdp with papEngine.movePDP(localPdp, newPdpGroup);"); + throw new PAPException("Could not move pdp "+localPdp); + } + } + if(((PdpEntity) localPdp).getJmxPort() != pdpRecord.getJmxPort()){ + ((PdpEntity) localPdp).setJmxPort(pdpRecord.getJmxPort()); + needToUpdate = true; + } + if(needToUpdate){ + try { + papEngine.updatePDP((OnapPDP) localPdp); + } catch (PAPException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PAPException trying to update pdp with papEngine.updatePdp("+localPdp+");"); + throw new PAPException("Could not update pdp "+localPdp); + } + } + } + //compare to local situation + //call command to update + } + private void handleIncomingPolicyChange(String url, String policyId,String oldPathString){ + String policyName = null; + EntityManager em = emf.createEntityManager(); + Query getPolicyEntityQuery = em.createNamedQuery("PolicyEntity.FindById"); + getPolicyEntityQuery.setParameter("id", Long.valueOf(policyId)); + + @SuppressWarnings("unchecked") + List policies = getPolicyEntityQuery.getResultList(); + PolicyEntity policy = null; + if (!policies.isEmpty()){ + policy = policies.get(0); + } + String action = "unknown action"; + try { + if(policy != null){ + policyName = policy.getPolicyName(); + logger.debug("Deleting Policy: " + policy.getPolicyName()); + action = "delete"; + Path subFile = null; + + if (policy.getConfigurationData()!= null){ + subFile = getPolicySubFile(policy.getConfigurationData().getConfigurationName(), "Config"); + }else if(policy.getActionBodyEntity()!= null){ + subFile = getPolicySubFile(policy.getActionBodyEntity().getActionBodyName(), "Action"); + } + + if(subFile != null){ + Files.deleteIfExists(subFile); + } + if (policy.getConfigurationData()!= null){ + writePolicySubFile(policy, "Config"); + }else if(policy.getActionBodyEntity()!= null){ + writePolicySubFile(policy, "Action"); + } + } + } catch (IOException e1) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "Error occurred while performing [" + action + "] of Policy File: " + policyName); + } + } + + private String getPdpPolicyName(String name, String scope){ + String finalName = ""; + finalName += scope; + finalName += "."; + finalName += removeFileExtension(name); + finalName += ".xml"; + return finalName; + } + private String removeFileExtension(String fileName){ + return fileName.substring(0, fileName.lastIndexOf('.')); + } + + private Path getPolicySubFile(String filename, String subFileType){ + logger.debug("getPolicySubFile(" + filename + ", " + subFileType + ")"); + Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS).toString(), subFileType); + File file = null; + + filename = FilenameUtils.removeExtension(filename); + + for(File tmpFile : filePath.toFile().listFiles()){ + if (FilenameUtils.removeExtension(tmpFile.getName()).equals(filename)){ + file = tmpFile; + } + } + + Path finalPath = null; + if (file!= null){ + finalPath = Paths.get(file.getAbsolutePath()); + } + + logger.debug("end of getPolicySubFile: " + finalPath); + return finalPath; + } + + private boolean writePolicySubFile(PolicyEntity policy, String policyType){ + logger.info("writePolicySubFile with policyName[" + policy.getPolicyName() + "] and policyType[" + policyType + "]"); + String type = null; + String subTypeName = null; + String subTypeBody = null; + if (policyType.equalsIgnoreCase("config")){ + type = "Config"; + subTypeName = FilenameUtils.removeExtension(policy.getConfigurationData().getConfigurationName()); + subTypeBody = policy.getConfigurationData().getConfigBody(); + + String configType = policy.getConfigurationData().getConfigType(); + + + if (configType != null) { + if (configType.equals(JSON_CONFIG)) { + subTypeName = subTypeName + ".json"; + } + if (configType.equals(XML_CONFIG)) { + subTypeName = subTypeName + ".xml"; + } + if (configType.equals(PROPERTIES_CONFIG)) { + subTypeName = subTypeName + ".properties"; + } + if (configType.equals(OTHER_CONFIG)) { + subTypeName = subTypeName + ".txt"; + } + } + + }else if (policyType.equalsIgnoreCase("action")){ + type = "Action"; + subTypeName = policy.getActionBodyEntity().getActionBodyName(); + subTypeBody = policy.getActionBodyEntity().getActionBody(); + + + } + Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS).toString(), type); + + if(subTypeBody == null){ + subTypeBody = ""; + } + boolean success = false; + try { + Files.deleteIfExists(Paths.get(filePath.toString(), subTypeName)); + File file = Paths.get(filePath.toString(),subTypeName).toFile(); + file.createNewFile(); + FileWriter fileWriter = new FileWriter(file, false); // false to overwrite + fileWriter.write(subTypeBody); + fileWriter.close(); + success = true; + + } catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Exception occured while creating Configuration File for Policy : " + policy.getPolicyName()); + } + + return success; + + } + + public void auditLocalDatabase(PAPPolicyEngine papEngine2){ + logger.debug("PolicyDBDao.auditLocalDatabase() is called"); + try{ + deleteAllGroupTables(); + auditGroups(papEngine2); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "auditLocalDatabase() error"); + logger.error("Exception Occured"+e); + } + } + + public void deleteAllGroupTables(){ + logger.debug("PolicyDBDao.deleteAllGroupTables() called"); + EntityManager em = emf.createEntityManager(); + em.getTransaction().begin(); + + Query deletePdpEntityEntityTableUpdate = em.createNamedQuery("PdpEntity.deleteAll"); + deletePdpEntityEntityTableUpdate.executeUpdate(); + + Query deleteGroupEntityTableUpdate = em.createNamedQuery("GroupEntity.deleteAll"); + deleteGroupEntityTableUpdate.executeUpdate(); + + em.getTransaction().commit(); + em.close(); + } + + @SuppressWarnings("unchecked") + public void auditGroups(PAPPolicyEngine papEngine2){ + logger.debug("PolicyDBDao.auditGroups() called"); + + EntityManager em = emf.createEntityManager(); + em.getTransaction().begin(); + final String AUDIT_STR = "Audit"; + try{ + + Set groups = papEngine2.getOnapPDPGroups(); + + for (OnapPDPGroup grp : groups){ + try{ + GroupEntity groupEntity = new GroupEntity(); + em.persist(groupEntity); + groupEntity.setGroupName(grp.getName()); + groupEntity.setDescription(grp.getDescription()); + groupEntity.setDefaultGroup(grp.isDefaultGroup()); + groupEntity.setCreatedBy(AUDIT_STR); + groupEntity.setGroupId(createNewPDPGroupId(grp.getId())); + groupEntity.setModifiedBy(AUDIT_STR); + Set pdps = grp.getOnapPdps(); + + for(OnapPDP pdp : pdps){ + PdpEntity pdpEntity = new PdpEntity(); + em.persist(pdpEntity); + pdpEntity.setGroup(groupEntity); + pdpEntity.setJmxPort(pdp.getJmxPort()); + pdpEntity.setPdpId(pdp.getId()); + pdpEntity.setPdpName(pdp.getName()); + pdpEntity.setModifiedBy(AUDIT_STR); + pdpEntity.setCreatedBy(AUDIT_STR); + + } + + Set policies = grp.getPolicies(); + + for(PDPPolicy policy : policies){ + try{ + String[] stringArray = getNameScopeAndVersionFromPdpPolicy(policy.getId()); + List policyEntityList; + Query getPolicyEntitiesQuery = em.createNamedQuery("PolicyEntity.findByNameAndScope"); + getPolicyEntitiesQuery.setParameter("name", stringArray[0]); + getPolicyEntitiesQuery.setParameter("scope", stringArray[1]); + + policyEntityList = getPolicyEntitiesQuery.getResultList(); + PolicyEntity policyEntity = null; + if(!policyEntityList.isEmpty()){ + policyEntity = policyEntityList.get(0); + } + if(policyEntity != null){ + groupEntity.addPolicyToGroup(policyEntity); + } + }catch(Exception e2){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "Exception auditGroups inner catch"); + } + } + }catch(Exception e1){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "Exception auditGroups middle catch"); + } + } + }catch(Exception e){ + em.getTransaction().rollback(); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Exception auditGroups outer catch"); + em.close(); + return; + } + + em.getTransaction().commit(); + em.close(); + + } + + private String getConfigFile(String filename, PolicyRestAdapter policy){ + if(policy == null){ + return getConfigFile(filename, (String)null); + } + return getConfigFile(filename, policy.getConfigType()); + } + //copied from ConfigPolicy.java and modified + // Here we are adding the extension for the configurations file based on the + // config type selection for saving. + private String getConfigFile(String filename, String configType) { + logger.debug("getConfigFile(String filename, String scope, String configType) as getConfigFile("+filename+", "+configType+") called"); + filename = FilenameUtils.removeExtension(filename); + String id = configType; + + if (id != null) { + if (id.equals(ConfigPolicy.JSON_CONFIG) || id.contains("Firewall")) { + filename = filename + ".json"; + } + if (id.equals(ConfigPolicy.XML_CONFIG)) { + filename = filename + ".xml"; + } + if (id.equals(ConfigPolicy.PROPERTIES_CONFIG)) { + filename = filename + ".properties"; + } + if (id.equals(ConfigPolicy.OTHER_CONFIG)) { + filename = filename + ".txt"; + } + } + return filename; + } + + private String[] getNameScopeAndVersionFromPdpPolicy(String fileName){ + String[] splitByDots = fileName.split("\\."); + if(splitByDots.length < 3){ + //should we throw something + return null; + } + String policyName = splitByDots[splitByDots.length-3]; + String version = splitByDots[splitByDots.length-2]; + //policy names now include version + String scope = ""; + for(int i=0;i 0){ + scope = scope.substring(1); + } + String[] returnArray = new String[3]; + returnArray[0] = policyName + "." + version + ".xml"; + returnArray[2] = version; + returnArray[1] = scope; + return returnArray; + } + + //copied from StdEngine.java + public static String createNewPDPGroupId(String name) { + String id = name; + // replace "bad" characters with sequences that will be ok for file names and properties keys. + id = id.replace(" ", "_sp_"); + id = id.replace("\t", "_tab_"); + id = id.replace("\\", "_bksl_"); + id = id.replace("/", "_sl_"); + id = id.replace(":", "_col_"); + id = id.replace("*", "_ast_"); + id = id.replace("?", "_q_"); + id = id.replace("\"", "_quo_"); + id = id.replace("<", "_lt_"); + id = id.replace(">", "_gt_"); + id = id.replace("|", "_bar_"); + id = id.replace("=", "_eq_"); + id = id.replace(",", "_com_"); + id = id.replace(";", "_scom_"); + + return id; + } + + /** + * Checks if any of the given strings are empty or null + * @param strings One or more Strings (or nulls) to check if they are null or empty + * @return true if one or more of the given strings are empty or null + */ + private static boolean isNullOrEmpty(String... strings){ + for(String s : strings){ + if(!(s instanceof String)){ + return true; + } + if(s.equals("")){ + return true; + } + } + return false; + } + + + private class PolicyDBDaoTransactionInstance implements PolicyDBDaoTransaction { + private EntityManager em; + private final Object emLock = new Object(); + long policyId; + long groupId; + long pdpId; + String newGroupId; + private boolean operationRun = false; + private final Thread transactionTimer; + + private PolicyDBDaoTransactionInstance(){ + //call the constructor with arguments + this(Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)), + Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT))); + } + //timeout is how long the transaction can sit before rolling back + //wait time is how long to wait for the transaction to start before throwing an exception + private PolicyDBDaoTransactionInstance(int transactionTimeout, int transactionWaitTime){ + if(logger.isDebugEnabled()){ + logger.debug("\n\nPolicyDBDaoTransactionInstance() as PolicyDBDaoTransactionInstance() called:" + + "\n transactionTimeout = " + transactionTimeout + + "\n transactionWaitTime = " + transactionWaitTime + "\n\n"); + } + this.em = emf.createEntityManager(); + policyId = -1; + groupId = -1; + pdpId = -1; + newGroupId = null; + synchronized(emLock){ + try{ + startTransactionSynced(this.em,transactionWaitTime); + } catch(Exception e){ + throw new PersistenceException("Could not lock transaction within "+transactionWaitTime+" milliseconds"); + } + } + class TransactionTimer implements Runnable { + + private int sleepTime; + public TransactionTimer(int timeout){ + this.sleepTime = timeout; + } + @Override + public void run() { + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nTransactionTimer.run() - SLEEPING: " + + "\n sleepTime (ms) = " + sleepTime + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + try { + Thread.sleep(sleepTime); + } catch (InterruptedException e) { + //probably, the transaction was completed, the last thing we want to do is roll back + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nTransactionTimer.run() - WAKE Interrupt: " + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + return; + } + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nTransactionTimer.run() - WAKE Timeout: " + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + rollbackTransaction(); + } + + } + + transactionTimer = new Thread(new TransactionTimer(transactionTimeout),"transactionTimerThread"); + transactionTimer.start(); + + + } + + private void checkBeforeOperationRun(){ + checkBeforeOperationRun(false); + } + private void checkBeforeOperationRun(boolean justCheckOpen){ + if(!isTransactionOpen()){ + PolicyLogger.error("There is no transaction currently open"); + throw new IllegalStateException("There is no transaction currently open"); + } + if(operationRun && !justCheckOpen){ + PolicyLogger.error("An operation has already been performed and the current transaction should be committed"); + throw new IllegalStateException("An operation has already been performed and the current transaction should be committed"); + } + operationRun = true; + } + @Override + public void commitTransaction() { + synchronized(emLock){ + logger.debug("commitTransaction() as commitTransaction() called"); + if(!isTransactionOpen()){ + logger.warn("There is no open transaction to commit"); + try{ + em.close(); + } catch(Exception e){ + logger.error("Exception Occured"+e); + } + return; + } + try{ + em.getTransaction().commit(); + } catch(RollbackException e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught RollbackException on em.getTransaction().commit()"); + throw new PersistenceException("The commit failed. Message:\n"+e.getMessage()); + } + em.close(); + // need to revisit + if(policyId >= 0){ + if(newGroupId != null){ + try{ + notifyOthers(policyId,POLICY_NOTIFICATION,newGroupId); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on notifyOthers("+policyId+","+POLICY_NOTIFICATION+","+newGroupId+")"); + } + } else { + try{ + notifyOthers(policyId,POLICY_NOTIFICATION); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on notifyOthers("+policyId+","+POLICY_NOTIFICATION+")"); + } + } + } + if(groupId >= 0){ + //we don't want commit to fail just because this does + if(newGroupId != null){ + try{ + notifyOthers(groupId,GROUP_NOTIFICATION,newGroupId); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on notifyOthers("+groupId+","+GROUP_NOTIFICATION+","+newGroupId+")"); + } + } else { + try{ + notifyOthers(groupId,GROUP_NOTIFICATION); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on notifyOthers("+groupId+","+GROUP_NOTIFICATION+")"); + } + } + } + if(pdpId >= 0){ + //we don't want commit to fail just because this does + try{ + notifyOthers(pdpId,PDP_NOTIFICATION); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on notifyOthers("+pdpId+","+PDP_NOTIFICATION+")"); + } + } + } + if(transactionTimer instanceof Thread){ + transactionTimer.interrupt(); + } + } + + @Override + public void rollbackTransaction() { + logger.debug("rollbackTransaction() as rollbackTransaction() called"); + synchronized(emLock){ + if(isTransactionOpen()){ + + try{ + em.getTransaction().rollback(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not rollback transaction"); + } + try{ + em.close(); + }catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not close EntityManager"); + } + + } else { + try{ + em.close(); + }catch(Exception e){ + logger.warn("Could not close already closed transaction"); + } + } + + } + if(transactionTimer instanceof Thread){ + transactionTimer.interrupt(); + } + + + } + + private void createPolicy(PolicyRestAdapter policy, String username, String policyScope, String policyName, String policyDataString) { + logger.debug("createPolicy(PolicyRestAdapter policy, String username, String policyScope, String policyName, String policyDataString) as createPolicy("+policy+", "+username+", "+policyScope+", "+policyName+", "+policyDataString+") called"); + synchronized(emLock){ + checkBeforeOperationRun(); + String configName = policyName; + if(policyName.contains("Config_")){ + policyName = policyName.replace(".Config_", ":Config_"); + }else if(policyName.contains("Action_")){ + policyName = policyName.replace(".Action_", ":Action_"); + }else if(policyName.contains("Decision_")){ + policyName = policyName.replace(".Decision_", ":Decision_"); + } + policyName = policyName.split(":")[1]; + Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName"); + createPolicyQuery.setParameter("scope", policyScope); + createPolicyQuery.setParameter("policyName", policyName); + List createPolicyQueryList = createPolicyQuery.getResultList(); + PolicyEntity newPolicyEntity; + boolean update; + if(createPolicyQueryList.size() < 1){ + newPolicyEntity = new PolicyEntity(); + update = false; + } else if(createPolicyQueryList.size() > 1){ + PolicyLogger.error("Somehow, more than one policy with the same scope, name, and deleted status were found in the database"); + throw new PersistenceException("Somehow, more than one policy with the same scope, name, and deleted status were found in the database"); + } else { + newPolicyEntity = (PolicyEntity)createPolicyQueryList.get(0); + update = true; + } + + ActionBodyEntity newActionBodyEntity = null; + if(policy.getPolicyType().equals("Action")){ + boolean abupdate = false; + if(newPolicyEntity.getActionBodyEntity() == null){ + newActionBodyEntity = new ActionBodyEntity(); + }else{ + newActionBodyEntity = em.find(ActionBodyEntity.class, newPolicyEntity.getActionBodyEntity().getActionBodyId()); + abupdate = true; + } + + if(newActionBodyEntity != null){ + if(!abupdate){ + em.persist(newActionBodyEntity); + } + //build the file path + //trim the .xml off the end + String policyNameClean = FilenameUtils.removeExtension(configName); + String actionBodyName = policyNameClean + ".json"; + Path actionBodyPath = Paths.get(Webapps.getActionHome(), actionBodyName); + if(logger.isDebugEnabled()){ + logger.debug("\nPolicyDBDao.createPolicy" + + "\n actionBodyPath = " + actionBodyPath); + } + //get the action body + String actionBodyString = null; + String actionBodyPathStr = null; + InputStream fileContentStream = null; + + if (Files.exists(actionBodyPath)) { + try { + actionBodyPathStr = (actionBodyPath != null ? actionBodyPath.toString() : null); + fileContentStream = new FileInputStream(actionBodyPathStr); + actionBodyString = IOUtils.toString(fileContentStream); + if(logger.isDebugEnabled()){ + logger.debug("\nPolicyDBDao.createPolicy" + + "\n actionBodyPathStr = " + actionBodyPathStr + + "\n actionBodyString = " + actionBodyString); + } + } catch (FileNotFoundException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught FileNotFoundException on new actionBodyPathStr FileInputStream("+actionBodyPathStr+")"); + throw new IllegalArgumentException("The actionBodyPathStr file path " + actionBodyPathStr + " does not exist" + + "\nEXCEPTION: " + e); + } catch(IOException e2){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "Caught IOException on actionBodyPath newIOUtils.toString("+fileContentStream+")"); + throw new IllegalArgumentException("The actionBodyPath file path cannot be read" + fileContentStream + + "\nEXCEPTION: " + e2); + } finally { + IOUtils.closeQuietly(fileContentStream); + } + + if(actionBodyString == null){ + throw new IllegalArgumentException("The file path (" + actionBodyPathStr + ") cannot be read"); + } + } else { + actionBodyString = "{}"; + } + + newActionBodyEntity.setActionBody(actionBodyString); + newActionBodyEntity.setActionBodyName(actionBodyName); + newActionBodyEntity.setModifiedBy("PolicyDBDao.createPolicy()"); + newActionBodyEntity.setDeleted(false); + if(!abupdate){ + newActionBodyEntity.setCreatedBy("PolicyDBDao.createPolicy()"); + } + if(logger.isDebugEnabled()){ + logger.debug("\nPolicyDBDao.createPolicy" + + "\n newActionBodyEntity.getActionBody() = " + newActionBodyEntity.getActionBody() + + "\n newActionBodyEntity.getActionBodyName() = " + newActionBodyEntity.getActionBodyName() + + "\n newActionBodyEntity.getModifiedBy() = " + newActionBodyEntity.getModifiedBy() + + "\n newActionBodyEntity.getCreatedBy() = " + newActionBodyEntity.getCreatedBy() + + "\n newActionBodyEntity.isDeleted() = " + newActionBodyEntity.isDeleted() + + "\n FLUSHING to DB"); + } + //push the actionBodyEntity to the DB + em.flush(); + }else{ + //newActionBodyEntity == null + //We have a actionBody in the policy but we found no actionBody in the DB + String msg = "\n\nPolicyDBDao.createPolicy - Incoming Action policy had an " + + "actionBody, but it could not be found in the DB for update." + + "\n policyScope = " + policyScope + + "\n policyName = " + policyName + "\n\n"; + PolicyLogger.error("PolicyDBDao.createPolicy - Incoming Action policy had an actionBody, but it could not be found in the DB for update: policyName = " + policyName); + throw new IllegalArgumentException(msg); + } + } + + ConfigurationDataEntity newConfigurationDataEntity; + if(policy.getPolicyType().equals("Config")){ + boolean configUpdate; + if(newPolicyEntity.getConfigurationData() == null){ + newConfigurationDataEntity = new ConfigurationDataEntity(); + configUpdate = false; + } else { + newConfigurationDataEntity = em.find(ConfigurationDataEntity.class, newPolicyEntity.getConfigurationData().getConfigurationDataId()); + configUpdate = true; + } + + if(newConfigurationDataEntity != null){ + if(!configUpdate){ + em.persist(newConfigurationDataEntity); + } + if(!stringEquals(newConfigurationDataEntity.getConfigurationName(),getConfigFile(configName,policy))){ + newConfigurationDataEntity.setConfigurationName(getConfigFile(configName,policy)); + } + if(newConfigurationDataEntity.getConfigType() == null || !newConfigurationDataEntity.getConfigType().equals(policy.getConfigType())){ + newConfigurationDataEntity.setConfigType(policy.getConfigType()); + } + if(!configUpdate){ + newConfigurationDataEntity.setCreatedBy(username); + } + if(newConfigurationDataEntity.getModifiedBy() == null || !newConfigurationDataEntity.getModifiedBy().equals(username)){ + newConfigurationDataEntity.setModifiedBy(username); + } + if(newConfigurationDataEntity.getDescription() == null || !newConfigurationDataEntity.getDescription().equals("")){ + newConfigurationDataEntity.setDescription(""); + } + if(newConfigurationDataEntity.getConfigBody() == null || newConfigurationDataEntity.getConfigBody().isEmpty() || + (!newConfigurationDataEntity.getConfigBody().equals(policy.getConfigBodyData()))){ + //hopefully one of these won't be null + if(policy.getConfigBodyData() == null || policy.getConfigBodyData().isEmpty()){ + newConfigurationDataEntity.setConfigBody(policy.getJsonBody()); + }else{ + newConfigurationDataEntity.setConfigBody(policy.getConfigBodyData()); + } + } + if(newConfigurationDataEntity.isDeleted() == true){ + newConfigurationDataEntity.setDeleted(false); + } + + em.flush(); + }else{ + //We have a configurationData body in the policy but we found no configurationData body in the DB + String msg = "\n\nPolicyDBDao.createPolicy - Incoming Config policy had a " + + "configurationData body, but it could not be found in the DB for update." + + "\n policyScope = " + policyScope + + "\n policyName = " + policyName + "\n\n"; + PolicyLogger.error("PolicyDBDao.createPolicy - Incoming Config policy had a configurationData body, but it could not be found in the DB for update: policyName = " + policyName); + throw new IllegalArgumentException(msg); + } + + } else { + newConfigurationDataEntity = null; + } + if(!update){ + em.persist(newPolicyEntity); + } + + policyId = newPolicyEntity.getPolicyId(); + + if(!stringEquals(newPolicyEntity.getPolicyName(),policyName)){ + newPolicyEntity.setPolicyName(policyName); + } + if(!stringEquals(newPolicyEntity.getCreatedBy(),username)){ + newPolicyEntity.setCreatedBy(username); + } + if(!stringEquals(newPolicyEntity.getDescription(),policy.getPolicyDescription())){ + newPolicyEntity.setDescription(policy.getPolicyDescription()); + } + if(!stringEquals(newPolicyEntity.getModifiedBy(),username)){ + newPolicyEntity.setModifiedBy(username); + } + if(!stringEquals(newPolicyEntity.getPolicyData(),policyDataString)){ + newPolicyEntity.setPolicyData(policyDataString); + } + if(!stringEquals(newPolicyEntity.getScope(),policyScope)){ + newPolicyEntity.setScope(policyScope); + } + if(newPolicyEntity.isDeleted() == true){ + newPolicyEntity.setDeleted(false); + } + newPolicyEntity.setConfigurationData(newConfigurationDataEntity); + newPolicyEntity.setActionBodyEntity(newActionBodyEntity); + + + em.flush(); + this.policyId = newPolicyEntity.getPolicyId(); + } + + return; + } + + @SuppressWarnings("unused") + public PolicyEntity getPolicy(int policyID){ + return getPolicy(policyID,null,null); + } + public PolicyEntity getPolicy(String policyName,String scope){ + return getPolicy(-1,policyName,scope); + } + private PolicyEntity getPolicy(int policyID, String policyName,String scope){ + logger.debug("getPolicy(int policyId, String policyName) as getPolicy("+policyID+","+policyName+") called"); + if(policyID < 0 && isNullOrEmpty(policyName,scope)){ + throw new IllegalArgumentException("policyID must be at least 0 or policyName must be not null or blank"); + } + + synchronized(emLock){ + checkBeforeOperationRun(true); + //check if group exists + String policyId; + Query policyQuery; + if(!isNullOrEmpty(policyName,scope)){ + policyId = policyName; + policyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:name AND p.scope=:scope"); + policyQuery.setParameter("name", policyId); + policyQuery.setParameter("scope", scope); + } else{ + policyId = String.valueOf(policyID); + policyQuery = em.createNamedQuery("PolicyEntity.FindById"); + policyQuery.setParameter("id", policyId); + } + List policyQueryList; + try{ + policyQueryList = policyQuery.getResultList(); + }catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get policy with policyQuery.getResultList()"); + throw new PersistenceException("Query failed trying to get policy "+policyId); + } + if(policyQueryList.size() < 1){ + PolicyLogger.error("Policy does not exist with id "+policyId); + throw new PersistenceException("Group policy is being added to does not exist with id "+policyId); + } else if(policyQueryList.size() > 1){ + PolicyLogger.error("Somehow, more than one policy with the id "+policyId+" were found in the database"); + throw new PersistenceException("Somehow, more than one policy with the id "+policyId+" were found in the database"); + } + return (PolicyEntity)policyQueryList.get(0); + } + } + + @Override + public void renamePolicy(String oldPath, String newPath,String username){ +/* String[] oldPolicy = getScopeAndNameAndType(oldPath); + String[] newPolicy = getScopeAndNameAndType(newPath); + if(oldPolicy == null || newPolicy == null){ + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW+"Could not parse one or more of the path names: " + +oldPath+", "+newPath); + throw new IllegalArgumentException("Could not parse one or more of the path names"); + } + synchronized (emLock) { + checkBeforeOperationRun(); + + PolicyEntity existingPolicy; + boolean existingPolicyDeleted = false; + List groups = null; + try{ + existingPolicy = getPolicy(newPolicy[1],newPolicy[0]); + } catch(Exception e){ + existingPolicy = null; + } + if(existingPolicy != null && !existingPolicy.isDeleted()){ + logger.error("The policy named "+existingPolicy.getPolicyName()+" already exists, cannot rename policy: "+newPolicy); + throw new IllegalArgumentException("The policy named "+existingPolicy.getPolicyName()+" already exists, cannot rename policy: "+newPolicy); + } else if(existingPolicy != null && existingPolicy.isDeleted()){ + try{ + Query getGroups = em.createQuery("SELECT g FROM GroupEntity g JOIN g.policies p WHERE p.policyId=:pid"); + + getGroups.setParameter("pid", existingPolicy.getPolicyId()); + groups = getGroups.getResultList(); + }catch(Exception e){ + groups = new LinkedList<>(); + } + for(Object o : groups){ + GroupEntity group = (GroupEntity)o; + group.removePolicyFromGroup(existingPolicy); + } + try{ + em.flush(); + }catch(Exception e){ + logger.error("Error while removing the policy from groups: "+existingPolicy.getPolicyName()); + } + try{ + em.remove(existingPolicy); + em.flush(); + }catch(Exception e){ + logger.error("Could not remove the existing deleted policy: "+existingPolicy.getPolicyName()); + } + existingPolicyDeleted = true; + //create the new policy + //for each of the groups, add the new policy + } + + PolicyEntity policyToRename; + try{ + policyToRename = getPolicy(oldPolicy[1],oldPolicy[0]); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "PolicyDBDao", "Could not get policy record to rename: " + +oldPolicy[1]); + throw new PersistenceException("Could not get policy record to rename"); + } + String policyDataString = null; + InputStream fileContentStream = null; + String policyFilePath = Paths.get(oldPath).toAbsolutePath().toString(); + //I want to try the old path first, then if it doesn't work, try the new path + for(int i=0;i<2;i++){ + try { + fileContentStream = new FileInputStream(policyFilePath); + policyDataString = IOUtils.toString(fileContentStream); + } catch (FileNotFoundException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught FileNotFoundException on new FileInputStream("+policyFilePath+")"); + //if we can't find the oldPath, we'll try the new path + if(i == 0){ + policyFilePath = Paths.get(newPath).toAbsolutePath().toString(); + continue; + } + throw new IllegalArgumentException("The file path does not exist"); + } catch(IOException e2){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e2, "PolicyDBDao", "Caught IOException on newIOUtils.toString("+fileContentStream+")"); + throw new IllegalArgumentException("The file path cannot be read"); + } finally { + IOUtils.closeQuietly(fileContentStream); + } + if(policyDataString == null){ + throw new IllegalArgumentException("The file path cannot be read"); + } + //escape the loop + i=2; + } + policyToRename.setPolicyName(newPolicy[1]); + policyToRename.setPolicyData(policyDataString); + policyToRename.setScope(newPolicy[0]); + policyToRename.setModifiedBy(username); + if(policyToRename.getConfigurationData() != null){ + String configType = policyToRename.getConfigurationData().getConfigType(); + policyToRename.getConfigurationData().setConfigurationName(getConfigFile(newPolicy[1], configType)); + policyToRename.getConfigurationData().setModifiedBy(username); + } + if(policyToRename.getActionBodyEntity() != null){ + String newActionName = newPolicy[0]+"."+removeFileExtension(newPolicy[1])+".json"; + policyToRename.getActionBodyEntity().setActionBodyName(newActionName); + policyToRename.getActionBodyEntity().setModifiedBy(username); + } + if(existingPolicyDeleted){ + for(Object o : groups){ + + GroupEntity group = (GroupEntity)o; + group.addPolicyToGroup(policyToRename); + } + } + em.flush(); + this.policyId = policyToRename.getPolicyId(); + this.newGroupId = oldPath; + }*/ + } + + @Override + public GroupEntity getGroup(long groupKey){ + logger.debug("getGroup(int groupKey) as getGroup("+groupKey+") called"); + if(groupKey < 0){ + throw new IllegalArgumentException("groupKey must be at least 0"); + } + synchronized(emLock){ + checkBeforeOperationRun(true); + //check if group exists + Query groupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupKey=:groupKey"); + groupQuery.setParameter("groupKey", groupKey); + List groupQueryList; + try{ + groupQueryList = groupQuery.getResultList(); + }catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get group with groupQuery.getResultList()"); + throw new PersistenceException("Query failed trying to get group "+groupKey); + } + if(groupQueryList.size() < 1){ + PolicyLogger.error("Group does not exist with groupKey "+groupKey); + throw new PersistenceException("Group does not exist with groupKey "+groupKey); + } else if(groupQueryList.size() > 1){ + PolicyLogger.error("Somehow, more than one group with the groupKey "+groupKey+" were found in the database"); + throw new PersistenceException("Somehow, more than one group with the groupKey "+groupKey+" were found in the database"); + } + return (GroupEntity)groupQueryList.get(0); + } + } + + @Override + public GroupEntity getGroup(String groupId){ + logger.debug("getGroup(String groupId) as getGroup("+groupId+") called"); + if(isNullOrEmpty(groupId)){ + throw new IllegalArgumentException("groupId must not be null or empty"); + } + synchronized(emLock){ + checkBeforeOperationRun(true); + //check if group exists + Query groupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId"); + groupQuery.setParameter("groupId", groupId); + List groupQueryList; + try{ + groupQueryList = groupQuery.getResultList(); + }catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get group with groupQuery.getResultList()"); + throw new PersistenceException("Query failed trying to get group "+groupId); + } + if(groupQueryList.size() < 1){ + PolicyLogger.error("Group does not exist with id "+groupId); + throw new PersistenceException("Group does not exist with id "+groupId); + } else if(groupQueryList.size() > 1){ + PolicyLogger.error("Somehow, more than one group with the id "+groupId+" were found in the database"); + throw new PersistenceException("Somehow, more than one group with the id "+groupId+" were found in the database"); + } + return (GroupEntity)groupQueryList.get(0); + } + } + @Override + public List getPdpsInGroup(long groupKey){ + logger.debug("getPdpsInGroup(int groupKey) as getPdpsInGroup("+groupKey+") called"); + if(groupKey < 0){ + throw new IllegalArgumentException("groupId must not be < 0"); + } + synchronized(emLock){ + checkBeforeOperationRun(true); + Query pdpsQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group"); + pdpsQuery.setParameter("group", getGroup(groupKey)); + return pdpsQuery.getResultList(); + } + } + @Override + public PdpEntity getPdp(long pdpKey){ + logger.debug("getPdp(int pdpKey) as getPdp("+pdpKey+") called"); + if(pdpKey < 0){ + throw new IllegalArgumentException("pdpKey must be at least 0"); + } + synchronized(emLock){ + checkBeforeOperationRun(true); + //check if group exists + Query pdpQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpKey=:pdpKey"); + pdpQuery.setParameter("pdpKey", pdpKey); + List pdpQueryList; + try{ + pdpQueryList = pdpQuery.getResultList(); + }catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get pdp with pdpQuery.getResultList()"); + throw new PersistenceException("Query failed trying to get pdp "+pdpKey); + } + if(pdpQueryList.size() < 1){ + PolicyLogger.error("Pdp does not exist with pdpKey "+pdpKey); + throw new PersistenceException("Pdp does not exist with pdpKey "+pdpKey); + } else if(pdpQueryList.size() > 1){ + PolicyLogger.error("Somehow, more than one pdp with the pdpKey "+pdpKey+" were found in the database"); + throw new PersistenceException("Somehow, more than one pdp with the pdpKey "+pdpKey+" were found in the database"); + } + return (PdpEntity)pdpQueryList.get(0); + } + } + + public void deletePolicy(String policyToDeletes){ + /*synchronized(emLock){ + checkBeforeOperationRun(); + logger.debug("deletePolicy(String policyToDeletes) as deletePolicy("+policyToDeletes+") called"); + String[] scopeNameAndType = getScopeAndNameAndType(policyToDeletes); + if(scopeNameAndType == null){ + throw new IllegalArgumentException("Could not parse file path"); + } + String realScope = scopeNameAndType[0]; + String realName = scopeNameAndType[1]; + Query deletePolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName AND p.deleted=:deleted"); + deletePolicyQuery.setParameter("scope",realScope); + deletePolicyQuery.setParameter("policyName", realName); + deletePolicyQuery.setParameter("deleted", false); + List deletePolicyQueryList = deletePolicyQuery.getResultList(); + if(deletePolicyQueryList.size() < 1){ + logger.warn("The policy being deleted could not be found."); + return; + } else if(deletePolicyQueryList.size() > 1){ + PolicyLogger.error("Somehow, more than one policy with the same scope, name, and deleted status were found in the database"); + throw new PersistenceException("Somehow, more than one policy with the same scope, name, and deleted status were found in the database"); + } else { + PolicyEntity policyToDelete = (PolicyEntity)deletePolicyQueryList.get(0); + policyToDelete.setDeleted(true); + if(policyToDelete.getConfigurationData() != null){ + ConfigurationDataEntity cde = em.find(ConfigurationDataEntity.class,policyToDelete.getConfigurationData().getConfigurationDataId()); + if(cde != null){ + cde.setDeleted(true); + } + } + if(policyToDelete.getActionBodyEntity() != null){ + ActionBodyEntity abe = em.find(ActionBodyEntity.class,policyToDelete.getActionBodyEntity().getActionBodyId()); + if(abe != null){ + abe.setDeleted(true); + } + } + + em.flush(); + this.policyId = policyToDelete.getPolicyId(); + + } + } +*/ + } + + + @Override + public boolean isTransactionOpen() { + logger.debug("isTransactionOpen() as isTransactionOpen() called"); + synchronized(emLock){ + return em.isOpen() && em.getTransaction().isActive(); + } + } + + + @Override + public void clonePolicy(String oldPolicyPath, String newPolicyPath, String username){ + /*String[] oldPolicyData = getScopeAndNameAndType(oldPolicyPath); + String[] newPolicyData = getScopeAndNameAndType(newPolicyPath); + if(oldPolicyData == null || newPolicyData == null){ + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW+"Could not parse one or more of the path names: " + +oldPolicyPath+", "+newPolicyPath); + throw new IllegalArgumentException("Could not parse the oldPolicyPath or newPolicyPath"); + } + PolicyEntity oldPolicy; + try{ + oldPolicy = getPolicy(oldPolicyData[1],oldPolicyData[0]); + }catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "PolicyDBDao", "Could not get policy record to clone: " + +oldPolicyData[1]); + throw new PersistenceException("Could not get policy record to clone"); + } + ConfigurationDataEntity clonedConfig = null; + if(oldPolicy.getConfigurationData() != null){ + clonedConfig = new ConfigurationDataEntity(); + em.persist(clonedConfig); + clonedConfig.setConfigBody(oldPolicy.getConfigurationData().getConfigBody()); + clonedConfig.setConfigType(oldPolicy.getConfigurationData().getConfigType()); + clonedConfig.setCreatedBy(username); + clonedConfig.setConfigurationName(getConfigFile(newPolicyData[1], oldPolicy.getConfigurationData().getConfigType())); + clonedConfig.setDescription(oldPolicy.getConfigurationData().getDescription()); + clonedConfig.setModifiedBy(username); + em.flush(); + } + ActionBodyEntity clonedAction = null; + if(oldPolicy.getActionBodyEntity() != null){ + clonedAction = new ActionBodyEntity(); + em.persist(clonedAction); + clonedAction.setActionBody(oldPolicy.getActionBodyEntity().getActionBody()); + clonedAction.setActionBodyName(newPolicyData[0]+"."+newPolicyData[1]+".json"); + clonedAction.setCreatedBy(username); + clonedAction.setModifiedBy(username); + em.flush(); + } + +*/ + } + + private String processConfigPath(String configPath){ + String webappsPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS); + if(webappsPath == null){ + logger.error("Webapps property does not exist"); + throw new IllegalArgumentException("Webapps property does not exist"); + } + configPath = configPath.replace("$URL", webappsPath); + //make sure the correct slashes are in + try{ + configPath = Paths.get(configPath).toString(); + } catch(InvalidPathException e){ + logger.error("Invalid config path: "+configPath); + throw new IllegalArgumentException("Invalid config path: "+configPath); + } + return configPath; + } + private String readConfigFile(String configPath){ + String configDataString = null; + InputStream configContentStream = null; + try { + configContentStream = new FileInputStream(configPath); + configDataString = IOUtils.toString(configContentStream); + } catch (FileNotFoundException e) { + logger.error("Caught FileNotFoundException on new FileInputStream("+configPath+")",e); + throw new IllegalArgumentException("The config file path does not exist"); + } catch(IOException e2){ + logger.error("Caught IOException on newIOUtils.toString("+configContentStream+")",e2); + throw new IllegalArgumentException("The config file path cannot be read"); + } finally { + IOUtils.closeQuietly(configContentStream); + } + if(configDataString == null){ + throw new IllegalArgumentException("The config file path cannot be read"); + } + return configDataString; + } + + @Override + public void createPolicy(Policy policy, String username){ + InputStream policyXmlStream = null; + try{ + logger.debug("createPolicy(PolicyRestAdapter policy, String username) as createPolicy("+policy+","+username+") called"); + String policyScope = policy.policyAdapter.getDomainDir().replace(File.separator, "."); + //Does not need to be XACMLPolicyWriterWithPapNotify since it is already in the PAP + //and this transaction is intercepted up stream. + String policyDataString; + try { + policyXmlStream = XACMLPolicyWriter.getXmlAsInputStream((PolicyType)policy.getCorrectPolicyDataObject()); + policyDataString = IOUtils.toString(policyXmlStream); + } catch (IOException e) { + policyDataString = "could not read"; + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught IOException on IOUtils.toString("+policyXmlStream+")"); + throw new IllegalArgumentException("Cannot parse the policy xml from the PolicyRestAdapter."); + } + IOUtils.closeQuietly(policyXmlStream); + String configPath = ""; + if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Config")) { + configPath = evaluateXPath("/Policy/Rule/AdviceExpressions/AdviceExpression[contains(@AdviceId,'ID')]/AttributeAssignmentExpression[@AttributeId='URLID']/AttributeValue/text()", policyDataString); + } else if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Action")) { + configPath = evaluateXPath("/Policy/Rule/ObligationExpressions/ObligationExpression[contains(@ObligationId, " +policy.policyAdapter.getActionAttribute()+ ")]/AttributeAssignmentExpression[@AttributeId='body']/AttributeValue/text()", policyDataString); + } + + String prefix = null; + if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Config")) { + + prefix = configPath.substring(configPath.indexOf(policyScope+".")+policyScope.concat(".").length(), configPath.indexOf(policy.policyAdapter.getPolicyName())); + if(isNullOrEmpty(policy.policyAdapter.getConfigBodyData())){ + String configData = ""; + try{ + String newConfigPath = configPath; + try{ + newConfigPath = processConfigPath(newConfigPath); + }catch(Exception e2){ + logger.error("Could not process config path: "+newConfigPath,e2); + } + configData = readConfigFile(newConfigPath); + }catch(Exception e){ + logger.error("Could not read config body data for "+configPath,e); + } + policy.policyAdapter.setConfigBodyData(configData); + } + } else if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Action")) { + prefix = "Action_"; + } else if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Decision")) { + prefix = "Decision_"; + } + + if(!(policy.policyAdapter.getData() instanceof PolicyType)){ + PolicyLogger.error("The data field is not an instance of PolicyType"); + throw new IllegalArgumentException("The data field is not an instance of PolicyType"); + } + String finalName = policyScope + "." + prefix+policy.policyAdapter.getPolicyName()+"."+((PolicyType)policy.policyAdapter.getData()).getVersion()+".xml"; + if(policy.policyAdapter.getConfigType() == null || policy.policyAdapter.getConfigType().equals("")){ + //get the config file extension + String ext = ""; + if (configPath != null) { + if (!configPath.equalsIgnoreCase("")) { + ext = configPath.substring(configPath.lastIndexOf('.'), configPath.length());; + } + } + + if(ext.contains("txt")){ + policy.policyAdapter.setConfigType(OTHER_CONFIG); + } else if(ext.contains("json")){ + policy.policyAdapter.setConfigType(JSON_CONFIG); + } else if(ext.contains("xml")){ + policy.policyAdapter.setConfigType(XML_CONFIG); + } else if(ext.contains("properties")){ + policy.policyAdapter.setConfigType(PROPERTIES_CONFIG); + } else { + if (policy.policyAdapter.getPolicyType().equalsIgnoreCase("Action")){ + policy.policyAdapter.setConfigType(JSON_CONFIG); + } + } + } + + createPolicy(policy.policyAdapter, username, policyScope,finalName,policyDataString); + }finally{ + if(policyXmlStream != null){ + try { + policyXmlStream.close(); + } catch (IOException e) { + logger.error("Exception Occured while closing input stream"+e); + } + } + } + } + + @Override + public void close(){ + synchronized(emLock){ + if(em.isOpen()){ + if(em.getTransaction().isActive()){ + em.getTransaction().rollback(); + } + em.close(); + } + if(transactionTimer instanceof Thread){ + transactionTimer.interrupt(); + } + } + } + + + + @Override + public void createGroup(String groupId, String groupName, String groupDescription, String username) { + logger.debug("deletePolicy(String policyToDeletes) as createGroup("+groupId+", "+groupName+", "+groupDescription+") called"); + if(isNullOrEmpty(groupId, groupName, username)){ + throw new IllegalArgumentException("groupId, groupName, and username must not be null or empty"); + } + if(!(groupDescription instanceof String)){ + groupDescription = ""; + } + + synchronized(emLock){ + checkBeforeOperationRun(); + Query checkGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + checkGroupQuery.setParameter("groupId", groupId); + checkGroupQuery.setParameter("deleted", false); + List checkGroupQueryList; + try{ + checkGroupQueryList = checkGroupQuery.getResultList(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on checkGroupQuery.getResultList()"); + throw new PersistenceException("Query failed trying to check for existing group"); + } + if(checkGroupQueryList.size() > 0){ + PolicyLogger.error("The group being added already exists with id "+groupId); + throw new PersistenceException("The group being added already exists with id "+groupId); + } + GroupEntity newGroup = new GroupEntity(); + em.persist(newGroup); + newGroup.setCreatedBy(username); + newGroup.setModifiedBy(username); + newGroup.setGroupName(groupName); + newGroup.setGroupId(groupId); + newGroup.setDescription(groupDescription); + + em.flush(); + this.groupId = newGroup.getGroupKey(); + } + } + + @Override + public void updateGroup(OnapPDPGroup group, String username){ + logger.debug("updateGroup(PDPGroup group) as updateGroup("+group+","+username+") called"); + if(group == null){ + throw new IllegalArgumentException("PDPGroup group must not be null"); + } + if(isNullOrEmpty(group.getId(), username)){ + throw new IllegalArgumentException("group.getId() and username must not be null or empty"); + } + + synchronized(emLock){ + checkBeforeOperationRun(); + Query getGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + getGroupQuery.setParameter("groupId", group.getId()); + getGroupQuery.setParameter("deleted", false); + List getGroupQueryList; + try{ + getGroupQueryList = getGroupQuery.getResultList(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on getGroupQuery.getResultList()"); + throw new PersistenceException("Query failed trying to get group "+group.getId()+" for editing"); + } + if(getGroupQueryList.size() < 1){ + PolicyLogger.error("The group cannot be found to update with id "+group.getId()); + throw new PersistenceException("The group cannot be found to update with id "+group.getId()); + } else if(getGroupQueryList.size() > 1){ + PolicyLogger.error("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database"); + throw new PersistenceException("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database"); + } + GroupEntity groupToUpdate = (GroupEntity)getGroupQueryList.get(0); + if(!stringEquals(groupToUpdate.getModifiedBy(), username)){ + groupToUpdate.setModifiedBy(username); + } + if(group.getDescription() != null && !stringEquals(group.getDescription(),groupToUpdate.getDescription())){ + groupToUpdate.setDescription(group.getDescription()); + } + //let's find out what policies have been deleted + StdPDPGroup oldGroup = null; + try { + oldGroup = (StdPDPGroup) papEngine.getGroup(group.getId()); + } catch (PAPException e1) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e1, "PolicyDBDao", "We cannot get the group from the papEngine to delete policies"); + } + if(oldGroup == null){ + PolicyLogger.error("We cannot get the group from the papEngine to delete policies"); + } else { + + Set newPolicySet = new HashSet<>(group.getPolicies().size()); + //a multiple of n runtime is faster than n^2, so I am using a hashset to do the comparison + for(PDPPolicy pol: group.getPolicies()){ + newPolicySet.add(pol.getId()); + } + for(PDPPolicy pol : oldGroup.getPolicies()){ + //should be fast since getPolicies uses a HashSet in StdPDPGroup + if(!newPolicySet.contains(pol.getId())){ + String[] scopeAndName = getNameScopeAndVersionFromPdpPolicy(pol.getId()); + PolicyEntity policyToDelete; + try{ + policyToDelete = getPolicy(scopeAndName[0],scopeAndName[1]); + }catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not get policy to remove: "+pol.getId()); + throw new PersistenceException("Could not get policy to remove: "+pol.getId()); + } + groupToUpdate.getPolicies().remove(policyToDelete); + + } + } + } + if(group.getName() != null && !stringEquals(group.getName(),groupToUpdate.getgroupName())){ + //we need to check if the new id exists in the database + String newGroupId = createNewPDPGroupId(group.getName()); + Query checkGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + checkGroupQuery.setParameter("groupId", newGroupId); + checkGroupQuery.setParameter("deleted", false); + List checkGroupQueryList; + try{ + checkGroupQueryList = checkGroupQuery.getResultList(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on checkGroupQuery.getResultList()"); + throw new PersistenceException("Query failed trying to check for existing group"); + } + if(checkGroupQueryList.size() != 0){ + PolicyLogger.error("The new group name already exists, group id "+newGroupId); + throw new PersistenceException("The new group name already exists, group id "+newGroupId); + } + groupToUpdate.setGroupId(newGroupId); + groupToUpdate.setGroupName(group.getName()); + this.newGroupId = group.getId(); + } + + em.flush(); + this.groupId = groupToUpdate.getGroupKey(); + } + } + + @Override + public void addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, String username) { + logger.debug("addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, String username) as addPdpToGroup("+pdpID+", "+groupID+", "+pdpName+", "+pdpDescription+", "+pdpJmxPort+", "+username+") called"); + if(isNullOrEmpty(pdpID, groupID,pdpName,username)){ + throw new IllegalArgumentException("pdpID, groupID, pdpName, and username must not be null or empty"); + } + if(!(pdpDescription instanceof String)){ + pdpDescription = ""; + } + synchronized(emLock){ + checkBeforeOperationRun(); + Query checkGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + checkGroupQuery.setParameter("groupId", groupID); + checkGroupQuery.setParameter("deleted", false); + List checkGroupQueryList; + try{ + checkGroupQueryList = checkGroupQuery.getResultList(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check for existing group on checkGroupQuery.getResultList()"); + throw new PersistenceException("Query failed trying to check for existing group"); + } + if(checkGroupQueryList.size() != 1){ + PolicyLogger.error("The group does not exist"); + throw new PersistenceException("The group does not exist"); + } + Query checkDuplicateQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); + checkDuplicateQuery.setParameter("pdpId", pdpID); + checkDuplicateQuery.setParameter("deleted", false); + List checkDuplicateList; + try{ + checkDuplicateList = checkDuplicateQuery.getResultList(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check for duplicate PDP "+pdpID+" on checkDuplicateQuery.getResultList()"); + throw new PersistenceException("Query failed trying to check for duplicate PDP "+pdpID); + } + PdpEntity newPdp; + if(checkDuplicateList.size() > 0){ + logger.warn("PDP already exists with id "+pdpID); + newPdp = (PdpEntity)checkDuplicateList.get(0); + } else { + newPdp = new PdpEntity(); + em.persist(newPdp); + } + + newPdp.setCreatedBy(username); + newPdp.setDeleted(false); + newPdp.setDescription(pdpDescription); + newPdp.setGroup((GroupEntity)checkGroupQueryList.get(0)); + newPdp.setJmxPort(pdpJmxPort); + newPdp.setModifiedBy(username); + newPdp.setPdpId(pdpID); + newPdp.setPdpName(pdpName); + + em.flush(); + this.pdpId = newPdp.getPdpKey(); + + } + } + + + @Override + public void updatePdp(OnapPDP pdp, String username){ + logger.debug("updatePdp(PDP pdp, String username) as updatePdp("+pdp+","+username+") called"); + if(pdp == null){ + throw new IllegalArgumentException("PDP pdp must not be null"); + } + if(isNullOrEmpty(pdp.getId(),username)){ + throw new IllegalArgumentException("pdp.getId() and username must not be null or empty"); + } + + synchronized(emLock){ + checkBeforeOperationRun(); + Query getPdpQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); + getPdpQuery.setParameter("pdpId", pdp.getId()); + getPdpQuery.setParameter("deleted", false); + List getPdpQueryList; + try{ + getPdpQueryList = getPdpQuery.getResultList(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on getPdpQuery.getResultList()"); + throw new PersistenceException("Query failed trying to get PDP "+pdp.getId()); + } + if(getPdpQueryList.size() < 1){ + PolicyLogger.error("The pdp cannot be found to update with id "+pdp.getId()); + throw new PersistenceException("The pdp cannot be found to update with id "+pdp.getId()); + } else if(getPdpQueryList.size() > 1){ + PolicyLogger.error("Somehow, more than one pdp with the same id "+pdp.getId()+" and deleted status were found in the database"); + throw new PersistenceException("Somehow, more than one pdp with the same id "+pdp.getId()+" and deleted status were found in the database"); + } + PdpEntity pdpToUpdate = (PdpEntity)getPdpQueryList.get(0); + if(!stringEquals(pdpToUpdate.getModifiedBy(), username)){ + pdpToUpdate.setModifiedBy(username); + } + if(pdp.getDescription() != null && !stringEquals(pdp.getDescription(),pdpToUpdate.getDescription())){ + pdpToUpdate.setDescription(pdp.getDescription()); + } + if(pdp.getName() != null && !stringEquals(pdp.getName(),pdpToUpdate.getPdpName())){ + pdpToUpdate.setPdpName(pdp.getName()); + } + if(pdp.getJmxPort() != null && !pdp.getJmxPort().equals(pdpToUpdate.getJmxPort())){ + pdpToUpdate.setJmxPort(pdp.getJmxPort()); + } + + em.flush(); + this.pdpId = pdpToUpdate.getPdpKey(); + } + } + + @Override + public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username){ + logger.debug("movePdp(PDP pdp, PDPGroup group, String username) as movePdp("+pdp+","+group+","+username+") called"); + if(pdp == null || group == null){ + throw new IllegalArgumentException("PDP pdp and PDPGroup group must not be null"); + } + if(isNullOrEmpty(username,pdp.getId(),group.getId())){ + throw new IllegalArgumentException("pdp.getId(), group.getId(), and username must not be null or empty"); + } + + synchronized(emLock){ + checkBeforeOperationRun(); + //check if pdp exists + Query getPdpQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); + getPdpQuery.setParameter("pdpId", pdp.getId()); + getPdpQuery.setParameter("deleted", false); + List getPdpQueryList; + try{ + getPdpQueryList = getPdpQuery.getResultList(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on getPdpQuery.getResultList()"); + throw new PersistenceException("Query failed trying to get pdp to move with id "+pdp.getId()); + } + if(getPdpQueryList.size() < 1){ + PolicyLogger.error("The pdp cannot be found to move with id "+pdp.getId()); + throw new PersistenceException("The pdp cannot be found to move with id "+pdp.getId()); + } else if(getPdpQueryList.size() > 1){ + PolicyLogger.error("Somehow, more than one pdp with the same id "+pdp.getId()+" and deleted status were found in the database"); + throw new PersistenceException("Somehow, more than one pdp with the same id "+pdp.getId()+" and deleted status were found in the database"); + } + + //check if new group exists + Query checkGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + checkGroupQuery.setParameter("groupId", group.getId()); + checkGroupQuery.setParameter("deleted", false); + List checkGroupQueryList; + try{ + checkGroupQueryList = checkGroupQuery.getResultList(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get group on checkGroupQuery.getResultList()"); + throw new PersistenceException("Query failed trying to get new group "+group.getId()); + } + if(checkGroupQueryList.size() != 1){ + PolicyLogger.error("The group "+group.getId()+" does not exist"); + throw new PersistenceException("The group "+group.getId()+" does not exist"); + } + GroupEntity groupToMoveInto = (GroupEntity)checkGroupQueryList.get(0); + PdpEntity pdpToUpdate = (PdpEntity)getPdpQueryList.get(0); + pdpToUpdate.setGroup(groupToMoveInto); + if(!stringEquals(pdpToUpdate.getModifiedBy(), username)){ + pdpToUpdate.setModifiedBy(username); + } + + em.flush(); + this.pdpId = pdpToUpdate.getPdpKey(); + } + } + + @Override + public void changeDefaultGroup(OnapPDPGroup group, String username){ + logger.debug("changeDefaultGroup(PDPGroup group, String username) as changeDefaultGroup("+group+","+username+") called"); + if(group == null){ + throw new IllegalArgumentException("PDPGroup group must not be null"); + } + if(isNullOrEmpty(group.getId(),username)){ + throw new IllegalArgumentException("group.getId() and username must not be null or empty"); + } + + synchronized(emLock){ + checkBeforeOperationRun(); + Query getGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + getGroupQuery.setParameter("groupId", group.getId()); + getGroupQuery.setParameter("deleted", false); + List getGroupQueryList; + try{ + getGroupQueryList = getGroupQuery.getResultList(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on getGroupQuery.getResultList()"); + throw new PersistenceException("Query failed trying to get group "+group.getId()); + } + if(getGroupQueryList.size() < 1){ + PolicyLogger.error("The group cannot be found to set default with id "+group.getId()); + throw new PersistenceException("The group cannot be found to set default with id "+group.getId()); + } else if(getGroupQueryList.size() > 1){ + PolicyLogger.error("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database"); + throw new PersistenceException("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database"); + } + GroupEntity newDefaultGroup = (GroupEntity)getGroupQueryList.get(0); + newDefaultGroup.setDefaultGroup(true); + if(!stringEquals(newDefaultGroup.getModifiedBy(), username)){ + newDefaultGroup.setModifiedBy(username); + } + + em.flush(); + this.groupId = newDefaultGroup.getGroupKey(); + Query setAllGroupsNotDefault = em.createQuery("UPDATE GroupEntity g SET g.defaultGroup=:defaultGroup WHERE g.deleted=:deleted AND g.groupKey<>:groupKey"); + //not going to set modified by for all groups + setAllGroupsNotDefault.setParameter("defaultGroup", false); + setAllGroupsNotDefault.setParameter("deleted", false); + setAllGroupsNotDefault.setParameter("groupKey", newDefaultGroup.getGroupKey()); + try{ + logger.info("set " + setAllGroupsNotDefault.executeUpdate() + " groups as not default"); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception on setAllGroupsNotDefault.executeUpdate()"); + throw new PersistenceException("Could not set all other groups default to false"); + } + + em.flush(); + } + } + + + @Override + public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username) throws PAPException { + logger.debug("deleteGroup(PDPGroup group, PDPGroup moveToGroup, String username) as deleteGroup("+group+", "+moveToGroup+","+username+") called"); + if(group == null){ + throw new IllegalArgumentException("PDPGroup group cannot be null"); + } + if(isNullOrEmpty(username,group.getId())){ + throw new IllegalArgumentException("group.getId() and and username must not be null or empty"); + } + + if(group.isDefaultGroup()){ + PolicyLogger.error("The default group "+group.getId()+" was attempted to be deleted. It cannot be."); + throw new PAPException("You cannot delete the default group."); + } + synchronized(emLock){ + checkBeforeOperationRun(); + Query deleteGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + deleteGroupQuery.setParameter("groupId", group.getId()); + deleteGroupQuery.setParameter("deleted", false); + List deleteGroupQueryList; + try{ + deleteGroupQueryList = deleteGroupQuery.getResultList(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if group exists deleteGroupQuery.getResultList()"); + throw new PersistenceException("Query failed trying to check if group exists"); + } + if(deleteGroupQueryList.size() < 1){ + logger.warn("The group could not be found with id " + group.getId()); + return; + } else if(deleteGroupQueryList.size() > 1){ + PolicyLogger.error("Somehow, more than one group with the id "+group.getId()+" were found in the database that are not deleted"); + throw new PersistenceException("Somehow, more than one group with the id "+group.getId()+" were found in the database that are not deleted"); + } + + Query pdpsInGroupQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.groupEntity=:group and p.deleted=:deleted"); + pdpsInGroupQuery.setParameter("group", ((GroupEntity)deleteGroupQueryList.get(0))); + pdpsInGroupQuery.setParameter("deleted", false); + List pdpsInGroupList; + try{ + pdpsInGroupList = pdpsInGroupQuery.getResultList(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to get PDPs in group on pdpsInGroupQuery.getResultList()"); + throw new PersistenceException("Query failed trying to get PDPs in group"); + } + if(pdpsInGroupList.size() > 0){ + if(moveToGroup != null){ + Query checkMoveToGroupQuery = em.createQuery("SELECT o FROM GroupEntity o WHERE o.groupId=:groupId AND o.deleted=:deleted"); + checkMoveToGroupQuery.setParameter("groupId", moveToGroup.getId()); + checkMoveToGroupQuery.setParameter("deleted", false); + List checkMoveToGroupList; + try{ + checkMoveToGroupList = checkMoveToGroupQuery.getResultList(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if group exists checkMoveToGroupQuery.getResultList()"); + throw new PersistenceException("Query failed trying to check if group exists"); + } + if(checkMoveToGroupList.size() < 1){ + PolicyLogger.error("The group could not be found with id " + moveToGroup.getId()); + throw new PersistenceException("The group could not be found with id " + moveToGroup.getId()); + } else if(checkMoveToGroupList.size() > 1){ + PolicyLogger.error("Somehow, more than one group with the id "+moveToGroup.getId()+" were found in the database that are not deleted"); + throw new PersistenceException("Somehow, more than one group with the id "+moveToGroup.getId()+" were found in the database that are not deleted"); + } else { + GroupEntity newGroup = (GroupEntity)checkMoveToGroupList.get(0); + for(Object pdpObject : pdpsInGroupList){ + PdpEntity pdp = (PdpEntity)pdpObject; + pdp.setGroup(newGroup); + if(!stringEquals(pdp.getModifiedBy(),username)){ + pdp.setModifiedBy(username); + } + try{ + + em.flush(); + this.newGroupId = newGroup.getGroupId(); + } catch(PersistenceException e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught PersistenceException trying to set pdp group to null on em.flush()"); + throw new PersistenceException("Query failed trying to set pdp group to "); + } + } + } + } else { + PolicyLogger.error("Group "+group.getId()+" is trying to be delted with PDPs. No group was provided to move them to"); + throw new PAPException("Group has PDPs. Must provide a group for them to move to"); + } + } + + //delete group here + GroupEntity groupToDelete = (GroupEntity)deleteGroupQueryList.get(0); + groupToDelete.setDeleted(true); + if(!stringEquals(groupToDelete.getModifiedBy(), username)){ + groupToDelete.setModifiedBy(username); + } + em.flush(); + this.groupId = groupToDelete.getGroupKey(); + } + } + + @Override + public void addPolicyToGroup(String groupID, String policyID, String username) { + logger.debug("addPolicyToGroup(String groupID, String policyID, String username) as addPolicyToGroup("+groupID+", "+policyID+","+username+") called"); + if(isNullOrEmpty(groupID, policyID, username)){ + throw new IllegalArgumentException("groupID, policyID, and username must not be null or empty"); + } + synchronized(emLock){ + checkBeforeOperationRun(); + //check if group exists + Query groupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + groupQuery.setParameter("groupId", groupID); + groupQuery.setParameter("deleted", false); + List groupQueryList; + try{ + groupQueryList = groupQuery.getResultList(); + }catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if group exists groupQuery.getResultList()"); + throw new PersistenceException("Query failed trying to check if group "+groupID+" exists"); + } + if(groupQueryList.size() < 1){ + PolicyLogger.error("Group policy is being added to does not exist with id "+groupID); + throw new PersistenceException("Group policy is being added to does not exist with id "+groupID); + } else if(groupQueryList.size() > 1){ + PolicyLogger.error("Somehow, more than one group with the id "+groupID+" were found in the database that are not deleted"); + throw new PersistenceException("Somehow, more than one group with the id "+groupID+" were found in the database that are not deleted"); + } + //we need to convert the form of the policy id that is used groups into the form that is used + //for the database. (com.Config_mypol.1.xml) to (Config_mypol.xml) + String[] policyNameScopeAndVersion = getNameScopeAndVersionFromPdpPolicy(policyID); + Query policyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:policyName AND p.scope=:scope AND p.deleted=:deleted"); + policyQuery.setParameter("policyName", policyNameScopeAndVersion[0]); + policyQuery.setParameter("scope", policyNameScopeAndVersion[1]); + policyQuery.setParameter("deleted", false); + List policyQueryList; + try{ + policyQueryList = policyQuery.getResultList(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if policy exists policyQuery.getResultList()"); + throw new PersistenceException("Query failed trying to check if policy "+policyNameScopeAndVersion[0]+" exists"); + } + if(policyQueryList.size() < 1){ + PolicyLogger.error("Policy being added to the group does not exist with policy id "+policyNameScopeAndVersion[0]); + throw new PersistenceException("Policy being added to the group does not exist with policy id "+policyNameScopeAndVersion[0]); + } else if(policyQueryList.size() > 1){ + PolicyLogger.error("Somehow, more than one policy with the id "+policyNameScopeAndVersion[0]+" were found in the database that are not deleted"); + throw new PersistenceException("Somehow, more than one group with the id "+policyNameScopeAndVersion[0]+" were found in the database that are not deleted"); + } + GroupEntity group = (GroupEntity)groupQueryList.get(0); + PolicyEntity policy = (PolicyEntity)policyQueryList.get(0); + Iterator policyIt = group.getPolicies().iterator(); + String policyName = getPolicyNameAndVersionFromPolicyFileName(policy.getPolicyName())[0]; + try{ + while(policyIt.hasNext()){ + PolicyEntity pol = policyIt.next(); + if(getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0].equals(policyName)){ + policyIt.remove(); + } + } + }catch(Exception e){ + PolicyLogger.error("Could not delete old versions for policy "+policy.getPolicyName()+", ID: "+policy.getPolicyId()); + } + group.addPolicyToGroup(policy); + em.flush(); + } + } + + //this means delete pdp not just remove from group + @Override + public void removePdpFromGroup(String pdpID, String username) { + logger.debug("removePdpFromGroup(String pdpID, String username) as removePdpFromGroup("+pdpID+","+username+") called"); + if(isNullOrEmpty(pdpID,username)){ + throw new IllegalArgumentException("pdpID and username must not be null or empty"); + } + synchronized(emLock){ + checkBeforeOperationRun(); + Query pdpQuery = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); + pdpQuery.setParameter("pdpId", pdpID); + pdpQuery.setParameter("deleted", false); + List pdpList; + try{ + pdpList = pdpQuery.getResultList(); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if pdp exists pdpQuery.getResultList()"); + throw new PersistenceException("Query failed trying to check if pdp "+pdpID+" exists"); + } + if(pdpList.size() > 1){ + PolicyLogger.error("Somehow, more than one pdp with the id "+pdpID+" were found in the database that are not deleted"); + throw new PersistenceException("Somehow, more than one pdp with the id "+pdpID+" were found in the database that are not deleted"); + } else if(pdpList.size() < 1){ + PolicyLogger.error("Pdp being removed does not exist with id "+pdpID); + return; + } + PdpEntity pdp = (PdpEntity)pdpList.get(0); + pdp.setGroup(null); + if(!stringEquals(pdp.getModifiedBy(),username)){ + pdp.setModifiedBy(username); + } + pdp.setDeleted(true); + + em.flush(); + this.pdpId = pdp.getPdpKey(); + } + } + } + + private PolicyDBDao(){ + + } + + public static PolicyDBDaoTestClass getPolicyDBDaoTestClass(){ + return new PolicyDBDao().new PolicyDBDaoTestClass(); + } + + final class PolicyDBDaoTestClass { + String getConfigFile(String filename, String scope, PolicyRestAdapter policy){ + return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy); + } + String computeScope(String fullPath, String pathToExclude){ + return PolicyDBDao.computeScope(fullPath, pathToExclude); + } + String encryptPassword(String password) throws Exception{ + return PolicyDBDao.encryptPassword(password); + } + String decryptPassword(String password) throws Exception{ + return PolicyDBDao.decryptPassword(password); + } + String getDescriptionFromXacml(String xacmlData){ + return PolicyDBDao.getDescriptionFromXacml(xacmlData); + } + String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName){ + return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName); + } + } + +} \ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java new file mode 100644 index 000000000..f5a22bcd4 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + +import java.util.List; + +import javax.persistence.PersistenceException; + +import org.onap.policy.rest.jpa.GroupEntity; +import org.onap.policy.rest.jpa.PdpEntity; +import org.onap.policy.xacml.api.pap.OnapPDP; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; + +import com.att.research.xacml.api.pap.PAPException; + +public interface PolicyDBDaoTransaction { + + /** + * Commits (makes permanent) the current transaction. Also, notifies other PolicyDBDao instances on other PAP servers of the update. + * @throws IllegalStateException if the PolicyDBDao transaction has not been used or has been committed already. + * @throws PersistenceException if the commit fails for some reason + */ + public void commitTransaction(); + + /** + * Create or update a policy + * @param policy A Policy object representing the policy to store or update + * @param username A string of the username you want to be stored for doing this operation + * @throws IllegalStateException If a transaction is open that has not yet been committed + * @throws PersistenceException If a database error occurs + * @throws IllegalArgumentException If the Policy's PolicyRestAdapter contains incorrect data. + */ + public void createPolicy(Policy policy, String username) throws IllegalStateException, PersistenceException, IllegalArgumentException; + + /** + * Check if the PolicyDBDaoTransaction is currently open + * @return False if the PolicyDBDao transaction has not been used or has been committed already, true if it is open. + */ + public boolean isTransactionOpen(); + + + + /** + * Delete an existing policy + * @param policyToDelete The file path of the policy to delete + * @throws IllegalArgumentException If the file path given can not be parsed + * @throws IllegalStateException If a transaction is open that has not yet been committed + * @throws PersistenceException If a database error occurs + */ + public void deletePolicy(String policyToDelete) throws IllegalStateException, PersistenceException, IllegalArgumentException; + + /** + * Rollback (undo) the current transaction. + */ + public void rollbackTransaction(); + + /** + * Close the PolicyDBDaoTransaction without rolling back or doing anything. Just used to close the EntityManager + */ + public void close(); + + + /** + * Create a new PDP group in the database + * @param groupID The ID to name the new group (use PolicyDBDao.createNewPDPGroupId) + * @param groupName The name to use for the new group + * @param groupDescription Description of the new group (optional) + * @param username Username of the user performing the operation + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs + */ + public void createGroup(String groupID, String groupName, String groupDescription, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; + + /** + * Updates a group in the database with a new name of description + * @param group The group with updated information. The id must match an existing group, but the name and description can be changed. + * @param username Username of the user performing the operation + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs or if the group can not be found + */ + public void updateGroup(OnapPDPGroup group, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; + + /** + * Updates a PDP in the database with new information + * @param pdp The PDP to update + * @param username Username of the user performing the operation + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs or if the pdp can not be found + */ + public void updatePdp(OnapPDP pdp, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; + + /** + * Change the default group in the database to the group provided. + * @param group The new group which should be set as default in the database + * @param username Username of the user performing the operation + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs + */ + public void changeDefaultGroup(OnapPDPGroup group, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; + + /** + * Moves a PDP to a new group. + * @param pdp The PDP which is to be moved to a new group + * @param group The new group which the PDP should be added to + * @param username Username of the user performing the operation + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs + */ + public void movePdp(OnapPDP pdp, OnapPDPGroup group, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; + + /** + * Add a new PDP to an existing group + * @param pdpID The ID to name the new PDP + * @param groupID The ID of the existing group to add the PDP to + * @param pdpName The name to use for the new PDP + * @param pdpDescription Description of the new PDP (optional) + * @param pdpJmxPort + * @param username Username of the user performing the operation + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs + */ + public void addPdpToGroup(String pdpID, String groupID, String pdpName, String pdpDescription, int pdpJmxPort, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; + + /** + * Add an existing policy to an existing group + * @param group The ID of the existing group to add the policy to + * @param policyID The ID of an existing policy + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs + */ + public void addPolicyToGroup(String group, String policyID, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; + + + /** + * Delete an existing PDP group + * @param group A PDPGroup object representing the group to delete + * @param moveToGroup A PDPGroup object representing another existing group which PDPs in the group being deleted should be moved to + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs + * @throws PAPException If an error relating to how groups are handled occurs + */ + public void deleteGroup(OnapPDPGroup group, OnapPDPGroup moveToGroup, String username)throws IllegalArgumentException, IllegalStateException, PersistenceException, PAPException; + + /** + * Removes an existing PDP from its group and deletes it. + * @param pdpID The ID of the existing PDP which should be deleted + * @throws IllegalArgumentException If non-optional parameters are null or empty strings + * @throws IllegalStateException If a transaction is already open + * @throws PersistenceException If a database error occurs + */ + public void removePdpFromGroup(String pdpID, String username) throws IllegalArgumentException, IllegalStateException, PersistenceException; + + public GroupEntity getGroup(long groupKey); + public GroupEntity getGroup(String groupId); + public List getPdpsInGroup(long groupKey); + public PdpEntity getPdp(long pdpKey); + + void renamePolicy(String oldPath, String newPath,String username); + + void clonePolicy(String oldPolicyPath, String newPolicyPath, String username); + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java new file mode 100644 index 000000000..ba5b0026a --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java @@ -0,0 +1,86 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.controlloop.policy.guard.ControlLoopGuard; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; + +public class SafePolicyBuilder { + + private SafePolicyBuilder(){ + //Private Constructor. + } + + public static ControlLoopGuard loadYamlGuard(String specification) { + // + // Read the yaml into our Java Object + // + PolicyLogger.info("Requested YAML to convert : " + specification); + Yaml yaml = new Yaml(new Constructor(ControlLoopGuard.class)); + Object obj = yaml.load(specification); + return (ControlLoopGuard) obj; + } + + public static String generateXacmlGuard(String xacmlFileContent,Map generateMap, List blacklist, List targets) { + //Setup default values and Targets. + StringBuilder targetRegex= new StringBuilder(".*|"); + if(targets!=null && !targets.isEmpty()){ + targetRegex = new StringBuilder(); + for(String t : targets){ + targetRegex.append(t + "|"); + } + } + if(generateMap.get("clname")==null|| generateMap.get("clname").isEmpty()){ + generateMap.put("clname",".*"); + } + generateMap.put("targets", targetRegex.toString().substring(0, targetRegex.length()-1)); + // Replace values. + for(Map.Entry map: generateMap.entrySet()){ + Pattern p = Pattern.compile("\\$\\{" +map.getKey() +"\\}"); + Matcher m = p.matcher(xacmlFileContent); + String finalInput = map.getValue(); + if(finalInput.contains("$")){ + finalInput = finalInput.replace("$", "\\$"); + } + xacmlFileContent=m.replaceAll(finalInput); + } + if(blacklist!=null && !blacklist.isEmpty()){ + StringBuilder rule = new StringBuilder(); + for(String blackListName : blacklist){ + if(blackListName.contains("$")){ + blackListName = blackListName.replace("$", "\\$"); + } + rule.append(""+blackListName+""); + } + Pattern p = Pattern.compile("\\$\\{blackListElement\\}"); + Matcher m = p.matcher(xacmlFileContent); + xacmlFileContent=m.replaceAll(rule.toString()); + } + PolicyLogger.info("Generated XACML from the YAML Spec: \n" + xacmlFileContent); + return xacmlFileContent; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/package-info.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/package-info.java new file mode 100644 index 000000000..31e504883 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/package-info.java @@ -0,0 +1,21 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java new file mode 100644 index 000000000..f7a170131 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java @@ -0,0 +1,261 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.controller; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +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.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.ActionPolicyDict; +import org.onap.policy.rest.jpa.UserInfo; +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 +public class ActionPolicyDictionaryController { + + private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyDictionaryController.class); + + private static CommonClassDao commonClassDao; + + @Autowired + public ActionPolicyDictionaryController(CommonClassDao commonClassDao){ + ActionPolicyDictionaryController.commonClassDao = commonClassDao; + } + + public ActionPolicyDictionaryController(){} + + public UserInfo getUserInfo(String loginId){ + UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + return name; + } + + @RequestMapping(value={"/get_ActionPolicyDictDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getActionEntitybyName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("actionPolicyDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ActionPolicyDict.class, "attributeName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(e.getMessage()); + } + } + + @RequestMapping(value={"/get_ActionPolicyDictData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getActionPolicyDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("actionPolicyDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ActionPolicyDict.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(e.getMessage()); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/action_dictionary/save_ActionDict"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + ActionPolicyDict actionPolicyDict = null; + ActionAdapter adapter = null; + String userId = null; + + if(fromAPI) { + actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("dictionaryFields").toString(), ActionPolicyDict.class); + adapter = (ActionAdapter)mapper.readValue(root.get("dictionaryFields").toString(), ActionAdapter.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(actionPolicyDict.getAttributeName(), "attributeName", ActionPolicyDict.class); + int id = 0; + ActionPolicyDict data = (ActionPolicyDict) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + actionPolicyDict.setId(1); + } else { + actionPolicyDict.setId(id); + } + actionPolicyDict.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionPolicyDict.class); + adapter = mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionAdapter.class); + userId = root.get("userid").textValue(); + } + String header = ""; + int counter = 0; + if(adapter.getHeaders().size() > 0){ + for(Object attribute : adapter.getHeaders()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("option").toString(); + String value = ((LinkedHashMap) attribute).get("number").toString(); + if(counter>0){ + header = header + ":"; + } + header = header + key + "="; + header = header + value; + counter ++; + } + } + } + actionPolicyDict.setHeader(header); + if(actionPolicyDict.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(actionPolicyDict.getAttributeName(), "attributeName", ActionPolicyDict.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + actionPolicyDict.setUserCreatedBy(this.getUserInfo(userId)); + actionPolicyDict.setUserModifiedBy(this.getUserInfo(userId)); + commonClassDao.save(actionPolicyDict); + } + }else{ + if(!isFakeUpdate) { + actionPolicyDict.setUserModifiedBy(this.getUserInfo(userId)); + actionPolicyDict.setModifiedDate(new Date()); + commonClassDao.update(actionPolicyDict); + } + } + + String responseString = null; + if(duplicateflag) { + responseString = "Duplicate"; + } else { + responseString = mapper.writeValueAsString(commonClassDao.getData(ActionPolicyDict.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate) { + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{actionPolicyDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + } + catch (Exception e){ + LOGGER.error(e.getMessage()); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/action_dictionary/remove_actionPolicyDict"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeActionPolicyDictionary(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()); + ActionPolicyDict actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("data").toString(), ActionPolicyDict.class); + commonClassDao.delete(actionPolicyDict); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(ActionPolicyDictionaryController.commonClassDao.getData(ActionPolicyDict.class)); + JSONObject j = new JSONObject("{actionPolicyDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(e.getMessage()); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } +} + +class ActionAdapter{ + private ArrayList headers; + + public ArrayList getHeaders() { + return headers; + } + + public void setHeaders(ArrayList headers) { + this.headers = headers; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java new file mode 100644 index 000000000..26d3ccfff --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java @@ -0,0 +1,552 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.controller; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.charset.StandardCharsets; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.io.IOUtils; +import org.json.JSONObject; +import org.onap.policy.api.PEDependency; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.BRMSController; +import org.onap.policy.rest.jpa.BRMSDependency; +import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +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 +public class BRMSDictionaryController{ + + private static final Logger LOGGER = FlexLogger.getLogger(BRMSDictionaryController.class); + + + private static CommonClassDao commonClassDao; + + @Autowired + public BRMSDictionaryController(CommonClassDao commonClassDao){ + BRMSDictionaryController.commonClassDao = commonClassDao; + } + + public BRMSDictionaryController() {} + + private String rule; + + public UserInfo getUserInfo(String loginId){ + UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + return name; + } + + @RequestMapping(value={"/get_BRMSParamDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getBRMSParamDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("brmsParamDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(BRMSParamTemplate.class, "ruleName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_BRMSParamData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getBRMSParamDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("brmsParamDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(BRMSParamTemplate.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/brms_dictionary/set_BRMSParamData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void SetRuleData(HttpServletRequest request, HttpServletResponse response) throws Exception{ + StringWriter writer = new StringWriter(); + IOUtils.copy(request.getInputStream() , writer, StandardCharsets.UTF_8); + String cleanStreamBoundary = writer.toString().replaceFirst("------(.*)(?s).*octet-stream", ""); + rule = cleanStreamBoundary.substring(0, cleanStreamBoundary.lastIndexOf("end")+4); + } + + @RequestMapping(value={"/brms_dictionary/save_BRMSParam"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + BRMSParamTemplate bRMSParamTemplateData; + String userId = null; + if(fromAPI) { + bRMSParamTemplateData = (BRMSParamTemplate)mapper.readValue(root.get("dictionaryFields").toString(), BRMSParamTemplate.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(bRMSParamTemplateData.getRuleName(), "ruleName", BRMSParamTemplate.class); + int id = 0; + BRMSParamTemplate data = (BRMSParamTemplate) duplicateData.get(0); + id = data.getId(); + bRMSParamTemplateData.setId(id); + bRMSParamTemplateData.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + bRMSParamTemplateData = (BRMSParamTemplate)mapper.readValue(root.get("brmsParamDictionaryData").toString(), BRMSParamTemplate.class); + userId = root.get("userid").textValue(); + } + + bRMSParamTemplateData.setRule(rule); + if(bRMSParamTemplateData.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(bRMSParamTemplateData.getRuleName(), "ruleName", BRMSParamTemplate.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + bRMSParamTemplateData.setUserCreatedBy(this.getUserInfo(userId)); + commonClassDao.save(bRMSParamTemplateData); + } + }else{ + commonClassDao.update(bRMSParamTemplateData); + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(BRMSDictionaryController.commonClassDao.getData(BRMSParamTemplate.class)); + } + if(fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + responseString = "Success"; + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{brmsParamDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/brms_dictionary/remove_brmsParam"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeBRMSParamDictionary(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()); + BRMSParamTemplate bRMSParamTemplateData = (BRMSParamTemplate)mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class); + commonClassDao.delete(bRMSParamTemplateData); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(BRMSDictionaryController.commonClassDao.getData(BRMSParamTemplate.class)); + JSONObject j = new JSONObject("{brmsParamDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/get_BRMSDependencyDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getBRMSDependencyDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("brmsDependencyDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(BRMSDependency.class, "dependencyName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_BRMSDependencyData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getBRMSDependencyDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("brmsDependencyDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(BRMSDependency.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/brms_dictionary/save_BRMSDependencyData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveBRMSDependencyDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + LOGGER.debug("DictionaryController: saveBRMSDependencyDictionary() is called"); + + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + BRMSDependency brmsDependency; + String userId = null; + if (fromAPI) { + brmsDependency = (BRMSDependency)mapper.readValue(root.get("dictionaryFields").toString(), BRMSDependency.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(brmsDependency.getDependencyName(), "dependencyName", BRMSDependency.class); + int id = 0; + BRMSDependency data = (BRMSDependency) duplicateData.get(0); + id = data.getId(); + brmsDependency.setId(id); + brmsDependency.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + brmsDependency = (BRMSDependency)mapper.readValue(root.get("brmsDependencyDictionaryData").toString(), BRMSDependency.class); + userId = root.get("userid").textValue(); + } + + LOGGER.audit("the userId from the onap portal is: " + userId); + String responseString = null; + + if(brmsDependency.getDependency()!=null && !brmsDependency.getDependency().trim().equals("")){ + PEDependency dependency = null; + try{ + dependency = PolicyUtils.jsonStringToObject(brmsDependency.getDependency(), PEDependency.class); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "wrong data given for BRMS PEDependency Dictionary : " + brmsDependency.getDependency()); + } + if(dependency==null){ + responseString = "Error"; + }else{ + if(brmsDependency.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(brmsDependency.getDependencyName(), "dependencyName", BRMSDependency.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + brmsDependency.setUserCreatedBy(getUserInfo(userId)); + brmsDependency.setUserModifiedBy(getUserInfo(userId)); + LOGGER.audit("DictionaryController: got the user info now about to call Save() method on brmsDependencydao"); + commonClassDao.save(brmsDependency); + } + }else{ + brmsDependency.setUserModifiedBy(this.getUserInfo(userId)); + brmsDependency.setModifiedDate(new Date()); + commonClassDao.update(brmsDependency); + } + if(duplicateflag) { + responseString = "Duplicate"; + } else { + responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSDependency.class)); + } + } + } + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate") && !responseString.equals("Error")) { + responseString = "Success"; + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{brmsDependencyDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + } catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/brms_dictionary/remove_brmsDependency"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeBRMSDependencyDictionary(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()); + BRMSDependency brmsDependency = (BRMSDependency)mapper.readValue(root.get("data").toString(), BRMSDependency.class); + commonClassDao.delete(brmsDependency); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSDependency.class)); + JSONObject j = new JSONObject("{brmsDependencyDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + + @RequestMapping(value={"/get_BRMSControllerDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getBRMSControllerDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("brmsControllerDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(BRMSController.class, "controllerName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_BRMSControllerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getBRMSControllerDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("brmsControllerDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(BRMSController.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/brms_dictionary/save_BRMSControllerData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveBRMSControllerDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + LOGGER.debug("DictionaryController: saveBRMSControllerDictionary() is called"); + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + BRMSController brmsController; + String userId = null; + if (fromAPI) { + brmsController = (BRMSController)mapper.readValue(root.get("dictionaryFields").toString(), BRMSController.class); + userId = "API"; + //check if update operation or create, get id for data to be updated + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(brmsController.getControllerName(), "controllerName", BRMSController.class); + int id = 0; + BRMSController data = (BRMSController) duplicateData.get(0); + id = data.getId(); + brmsController.setId(id); + brmsController.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + brmsController = (BRMSController)mapper.readValue(root.get("brmsControllerDictionaryData").toString(), BRMSController.class); + userId = root.get("userid").textValue(); + } + LOGGER.audit("the userId from the onap portal is: " + userId); + String responseString = null; + if(brmsController.getController()!=null && !brmsController.getController().trim().equals("")){ + PEDependency dependency = null; + try{ + dependency = PolicyUtils.jsonStringToObject(brmsController.getController(), PEDependency.class); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "wrong data given for BRMS Controller Dictionary : " + brmsController.getController()); + } + if(dependency==null){ + responseString = "Error"; + }else{ + if(brmsController.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(brmsController.getControllerName(), "controllerName", BRMSController.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + brmsController.setUserCreatedBy(getUserInfo(userId)); + brmsController.setUserModifiedBy(getUserInfo(userId)); + LOGGER.audit("DictionaryController: got the user info now about to call Save() method on brmsControllerdao"); + commonClassDao.save(brmsController); + } + }else{ + brmsController.setUserModifiedBy(this.getUserInfo(userId)); + brmsController.setModifiedDate(new Date()); + commonClassDao.update(brmsController); + } + if(duplicateflag) { + responseString = "Duplicate"; + } else { + responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSController.class)); + } + } + } + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate") && !responseString.equals("Error")) { + responseString = "Success"; + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{brmsControllerDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + } catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/brms_dictionary/remove_brmsController"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeBRMSControllerDictionary(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()); + BRMSController brmsController = (BRMSController)mapper.readValue(root.get("data").toString(), BRMSController.class); + commonClassDao.delete(brmsController); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSController.class)); + JSONObject j = new JSONObject("{brmsControllerDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + public BRMSDependency getDependencyDataByID(String dependencyName){ + return (BRMSDependency) commonClassDao.getEntityItem(BRMSDependency.class, "dependencyName", dependencyName); + } + + public BRMSController getControllerDataByID(String controllerName){ + return (BRMSController) commonClassDao.getEntityItem(BRMSController.class, "controllerName", controllerName); + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java new file mode 100644 index 000000000..75345f99c --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java @@ -0,0 +1,1031 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.controller; + +import java.io.PrintWriter; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +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.pap.xacml.rest.adapters.GridData; +import org.onap.policy.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.ClosedLoopD2Services; +import org.onap.policy.rest.jpa.ClosedLoopSite; +import org.onap.policy.rest.jpa.PEPOptions; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.rest.jpa.VNFType; +import org.onap.policy.rest.jpa.VSCLAction; +import org.onap.policy.rest.jpa.VarbindDictionary; +import org.onap.policy.xacml.api.XACMLErrorConstants; +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 +public class ClosedLoopDictionaryController{ + + private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopDictionaryController.class); + + private static CommonClassDao commonClassDao; + + @Autowired + public ClosedLoopDictionaryController(CommonClassDao commonClassDao){ + ClosedLoopDictionaryController.commonClassDao = commonClassDao; + } + + public ClosedLoopDictionaryController(){} + + public UserInfo getUserInfo(String loginId){ + UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + return name; + } + + + @RequestMapping(value={"/get_VSCLActionDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getVSCLActionDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("vsclActionDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(VSCLAction.class, "vsclaction"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + + @RequestMapping(value={"/get_VSCLActionData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getVSCLActionDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("vsclActionDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/get_VNFTypeDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getVNFTypeDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("vnfTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(VNFType.class, "vnftype"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_VNFTypeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getVNFTypeDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("vnfTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(VNFType.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/get_PEPOptionsDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPEPOptionsDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("pepOptionsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PEPOptions.class, "pepName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_PEPOptionsData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPEPOptionsDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("pepOptionsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/get_VarbindDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getVarbindDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("varbindDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(VarbindDictionary.class, "varbindName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_VarbindDictionaryData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getVarbindDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("varbindDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/get_ClosedLoopServicesDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getClosedLoopServiceDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("closedLoopServiceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ClosedLoopD2Services.class, "serviceName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_ClosedLoopServicesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getClosedLoopServiceDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("closedLoopServiceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/get_ClosedLoopSiteDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getClosedLoopSiteDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("closedLoopSiteDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ClosedLoopSite.class, "siteName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_ClosedLoopSiteData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getClosedLoopSiteDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("closedLoopSiteDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/cl_dictionary/save_vsclAction"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveVSCLAction(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + VSCLAction vSCLAction; + String userId = null; + if (fromAPI) { + vSCLAction = (VSCLAction)mapper.readValue(root.get("dictionaryFields").toString(), VSCLAction.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(vSCLAction.getVsclaction(), "vsclaction", VSCLAction.class); + int id = 0; + VSCLAction data = (VSCLAction) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + vSCLAction.setId(1); + } else { + vSCLAction.setId(id); + } + + vSCLAction.setUserCreatedBy(this.getUserInfo(userId)); + } + + } else { + vSCLAction = (VSCLAction)mapper.readValue(root.get("vsclActionDictionaryData").toString(), VSCLAction.class); + userId = root.get("userid").textValue(); + } + if(vSCLAction.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(vSCLAction.getVsclaction(), "vsclaction", VSCLAction.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + vSCLAction.setUserCreatedBy(this.getUserInfo(userId)); + vSCLAction.setUserModifiedBy(this.getUserInfo(userId)); + vSCLAction.setModifiedDate(new Date()); + commonClassDao.save(vSCLAction); + } + }else{ + if(!isFakeUpdate) { + vSCLAction.setUserModifiedBy(this.getUserInfo(userId)); + commonClassDao.update(vSCLAction); + } + } + + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class)); + } + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate) { + responseString = "Exists"; + } else { + responseString = "Success"; + } + + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{vsclActionDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/cl_dictionary/remove_VsclAction"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeVSCLAction(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()); + VSCLAction vSCLAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class); + commonClassDao.delete(vSCLAction); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class)); + JSONObject j = new JSONObject("{vsclActionDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/cl_dictionary/save_vnfType"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveVnfType(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + VNFType vNFType; + String userId = null; + + if (fromAPI) { + vNFType = (VNFType)mapper.readValue(root.get("dictionaryFields").toString(), VNFType.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(vNFType.getVnftype(), "vnftype", VNFType.class); + int id = 0; + VNFType data = (VNFType) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + vNFType.setId(1); + } else { + vNFType.setId(id); + } + vNFType.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + vNFType = (VNFType)mapper.readValue(root.get("vnfTypeDictionaryData").toString(), VNFType.class); + userId = root.get("userid").textValue(); + } + if(vNFType.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(vNFType.getVnftype(), "vnftype", VNFType.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + vNFType.setUserCreatedBy(this.getUserInfo(userId)); + vNFType.setUserModifiedBy(this.getUserInfo(userId)); + commonClassDao.save(vNFType); + } + }else{ + if(!isFakeUpdate) { + vNFType.setUserModifiedBy(this.getUserInfo(userId)); + vNFType.setModifiedDate(new Date()); + commonClassDao.update(vNFType); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(VNFType.class)); + } + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate) { + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{vnfTypeDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/cl_dictionary/remove_vnfType"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeVnfType(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()); + VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class); + commonClassDao.delete(vNFType); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(VNFType.class)); + JSONObject j = new JSONObject("{vnfTypeDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/cl_dictionary/save_pepOptions"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePEPOptions(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PEPOptions pEPOptions; + GridData gridData; + String userId = null; + if (fromAPI) { + pEPOptions = (PEPOptions)mapper.readValue(root.get("dictionaryFields").toString(), PEPOptions.class); + gridData = (GridData)mapper.readValue(root.get("dictionaryFields").toString(), GridData.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), "pepName", PEPOptions.class); + int id = 0; + PEPOptions data = (PEPOptions) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + pEPOptions.setId(1); + } else { + pEPOptions.setId(id); + } + pEPOptions.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + pEPOptions = (PEPOptions)mapper.readValue(root.get("pepOptionsDictionaryData").toString(), PEPOptions.class); + gridData = (GridData)mapper.readValue(root.get("pepOptionsDictionaryData").toString(), GridData.class); + userId = root.get("userid").textValue(); + } + String actions = ""; + int counter = 0; + if(gridData.getAttributes().size() > 0){ + for(Object attribute : gridData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("option").toString(); + String value = ((LinkedHashMap) attribute).get("number").toString(); + if(counter>0){ + actions = actions + ":#@"; + } + actions = actions + key + "=#@"; + actions = actions + value; + counter ++; + } + } + } + pEPOptions.setActions(actions); + if(pEPOptions.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), "pepName", PEPOptions.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + pEPOptions.setUserCreatedBy(this.getUserInfo(userId)); + pEPOptions.setUserModifiedBy(this.getUserInfo(userId)); + commonClassDao.save(pEPOptions); + } + }else{ + if(!isFakeUpdate){ + pEPOptions.setUserModifiedBy(this.getUserInfo(userId)); + pEPOptions.setModifiedDate(new Date()); + commonClassDao.update(pEPOptions); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class)); + } + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{pepOptionsDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/cl_dictionary/remove_pepOptions"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removePEPOptions(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()); + PEPOptions pEPOptions = (PEPOptions)mapper.readValue(root.get("data").toString(), PEPOptions.class); + commonClassDao.delete(pEPOptions); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class)); + JSONObject j = new JSONObject("{pepOptionsDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/cl_dictionary/save_service"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveServiceType(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + ClosedLoopD2Services serviceData; + String userId = null; + if (fromAPI) { + serviceData = (ClosedLoopD2Services)mapper.readValue(root.get("dictionaryFields").toString(), ClosedLoopD2Services.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(serviceData.getServiceName(), "serviceName", ClosedLoopD2Services.class); + int id = 0; + ClosedLoopD2Services data = (ClosedLoopD2Services) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + serviceData.setId(1); + } else { + serviceData.setId(id); + } + serviceData.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + serviceData = (ClosedLoopD2Services)mapper.readValue(root.get("closedLoopServiceDictionaryData").toString(), ClosedLoopD2Services.class); + userId = root.get("userid").textValue(); + } + if(serviceData.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(serviceData.getServiceName(), "serviceName", ClosedLoopD2Services.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + serviceData.setUserCreatedBy(this.getUserInfo(userId)); + serviceData.setUserModifiedBy(this.getUserInfo(userId)); + commonClassDao.save(serviceData); + } + }else{ + if(!isFakeUpdate){ + serviceData.setUserModifiedBy(this.getUserInfo(userId)); + serviceData.setModifiedDate(new Date()); + commonClassDao.update(serviceData); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class)); + } + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{closedLoopServiceDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/cl_dictionary/remove_Service"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeServiceType(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()); + ClosedLoopD2Services closedLoopD2Services = (ClosedLoopD2Services)mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class); + commonClassDao.delete(closedLoopD2Services); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class)); + JSONObject j = new JSONObject("{closedLoopServiceDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/cl_dictionary/save_siteName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveSiteType(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + ClosedLoopSite siteData; + String userId = null; + if (fromAPI) { + siteData = (ClosedLoopSite)mapper.readValue(root.get("dictionaryFields").toString(), ClosedLoopSite.class); + userId = "API"; + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(siteData.getSiteName(), "siteName", ClosedLoopSite.class); + int id = 0; + ClosedLoopSite data = (ClosedLoopSite) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + siteData.setId(1); + } else { + siteData.setId(id); + } + siteData.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + siteData = (ClosedLoopSite)mapper.readValue(root.get("closedLoopSiteDictionaryData").toString(), ClosedLoopSite.class); + userId = root.get("userid").textValue(); + } + if(siteData.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(siteData.getSiteName(), "siteName", ClosedLoopSite.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + siteData.setUserCreatedBy(this.getUserInfo(userId)); + siteData.setUserModifiedBy(this.getUserInfo(userId)); + commonClassDao.save(siteData); + } + }else{ + if(!isFakeUpdate) { + siteData.setUserModifiedBy(this.getUserInfo(userId)); + siteData.setModifiedDate(new Date()); + commonClassDao.update(siteData); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{closedLoopSiteDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/cl_dictionary/remove_site"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeSiteType(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()); + ClosedLoopSite closedLoopSite = (ClosedLoopSite)mapper.readValue(root.get("data").toString(), ClosedLoopSite.class); + commonClassDao.delete(closedLoopSite); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class)); + JSONObject j = new JSONObject("{closedLoopSiteDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/cl_dictionary/save_varbind"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveVarbind(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + VarbindDictionary varbindDictionary; + String userId = null; + if (fromAPI) { + varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("dictionaryFields").toString(), VarbindDictionary.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(varbindDictionary.getVarbindName(), "varbindName", VarbindDictionary.class); + int id = 0; + VarbindDictionary data = (VarbindDictionary) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + varbindDictionary.setId(1); + } else { + varbindDictionary.setId(id); + } + varbindDictionary.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("varbindDictionaryData").toString(), VarbindDictionary.class); + userId = root.get("userid").textValue(); + } + if(varbindDictionary.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(varbindDictionary.getVarbindName(), "varbindName", VarbindDictionary.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + varbindDictionary.setUserCreatedBy(this.getUserInfo(userId)); + varbindDictionary.setUserModifiedBy(this.getUserInfo(userId)); + commonClassDao.save(varbindDictionary); + } + }else{ + if(!isFakeUpdate){ + varbindDictionary.setUserModifiedBy(this.getUserInfo(userId)); + varbindDictionary.setModifiedDate(new Date()); + commonClassDao.update(varbindDictionary); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{varbindDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/cl_dictionary/remove_varbindDict"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeVarbind(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()); + VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class); + commonClassDao.delete(varbindDictionary); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class)); + JSONObject j = new JSONObject("{varbindDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + +} + diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java new file mode 100644 index 000000000..ac19b99a2 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java @@ -0,0 +1,426 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.controller; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +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.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.Datatype; +import org.onap.policy.rest.jpa.DecisionSettings; +import org.onap.policy.rest.jpa.RainyDayTreatments; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.xacml.api.XACMLErrorConstants; +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 +public class DecisionPolicyDictionaryController { + + private static final Logger LOGGER = FlexLogger.getLogger(DecisionPolicyDictionaryController.class); + + private static CommonClassDao commonClassDao; + + @Autowired + public DecisionPolicyDictionaryController(CommonClassDao commonClassDao){ + DecisionPolicyDictionaryController.commonClassDao = commonClassDao; + } + + public DecisionPolicyDictionaryController(){} + + public UserInfo getUserInfo(String loginId){ + UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + return name; + } + + @RequestMapping(value={"/get_SettingsDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getSettingsDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("settingsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(DecisionSettings.class, "xacmlId"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + + @RequestMapping(value={"/get_SettingsDictionaryData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getSettingsDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("settingsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/decision_dictionary/save_Settings"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + DecisionSettings decisionSettings; + String userId = null; + + if (fromAPI) { + decisionSettings = (DecisionSettings)mapper.readValue(root.get("dictionaryFields").toString(), DecisionSettings.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), "xacmlId", DecisionSettings.class); + int id = 0; + DecisionSettings data = (DecisionSettings) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + decisionSettings.setId(1); + } else { + decisionSettings.setId(id); + } + decisionSettings.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + decisionSettings = (DecisionSettings)mapper.readValue(root.get("settingsDictionaryData").toString(), DecisionSettings.class); + userId = root.get("userid").textValue(); + } + if(decisionSettings.getDatatypeBean().getShortName() != null){ + String datatype = decisionSettings.getDatatypeBean().getShortName(); + Datatype a = new Datatype(); + if(datatype.equalsIgnoreCase("string")){ + a.setId(26); + }else if(datatype.equalsIgnoreCase("integer")){ + a.setId(12); + }else if(datatype.equalsIgnoreCase("boolean")){ + a.setId(18); + }else if(datatype.equalsIgnoreCase("double")){ + a.setId(25); + }else if(datatype.equalsIgnoreCase("user")){ + a.setId(29); + } + decisionSettings.setDatatypeBean(a); + } + if(decisionSettings.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), "xacmlId", DecisionSettings.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + decisionSettings.setUserCreatedBy(this.getUserInfo(userId)); + decisionSettings.setUserModifiedBy(this.getUserInfo(userId)); + commonClassDao.save(decisionSettings); + } + }else{ + if(!isFakeUpdate) { + decisionSettings.setUserModifiedBy(this.getUserInfo(userId)); + decisionSettings.setModifiedDate(new Date()); + commonClassDao.update(decisionSettings); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{settingsDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/settings_dictionary/remove_settings"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeSettingsDictionary(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()); + DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class); + commonClassDao.delete(decisionSettings); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)); + JSONObject j = new JSONObject("{settingsDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + + + @RequestMapping(value={"/get_RainyDayDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getRainyDayDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("rainyDayDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(RainyDayTreatments.class, "bbid"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + + @RequestMapping(value={"/get_RainyDayDictionaryData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getRainyDayDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("rainyDayDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/decision_dictionary/save_RainyDay"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + RainyDayTreatments decisionRainyDay; + TreatmentValues treatmentsData = null; + if (fromAPI) { + decisionRainyDay = (RainyDayTreatments)mapper.readValue(root.get("dictionaryFields").toString(), RainyDayTreatments.class); + treatmentsData = (TreatmentValues)mapper.readValue(root.get("dictionaryFields").toString(), TreatmentValues.class); + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(decisionRainyDay.getBbid()+":"+decisionRainyDay.getWorkstep(), "bbid:workstep", RainyDayTreatments.class); + int id = 0; + RainyDayTreatments data = (RainyDayTreatments) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + } else { + decisionRainyDay.setId(id); + } + } + } else { + decisionRainyDay = (RainyDayTreatments)mapper.readValue(root.get("rainyDayDictionaryData").toString(), RainyDayTreatments.class); + treatmentsData = (TreatmentValues)mapper.readValue(root.get("rainyDayDictionaryData").toString(), TreatmentValues.class); + } + + String userValue = ""; + int counter = 0; + if(treatmentsData.getUserDataTypeValues().size() > 0){ + for(Object treatment : treatmentsData.getUserDataTypeValues()){ + if(treatment instanceof LinkedHashMap){ + String key = ((LinkedHashMap) treatment).get("treatment").toString(); + if(counter>0){ + userValue = userValue + ","; + } + userValue = userValue + key ; + counter ++; + } + } + } + decisionRainyDay.setTreatments(userValue); + + if(decisionRainyDay.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(decisionRainyDay.getBbid()+":"+decisionRainyDay.getWorkstep(), "bbid:workstep", RainyDayTreatments.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(decisionRainyDay); + } + }else{ + if(!isFakeUpdate) { + commonClassDao.update(decisionRainyDay); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{rainyDayDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/decision_dictionary/remove_rainyDay"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeRainyDayDictionary(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()); + RainyDayTreatments decisionRainyDay = (RainyDayTreatments)mapper.readValue(root.get("data").toString(), RainyDayTreatments.class); + commonClassDao.delete(decisionRainyDay); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)); + JSONObject j = new JSONObject("{rainyDayDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + +} + +class TreatmentValues { + private ArrayList userDataTypeValues; + + public ArrayList getUserDataTypeValues() { + return userDataTypeValues; + } + + public void setUserDataTypeValues(ArrayList userDataTypeValues) { + this.userDataTypeValues = userDataTypeValues; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java new file mode 100644 index 000000000..1811223e6 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java @@ -0,0 +1,246 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.controller; + +import java.io.PrintWriter; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +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.pap.xacml.rest.adapters.GridData; +import org.onap.policy.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.DescriptiveScope; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.xacml.api.XACMLErrorConstants; +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 +public class DescriptiveDictionaryController { + + private static final Logger LOGGER = FlexLogger.getLogger(DescriptiveDictionaryController.class); + + private static CommonClassDao commonClassDao; + + @Autowired + public DescriptiveDictionaryController(CommonClassDao commonClassDao){ + DescriptiveDictionaryController.commonClassDao = commonClassDao; + } + + public DescriptiveDictionaryController(){} + + public UserInfo getUserInfo(String loginId){ + UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + return name; + } + + @RequestMapping(value={"/get_DescriptiveScopeByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getDescriptiveDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("descriptiveScopeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(DescriptiveScope.class, "descriptiveScopeName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_DescriptiveScope"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getDescriptiveDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("descriptiveScopeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/descriptive_dictionary/save_descriptive"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + DescriptiveScope descriptiveScope; + GridData data; + String userId = null; + if (fromAPI) { + descriptiveScope = (DescriptiveScope)mapper.readValue(root.get("dictionaryFields").toString(), DescriptiveScope.class); + data = (GridData)mapper.readValue(root.get("dictionaryFields").toString(), GridData.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), "descriptiveScopeName", DescriptiveScope.class); + int id = 0; + DescriptiveScope dbdata = (DescriptiveScope) duplicateData.get(0); + id = dbdata.getId(); + if(id==0){ + isFakeUpdate=true; + descriptiveScope.setId(1); + } else { + descriptiveScope.setId(id); + } + descriptiveScope.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + descriptiveScope = (DescriptiveScope)mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), DescriptiveScope.class); + data = (GridData)mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), GridData.class); + userId = root.get("userid").textValue(); + } + String header = ""; + int counter = 0; + if(data.getAttributes().size() > 0){ + for(Object attribute : data.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("option").toString(); + String value = ((LinkedHashMap) attribute).get("number").toString(); + if(counter>0){ + header = header + "AND"; + } + header = header + key + ":"; + header = header + value; + counter ++; + } + } + } + descriptiveScope.setSearch(header); + if(descriptiveScope.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), "descriptiveScopeName", DescriptiveScope.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + descriptiveScope.setUserCreatedBy(this.getUserInfo(userId)); + descriptiveScope.setUserModifiedBy(this.getUserInfo(userId)); + commonClassDao.save(descriptiveScope); + } + }else{ + if(!isFakeUpdate){ + descriptiveScope.setUserModifiedBy(this.getUserInfo(userId)); + descriptiveScope.setModifiedDate(new Date()); + commonClassDao.update(descriptiveScope); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/descriptive_dictionary/remove_descriptiveScope"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeDescriptiveDictionary(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()); + DescriptiveScope descriptiveScope = (DescriptiveScope)mapper.readValue(root.get("data").toString(), DescriptiveScope.class); + commonClassDao.delete(descriptiveScope); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)); + JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } +} + diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java new file mode 100644 index 000000000..d16de1f9c --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java @@ -0,0 +1,447 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.controller; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; +import org.onap.policy.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.Attribute; +import org.onap.policy.rest.jpa.Category; +import org.onap.policy.rest.jpa.Datatype; +import org.onap.policy.rest.jpa.OnapName; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.xacml.api.XACMLErrorConstants; +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 com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +public class DictionaryController { + + private static final Log LOGGER = LogFactory.getLog(DictionaryController.class); + + private static CommonClassDao commonClassDao; + + @Autowired + public DictionaryController(CommonClassDao commonClassDao){ + DictionaryController.commonClassDao = commonClassDao; + } + + public DictionaryController(){} + + public UserInfo getUserInfo(String loginId){ + UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + return name; + } + + + public Category getCategory(){ + List list = commonClassDao.getData(Category.class); + for (int i = 0; i < list.size() ; i++) { + Category value = (Category) list.get(i); + if (value.getShortName().equals("resource")) { + return value; + } + } + return null; + } + + @RequestMapping(value={"/get_AttributeDatabyAttributeName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getAttributeDictionaryEntityDatabyAttributeName(HttpServletRequest request, HttpServletResponse response){ + try{ + System.out.println(); + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("attributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(Attribute.class, "xacmlId"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + //Attribute Dictionary + @RequestMapping(value="/get_AttributeData", method= RequestMethod.GET , produces=MediaType.APPLICATION_JSON_VALUE) + public void getAttributeDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + System.out.println(); + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("attributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(Attribute.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/attribute_dictionary/save_attribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + Attribute attributeData = null; + AttributeValues attributeValueData = null; + String userId = null; + if (fromAPI) { + //JsonNode json = root.get("dictionaryFields"); + attributeData = (Attribute)mapper.readValue(root.get("dictionaryFields").toString(), Attribute.class); + attributeValueData = (AttributeValues)mapper.readValue(root.get("dictionaryFields").toString(), AttributeValues.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), "xacmlId", Attribute.class); + int id = 0; + Attribute data = (Attribute) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + attributeData.setId(1); + } else { + attributeData.setId(id); + } + attributeData.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + attributeData = (Attribute)mapper.readValue(root.get("attributeDictionaryData").toString(), Attribute.class); + attributeValueData = (AttributeValues)mapper.readValue(root.get("attributeDictionaryData").toString(), AttributeValues.class); + userId = root.get("userid").textValue(); + } + String userValue = ""; + int counter = 0; + if(attributeValueData.getUserDataTypeValues().size() > 0){ + for(Object attribute : attributeValueData.getUserDataTypeValues()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("attributeValues").toString(); + if(counter>0){ + userValue = userValue + ","; + } + userValue = userValue + key ; + counter ++; + } + } + } + attributeData.setAttributeValue(userValue); + if(attributeData.getDatatypeBean().getShortName() != null){ + String datatype = attributeData.getDatatypeBean().getShortName(); + Datatype a = new Datatype(); + if(datatype.equalsIgnoreCase("string")){ + a.setId(26); + }else if(datatype.equalsIgnoreCase("integer")){ + a.setId(12); + }else if(datatype.equalsIgnoreCase("boolean")){ + a.setId(18); + }else if(datatype.equalsIgnoreCase("double")){ + a.setId(25); + }else if(datatype.equalsIgnoreCase("user")){ + a.setId(29); + } + attributeData.setDatatypeBean(a); + } + if(attributeData.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), "xacmlId", Attribute.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + attributeData.setCategoryBean(this.getCategory()); + attributeData.setUserCreatedBy(this.getUserInfo(userId)); + attributeData.setUserModifiedBy(this.getUserInfo(userId)); + commonClassDao.save(attributeData); + } + }else{ + if(!isFakeUpdate) { + attributeData.setUserModifiedBy(this.getUserInfo(userId)); + attributeData.setModifiedDate(new Date()); + commonClassDao.update(attributeData); + } + } + String responseString = null; + if(duplicateflag) { + responseString = "Duplicate"; + } else { + responseString = mapper.writeValueAsString(commonClassDao.getData(Attribute.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate) { + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{attributeDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/attribute_dictionary/remove_attribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeAttributeDictionary(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()); + Attribute attributeData = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class); + commonClassDao.delete(attributeData); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.getData(Attribute.class)); + JSONObject j = new JSONObject("{attributeDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + //OnapName Dictionary + @RequestMapping(value={"/get_OnapNameDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getOnapNameDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + LOGGER.info("get_OnapNameDataByName is called"); + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("onapNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(OnapName.class, "onapName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_OnapNameData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getOnapNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("onapNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(OnapName.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/onap_dictionary/save_onapName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + OnapName onapData; + String userId = null; + if (fromAPI) { + onapData = (OnapName)mapper.readValue(root.get("dictionaryFields").toString(), OnapName.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getOnapName(), "onapName", OnapName.class); + int id = 0; + OnapName data = (OnapName) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + onapData.setId(1); + } else { + onapData.setId(id); + } + onapData.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + onapData = (OnapName)mapper.readValue(root.get("onapNameDictionaryData").toString(), OnapName.class); + userId = root.get("userid").textValue(); + } + if(onapData.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getOnapName(), "onapName", OnapName.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + onapData.setUserCreatedBy(getUserInfo(userId)); + onapData.setUserModifiedBy(getUserInfo(userId)); + commonClassDao.save(onapData); + } + }else{ + if(!isFakeUpdate){ + onapData.setUserModifiedBy(this.getUserInfo(userId)); + onapData.setModifiedDate(new Date()); + commonClassDao.update(onapData); + } + } + String responseString = null; + if(duplicateflag) { + responseString = "Duplicate"; + } else { + responseString = mapper.writeValueAsString(commonClassDao.getData(OnapName.class)); + } + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{onapNameDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/onap_dictionary/remove_onap"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeOnapDictionary(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()); + OnapName onapData = (OnapName)mapper.readValue(root.get("data").toString(), OnapName.class); + commonClassDao.delete(onapData); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(OnapName.class)); + JSONObject j = new JSONObject("{onapNameDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + +} + +class AttributeValues{ + private ArrayList userDataTypeValues; + + public ArrayList getUserDataTypeValues() { + return userDataTypeValues; + } + + public void setUserDataTypeValues(ArrayList userDataTypeValues) { + this.userDataTypeValues = userDataTypeValues; + } +} + diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java new file mode 100644 index 000000000..12851917a --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java @@ -0,0 +1,539 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.controller; + /* + * + * + * */ +import java.io.File; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.OutputStream; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.compress.utils.IOUtils; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.ActionList; +import org.onap.policy.rest.jpa.ActionPolicyDict; +import org.onap.policy.rest.jpa.AddressGroup; +import org.onap.policy.rest.jpa.Attribute; +import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.Category; +import org.onap.policy.rest.jpa.Datatype; +import org.onap.policy.rest.jpa.DecisionSettings; +import org.onap.policy.rest.jpa.DescriptiveScope; +import org.onap.policy.rest.jpa.OnapName; +import org.onap.policy.rest.jpa.GroupServiceList; +import org.onap.policy.rest.jpa.PEPOptions; +import org.onap.policy.rest.jpa.PrefixList; +import org.onap.policy.rest.jpa.ProtocolList; +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.rest.jpa.UserInfo; +import org.onap.policy.rest.jpa.VNFType; +import org.onap.policy.rest.jpa.VSCLAction; +import org.onap.policy.rest.jpa.VarbindDictionary; +import org.onap.policy.rest.jpa.Zone; +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.ObjectMapper; + +import au.com.bytecode.opencsv.CSVReader; + + +@Controller +public class DictionaryImportController { + private String newFile; + + private static CommonClassDao commonClassDao; + + @Autowired + public DictionaryImportController(CommonClassDao commonClassDao){ + DictionaryImportController.commonClassDao = commonClassDao; + } + + public DictionaryImportController(){} + + + @RequestMapping(value={"/dictionary/import_dictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void ImportDictionaryData(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 userId = request.getParameter("userId"); + String dictionaryName = request.getParameter("dictionaryName"); + + File file = new File(dictionaryName); + OutputStream outputStream = new FileOutputStream(file); + IOUtils.copy(request.getInputStream(), outputStream); + outputStream.close(); + this.newFile = file.toString(); + CSVReader csvReader = new CSVReader(new FileReader(this.newFile)); + List dictSheet = csvReader.readAll(); + if(dictionaryName.startsWith("Attribute")){ + for(int i = 1; i< dictSheet.size(); i++){ + Attribute attribute = new Attribute(""); + UserInfo userinfo = new UserInfo(); + userinfo.setUserLoginId(userId); + attribute.setUserCreatedBy(userinfo); + attribute.setUserModifiedBy(userinfo); + String[] rows = dictSheet.get(i); + for (int j=0 ; j model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + List list = commonClassDao.getData(EnforcingType.class); + List dictList = new ArrayList<>(); + for(int i = 0; i < list.size(); i++){ + EnforcingType dict = (EnforcingType) list.get(i); + dictList.add(dict.getEnforcingType()); + } + model.put("enforcerDictionaryDatas", mapper.writeValueAsString(dictList)); + org.onap.policy.pap.xacml.rest.util.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={"/enforcer_dictionary/save_enforcerType"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveEnforcerDictionary(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()); + EnforcingType enforcingType = (EnforcingType)mapper.readValue(root.get("enforcerDictionaryData").toString(), EnforcingType.class); + if(enforcingType.getId() == 0){ + commonClassDao.save(enforcingType); + }else{ + commonClassDao.update(enforcingType); + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.getData(EnforcingType.class)); + JSONObject j = new JSONObject("{enforcerDictionaryDatas: " + 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; + } + + @RequestMapping(value={"/enforcer_dictionary/remove_enforcer"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeEnforcerDictionary(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()); + EnforcingType enforcingType = (EnforcingType)mapper.readValue(root.get("data").toString(), EnforcingType.class); + commonClassDao.delete(enforcingType); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(EnforcingType.class)); + JSONObject j = new JSONObject("{enforcerDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + System.out.println(e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java new file mode 100644 index 000000000..ee2d1d622 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java @@ -0,0 +1,2279 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.controller; + +import java.io.PrintWriter; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.jboss.netty.handler.ipfilter.CIDR; +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.adapters.GridData; +import org.onap.policy.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.ActionList; +import org.onap.policy.rest.jpa.AddressGroup; +import org.onap.policy.rest.jpa.FWTag; +import org.onap.policy.rest.jpa.FWTagPicker; +import org.onap.policy.rest.jpa.FirewallDictionaryList; +import org.onap.policy.rest.jpa.GroupServiceList; +import org.onap.policy.rest.jpa.PrefixList; +import org.onap.policy.rest.jpa.PortList; +import org.onap.policy.rest.jpa.ProtocolList; +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.rest.jpa.UserInfo; +import org.onap.policy.rest.jpa.Zone; +import org.onap.policy.xacml.api.XACMLErrorConstants; +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 +public class FirewallDictionaryController { + + private static final Logger LOGGER = FlexLogger.getLogger(FirewallDictionaryController.class); + + private static CommonClassDao commonClassDao; + + @Autowired + public FirewallDictionaryController(CommonClassDao commonClassDao){ + FirewallDictionaryController.commonClassDao = commonClassDao; + } + + public FirewallDictionaryController(){} + + public UserInfo getUserInfo(String loginId){ + UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + return name; + } + + + @RequestMapping(value={"/get_PrefixListDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPrefixListDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("prefixListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PrefixList.class, "prefixListName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_PrefixListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPrefixListDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("prefixListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PrefixList.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/fw_dictionary/save_prefixList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PrefixList prefixList; + if (fromAPI) { + prefixList = (PrefixList)mapper.readValue(root.get("dictionaryFields").toString(), PrefixList.class); + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(prefixList.getPrefixListName(), "prefixListName", PrefixList.class); + int id = 0; + PrefixList data = (PrefixList) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + prefixList.setId(1); + } else { + prefixList.setId(id); + } + } + } else { + prefixList = (PrefixList)mapper.readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); + } + if(prefixList.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(prefixList.getPrefixListName(), "prefixListName", PrefixList.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(prefixList); + } + }else{ + if(!isFakeUpdate) { + commonClassDao.update(prefixList); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(PrefixList.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{prefixListDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/fw_dictionary/remove_PrefixList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removePrefixListDictionary(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()); + PrefixList prefixList = (PrefixList)mapper.readValue(root.get("data").toString(), PrefixList.class); + commonClassDao.delete(prefixList); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.getData(PrefixList.class)); + JSONObject j = new JSONObject("{prefixListDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/fw_dictionary/validate_prefixList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView validatePrefixListDictionary(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()); + PrefixList prefixList = (PrefixList)mapper.readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); + String responseValidation = "success"; + try{ + CIDR.newCIDR(prefixList.getPrefixListValue()); + }catch(UnknownHostException e){ + responseValidation = "error"; + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{result: " + responseValidation + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/get_PortListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPortListDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("portListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PortList.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/fw_dictionary/save_portName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePortListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PortList portList = (PortList)mapper.readValue(root.get("portListDictionaryData").toString(), PortList.class); + if(portList.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(portList.getPortName(), "portName", PortList.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(portList); + } + }else{ + commonClassDao.update(portList); + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(PortList.class)); + } + JSONObject j = new JSONObject("{portListDictionaryDatas: " + responseString + "}"); + + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/fw_dictionary/remove_PortList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removePortListDictionary(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()); + PortList portList = (PortList)mapper.readValue(root.get("data").toString(), PortList.class); + commonClassDao.delete(portList); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.getData(PortList.class)); + JSONObject j = new JSONObject("{portListDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/get_ProtocolListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getProtocolListDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + model.put("protocolListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/get_ProtocolListDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getProtocolListDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + model.put("protocolListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ProtocolList.class, "protocolName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/fw_dictionary/save_protocolList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + ProtocolList protocolList; + if (fromAPI) { + protocolList = (ProtocolList)mapper.readValue(root.get("dictionaryFields").toString(), ProtocolList.class); + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(protocolList.getProtocolName(), "protocolName", ProtocolList.class); + int id = 0; + ProtocolList data = (ProtocolList) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + protocolList.setId(1); + } else { + protocolList.setId(id); + } + } + } else { + protocolList = (ProtocolList)mapper.readValue(root.get("protocolListDictionaryData").toString(), ProtocolList.class); + } + if(protocolList.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(protocolList.getProtocolName(), "protocolName", ProtocolList.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(protocolList); + } + }else{ + if(!isFakeUpdate){ + commonClassDao.update(protocolList); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{protocolListDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/fw_dictionary/remove_protocol"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeProtocolListDictionary(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()); + ProtocolList protocolList = (ProtocolList)mapper.readValue(root.get("data").toString(), ProtocolList.class); + commonClassDao.delete(protocolList); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class)); + JSONObject j = new JSONObject("{protocolListDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/get_AddressGroupDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getAddressGroupDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("addressGroupDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(AddressGroup.class, "name"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_AddressGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getAddressGroupDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("addressGroupDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/fw_dictionary/save_addressGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + AddressGroup addressGroup; + GridData gridData; + if (fromAPI) { + addressGroup = (AddressGroup)mapper.readValue(root.get("dictionaryFields").toString(), AddressGroup.class); + gridData = (GridData)mapper.readValue(root.get("dictionaryFields").toString(), GridData.class); + + if(!addressGroup.getGroupName().startsWith("Group_")){ + String groupName = "Group_"+addressGroup.getGroupName(); + addressGroup.setGroupName(groupName); + } + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class); + int id = 0; + AddressGroup data = (AddressGroup) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + addressGroup.setId(1); + } else { + addressGroup.setId(id); + } + } + } else { + addressGroup = (AddressGroup)mapper.readValue(root.get("addressGroupDictionaryData").toString(), AddressGroup.class); + gridData = (GridData)mapper.readValue(root.get("addressGroupDictionaryData").toString(), GridData.class); + if(!addressGroup.getGroupName().startsWith("Group_")){ + String groupName = "Group_"+addressGroup.getGroupName(); + addressGroup.setGroupName(groupName); + } + } + String userValue = ""; + int counter = 0; + if(gridData.getAttributes().size() > 0){ + for(Object attribute : gridData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("option").toString(); + if(counter>0){ + userValue = userValue + ","; + } + userValue = userValue + key ; + counter ++; + } + } + } + addressGroup.setServiceList(userValue); + if(addressGroup.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(addressGroup); + } + }else{ + if (!isFakeUpdate) { + commonClassDao.update(addressGroup); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class)); + } + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{addressGroupDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/fw_dictionary/remove_AddressGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeAddressGroupDictionary(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()); + AddressGroup addressGroup = (AddressGroup)mapper.readValue(root.get("data").toString(), AddressGroup.class); + commonClassDao.delete(addressGroup); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class)); + JSONObject j = new JSONObject("{addressGroupDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/get_ActionListDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getActionListDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + List list = commonClassDao.getData(ActionList.class); + List dictList = new ArrayList<>(); + for(int i = 0; i < list.size(); i++){ + ActionList dict = (ActionList) list.get(i); + dictList.add(dict.getActionName()); + } + model.put("actionListDictionaryDatas", mapper.writeValueAsString(dictList)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_ActionListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getActionListDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("actionListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ActionList.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/fw_dictionary/save_ActionList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + ActionList actionList; + if (fromAPI) { + actionList = (ActionList)mapper.readValue(root.get("dictionaryFields").toString(), ActionList.class); + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(actionList.getActionName(), "actionName", ActionList.class); + int id = 0; + ActionList data = (ActionList) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + actionList.setId(1); + } else { + actionList.setId(id); + } + } + } else { + actionList = (ActionList)mapper.readValue(root.get("actionListDictionaryData").toString(), ActionList.class); + } + if(actionList.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(actionList.getActionName(), "actionName", ActionList.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(actionList); + } + }else{ + if(!isFakeUpdate) { + commonClassDao.update(actionList); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(ActionList.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{actionListDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/fw_dictionary/remove_ActionList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeActionListDictionary(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()); + ActionList actionList = (ActionList)mapper.readValue(root.get("data").toString(), ActionList.class); + commonClassDao.delete(actionList); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.getData(ActionList.class)); + JSONObject j = new JSONObject("{actionListDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/get_ServiceGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getServiceGroupDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("serviceGroupDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/get_ServiceGroupDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getServiceGroupDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("serviceGroupDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(GroupServiceList.class, "name"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/fw_dictionary/save_serviceGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + GroupServiceList groupServiceList; + GridData gridData; + if (fromAPI) { + groupServiceList = (GroupServiceList)mapper.readValue(root.get("dictionaryFields").toString(), GroupServiceList.class); + gridData = (GridData)mapper.readValue(root.get("dictionaryFields").toString(), GridData.class); + + if(!groupServiceList.getGroupName().startsWith("Group_")){ + String groupName = "Group_"+groupServiceList.getGroupName(); + groupServiceList.setGroupName(groupName); + } + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(groupServiceList.getGroupName(), "name", GroupServiceList.class); + int id = 0; + GroupServiceList data = (GroupServiceList) duplicateData.get(0); + id = data.getId(); + + if(id==0){ + isFakeUpdate=true; + groupServiceList.setId(1); + } else { + groupServiceList.setId(id); + } + } + } else { + groupServiceList = (GroupServiceList)mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GroupServiceList.class); + gridData = (GridData)mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GridData.class); + } + if(!groupServiceList.getGroupName().startsWith("Group_")){ + String groupName = "Group_"+groupServiceList.getGroupName(); + groupServiceList.setGroupName(groupName); + } + String userValue = ""; + int counter = 0; + if(gridData.getAttributes().size() > 0){ + for(Object attribute : gridData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("option").toString(); + if(counter>0){ + userValue = userValue + ","; + } + userValue = userValue + key ; + counter ++; + } + } + } + groupServiceList.setServiceList(userValue); + if(groupServiceList.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(groupServiceList.getGroupName(), "name", GroupServiceList.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(groupServiceList); + } + }else{ + if(!isFakeUpdate) { + commonClassDao.update(groupServiceList); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{serviceGroupDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/fw_dictionary/remove_serviceGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeServiceGroupDictionary(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()); + GroupServiceList groupServiceList = (GroupServiceList)mapper.readValue(root.get("data").toString(), GroupServiceList.class); + commonClassDao.delete(groupServiceList); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class)); + JSONObject j = new JSONObject("{serviceGroupDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + System.out.println(e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/get_SecurityZoneDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getSecurityZoneDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("securityZoneDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(SecurityZone.class, "zoneName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_SecurityZoneData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getSecurityZoneDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("securityZoneDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/fw_dictionary/save_securityZone"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + SecurityZone securityZone; + if (fromAPI) { + securityZone = (SecurityZone)mapper.readValue(root.get("dictionaryFields").toString(), SecurityZone.class); + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(securityZone.getZoneName(), "zoneName", SecurityZone.class); + int id = 0; + SecurityZone data = (SecurityZone) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + securityZone.setId(1); + } else { + securityZone.setId(id); + } + } + } else { + securityZone = (SecurityZone)mapper.readValue(root.get("securityZoneDictionaryData").toString(), SecurityZone.class); + } + if(securityZone.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(securityZone.getZoneName(), "zoneName", SecurityZone.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(securityZone); + } + }else{ + if(!isFakeUpdate) { + commonClassDao.update(securityZone); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{securityZoneDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/fw_dictionary/remove_securityZone"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeSecurityZoneDictionary(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()); + SecurityZone securityZone = (SecurityZone)mapper.readValue(root.get("data").toString(), SecurityZone.class); + commonClassDao.delete(securityZone); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class)); + JSONObject j = new JSONObject("{securityZoneDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + + @RequestMapping(value={"/get_ServiceListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getServiceListDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("serviceListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(ServiceList.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/get_ServiceListDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getServiceListDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("serviceListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(ServiceList.class, "serviceName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/fw_dictionary/save_serviceList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + ServiceList serviceList; + GridData serviceListGridData; + if (fromAPI) { + serviceList = (ServiceList)mapper.readValue(root.get("dictionaryFields").toString(), ServiceList.class); + serviceListGridData = (GridData)mapper.readValue(root.get("dictionaryFields").toString(), GridData.class); + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(serviceList.getServiceName(), "serviceName", ServiceList.class); + int id = 0; + ServiceList data = (ServiceList) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + serviceList.setId(1); + } else { + serviceList.setId(id); + } + } + }else{ + serviceList = (ServiceList)mapper.readValue(root.get("serviceListDictionaryData").toString(), ServiceList.class); + serviceListGridData = (GridData)mapper.readValue(root.get("serviceListDictionaryData").toString(), GridData.class); + } + String tcpValue = ""; + int counter = 0; + if(serviceListGridData.getTransportProtocols().size() > 0){ + for(Object attribute : serviceListGridData.getTransportProtocols()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("option").toString(); + if(counter>0){ + tcpValue = tcpValue + ","; + } + tcpValue = tcpValue + key ; + counter ++; + } + } + } + serviceList.setServiceTransProtocol(tcpValue); + String appValue = ""; + int counter1 = 0; + if(serviceListGridData.getAppProtocols().size() > 0){ + for(Object attribute : serviceListGridData.getAppProtocols()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("option").toString(); + if(counter1>0){ + appValue = appValue + ","; + } + appValue = appValue + key ; + counter1 ++; + } + } + } + serviceList.setServiceAppProtocol(appValue); + serviceList.setServiceType("SERVICE"); + if(serviceList.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(serviceList.getServiceName(), "serviceName", ServiceList.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(serviceList); + } + }else{ + if(!isFakeUpdate) { + commonClassDao.update(serviceList); + } + } + + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(ServiceList.class)); + } + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{serviceListDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + + return null; + } + + @RequestMapping(value={"/fw_dictionary/remove_serviceList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeServiceListDictionary(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()); + ServiceList serviceList = (ServiceList)mapper.readValue(root.get("data").toString(), ServiceList.class); + commonClassDao.delete(serviceList); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(ServiceList.class)); + JSONObject j = new JSONObject("{serviceListDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + System.out.println(e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/get_ZoneData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getZoneDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("zoneDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(Zone.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error("Exception Occured"+e); + } + } + + @RequestMapping(value={"/get_ZoneDictionaryDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getZoneDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("zoneDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(Zone.class, "zoneName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/fw_dictionary/save_zoneName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + Zone zone; + if (fromAPI) { + zone = (Zone)mapper.readValue(root.get("dictionaryFields").toString(), Zone.class); + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(zone.getZoneName(), "zoneName", Zone.class); + int id = 0; + Zone data = (Zone) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + zone.setId(1); + } else { + zone.setId(id); + } + } + } else { + zone = (Zone)mapper.readValue(root.get("zoneDictionaryData").toString(), Zone.class); + } + if(zone.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(zone.getZoneName(), "zoneName", Zone.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(zone); + } + }else{ + if(!isFakeUpdate) { + commonClassDao.update(zone); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(Zone.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{zoneDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/fw_dictionary/remove_zone"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeZoneDictionary(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()); + Zone zone = (Zone)mapper.readValue(root.get("data").toString(), Zone.class); + commonClassDao.delete(zone); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(Zone.class)); + JSONObject j = new JSONObject("{zoneDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/get_TermListDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getTermListDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + model.put("termListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(TermList.class, "termName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_TermListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getTermListDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + model.put("termListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(TermList.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/fw_dictionary/save_termList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + TermList termList; + TermListData termListDatas; + String userId = null; + if (fromAPI) { + termList = (TermList)mapper.readValue(root.get("dictionaryFields").toString(), TermList.class); + termListDatas = (TermListData)mapper.readValue(root.get("dictionaryFields").toString(), TermListData.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(termList.getTermName(), "termName", TermList.class); + int id = 0; + TermList data = (TermList) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + termList.setId(1); + } else { + termList.setId(id); + } + termList.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + termList = (TermList)mapper.readValue(root.get("termListDictionaryData").toString(), TermList.class); + termListDatas = (TermListData)mapper.readValue(root.get("termListDictionaryData").toString(), TermListData.class); + userId = root.get("userid").textValue(); + } + String fromZoneValue = ""; + int counter = 0; + if(termListDatas.getFromZoneDatas().size() > 0){ + for(Object fromZone : termListDatas.getFromZoneDatas()){ + if(fromZone instanceof LinkedHashMap){ + String key = ((LinkedHashMap) fromZone).get("option").toString(); + if(counter>0){ + fromZoneValue = fromZoneValue + ","; + } + fromZoneValue = fromZoneValue + key ; + counter ++; + } + } + } + termList.setFromZones(fromZoneValue); + + String toZoneValue = ""; + int toZonecounter = 0; + if(termListDatas.getToZoneDatas().size() > 0){ + for(Object toZone : termListDatas.getToZoneDatas()){ + if(toZone instanceof LinkedHashMap){ + String key = ((LinkedHashMap) toZone).get("option").toString(); + if(toZonecounter>0){ + toZoneValue = toZoneValue + ","; + } + toZoneValue = toZoneValue + key ; + toZonecounter ++; + } + } + } + termList.setToZones(toZoneValue); + + String srcListValues = ""; + int srcListcounter = 0; + if(termListDatas.getSourceListDatas().size() > 0){ + for(Object srcList : termListDatas.getSourceListDatas()){ + if(srcList instanceof LinkedHashMap){ + String key = ((LinkedHashMap) srcList).get("option").toString(); + if(srcListcounter>0){ + srcListValues = srcListValues + ","; + } + srcListValues = srcListValues + key ; + srcListcounter ++; + } + } + } + termList.setSrcIPList(srcListValues); + + String desListValues = ""; + int destListcounter = 0; + if(termListDatas.getDestinationListDatas().size() > 0){ + for(Object desList : termListDatas.getDestinationListDatas()){ + if(desList instanceof LinkedHashMap){ + String key = ((LinkedHashMap) desList).get("option").toString(); + if(destListcounter>0){ + desListValues = desListValues + ","; + } + desListValues = desListValues + key ; + destListcounter ++; + } + } + } + termList.setDestIPList(desListValues); + + String srcSerValue = ""; + int srcSercounter = 0; + if(termListDatas.getSourceServiceDatas().size() > 0){ + for(Object srcSrc : termListDatas.getSourceServiceDatas()){ + if(srcSrc instanceof LinkedHashMap){ + String key = ((LinkedHashMap) srcSrc).get("option").toString(); + if(srcSercounter>0){ + srcSerValue = srcSerValue + ","; + } + srcSerValue = srcSerValue + key ; + srcSercounter ++; + } + } + } + termList.setSrcPortList(srcSerValue); + + String desSrcValue = ""; + int desSrccounter = 0; + if(termListDatas.getDestinationServiceDatas().size() > 0){ + for(Object desSrc : termListDatas.getDestinationServiceDatas()){ + if(desSrc instanceof LinkedHashMap){ + String key = ((LinkedHashMap) desSrc).get("option").toString(); + if(desSrccounter>0){ + desSrcValue = desSrcValue + ","; + } + desSrcValue = desSrcValue + key ; + desSrccounter ++; + } + } + } + termList.setDestPortList(desSrcValue); + + String actionValue = ""; + int actioncounter = 0; + if(termListDatas.getActionListDatas().size() > 0){ + for(Object actionList : termListDatas.getActionListDatas()){ + if(actionList instanceof LinkedHashMap){ + String key = ((LinkedHashMap) actionList).get("option").toString(); + if(actioncounter>0){ + actionValue = actionValue + ","; + } + actionValue = actionValue + key ; + actioncounter ++; + } + } + } + termList.setAction(actionValue); + + if(termList.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(termList.getTermName(), "termName", TermList.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + termList.setUserCreatedBy(this.getUserInfo(userId)); + termList.setUserModifiedBy(this.getUserInfo(userId)); + commonClassDao.save(termList); + } + }else{ + if(!isFakeUpdate) { + termList.setUserModifiedBy(this.getUserInfo(userId)); + commonClassDao.update(termList); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(TermList.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{termListDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/fw_dictionary/remove_termList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeTermListDictionary(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()); + TermList termList = (TermList)mapper.readValue(root.get("data").toString(), TermList.class); + commonClassDao.delete(termList); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(TermList.class)); + JSONObject j = new JSONObject("{termListDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + //ParentList Dictionary Data + @RequestMapping(value={"/get_FWDictionaryListDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getFWDictListDictionaryEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("fwDictListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FirewallDictionaryList.class, "parentItemName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_FWDictionaryListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getFWDictionaryListEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("fwDictListDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value={"/fw_dictionary/save_FWDictionaryList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveFWDictionaryList(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + FirewallDictionaryList fwDictList = (FirewallDictionaryList)mapper.readValue(root.get("fwDictListDictionaryData").toString(), FirewallDictionaryList.class); + GridData gridData = (GridData)mapper.readValue(root.get("fwDictListDictionaryData").toString(), GridData.class); + String userSLValue = ""; + int slcounter = 0; + if(gridData.getAttributes().size() > 0){ + for(Object attribute : gridData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("option").toString(); + if(slcounter>0){ + userSLValue = userSLValue + ","; + } + userSLValue = userSLValue + key ; + slcounter ++; + } + } + } + fwDictList.setServiceList(userSLValue); + String userALValue = ""; + int alcounter = 0; + if(gridData.getAlAttributes().size() > 0){ + for(Object attribute : gridData.getAlAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("option").toString(); + if(alcounter>0){ + userALValue = userALValue + ","; + } + userALValue = userALValue + key ; + alcounter ++; + } + } + } + fwDictList.setAddressList(userALValue); + if(fwDictList.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(fwDictList.getParentItemName(), "parentItemName", FirewallDictionaryList.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(fwDictList); + } + }else{ + commonClassDao.update(fwDictList); + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class)); + } + JSONObject j = new JSONObject("{fwDictListDictionaryDatas: " + responseString + "}"); + + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/fw_dictionary/remove_FWDictionaryList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeFWDictionaryListy(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()); + FirewallDictionaryList fwDictList = (FirewallDictionaryList)mapper.readValue(root.get("data").toString(), FirewallDictionaryList.class); + commonClassDao.delete(fwDictList); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class)); + JSONObject j = new JSONObject("{fwDictListDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + + @RequestMapping(value={"/get_TagPickerNameByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getTagPickerNameEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + model.put("fwTagPickerDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FWTagPicker.class, "tagPickerName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_TagPickerListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getTagPickerDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + model.put("fwTagPickerDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/fw_dictionary/save_fwTagPicker"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveFirewallTagPickerDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + + FWTagPicker fwTagPicker; + TagGridValues data; + String userId = null; + if (fromAPI) { + fwTagPicker = (FWTagPicker)mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), FWTagPicker.class); + data = (TagGridValues)mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), TagGridValues.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(fwTagPicker.getTagPickerName(), "tagPickerName", FWTagPicker.class); + int id = 0; + FWTagPicker dbdata = (FWTagPicker) duplicateData.get(0); + id = dbdata.getId(); + fwTagPicker.setId(id); + fwTagPicker.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + + fwTagPicker = (FWTagPicker)mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), FWTagPicker.class); + data = (TagGridValues)mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), TagGridValues.class); + userId = root.get("userid").textValue(); + } + + String header = ""; + int counter = 0; + if(data.getTags().size() > 0){ + for(Object attribute : data.getTags()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("option").toString(); + String value = ((LinkedHashMap) attribute).get("number").toString(); + if(counter>0){ + header = header + "#"; + } + header = header + key + ":"; + header = header + value; + counter ++; + } + } + } + fwTagPicker.setTagValues(header); + if(fwTagPicker.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(fwTagPicker.getTagPickerName(), "tagPickerName", FWTagPicker.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + fwTagPicker.setUserCreatedBy(this.getUserInfo(userId)); + fwTagPicker.setUserModifiedBy(this.getUserInfo(userId)); + commonClassDao.save(fwTagPicker); + } + }else{ + fwTagPicker.setUserModifiedBy(this.getUserInfo(userId)); + fwTagPicker.setModifiedDate(new Date()); + commonClassDao.update(fwTagPicker); + } + + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + responseString = "Success"; + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{fwTagPickerDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/fw_dictionary/remove_tagPicker"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeFirewallTagPickerDictionary(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()); + FWTagPicker fwTagPicker = (FWTagPicker)mapper.readValue(root.get("data").toString(), FWTagPicker.class); + commonClassDao.delete(fwTagPicker); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class)); + JSONObject j = new JSONObject("{fwTagPickerDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + + @RequestMapping(value={"/get_TagNameByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getTagNameEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("fwTagDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(FWTag.class, "fwTagName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/get_TagListData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getTagDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("fwTagDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(FWTag.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @RequestMapping(value={"/fw_dictionary/save_fwTag"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveFirewallTagDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + + FWTag fwTag; + TagGridValues tagGridValues; + String userId = null; + if (fromAPI) { + fwTag = (FWTag)mapper.readValue(root.get("fwTagDictionaryDatas").toString(), FWTag.class); + tagGridValues = (TagGridValues)mapper.readValue(root.get("fwTagDictionaryDatas").toString(), TagGridValues.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), "tagName", FWTag.class); + int id = 0; + FWTag data = (FWTag) duplicateData.get(0); + id = data.getId(); + fwTag.setId(id); + fwTag.setUserCreatedBy(this.getUserInfo(userId)); + + } + } else { + fwTag = (FWTag)mapper.readValue(root.get("fwTagDictionaryData").toString(), FWTag.class); + tagGridValues = (TagGridValues)mapper.readValue(root.get("fwTagDictionaryData").toString(), TagGridValues.class); + userId = root.get("userid").textValue(); + } + + String userValue = ""; + int counter = 0; + if(tagGridValues.getTags().size() > 0){ + for(Object attribute : tagGridValues.getTags()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("tags").toString(); + if(counter>0){ + userValue = userValue + ","; + } + userValue = userValue + key ; + counter ++; + } + } + } + fwTag.setTagValues(userValue); + if(fwTag.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), "fwTagName", FWTag.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + fwTag.setUserCreatedBy(this.getUserInfo(userId)); + fwTag.setUserModifiedBy(this.getUserInfo(userId)); + commonClassDao.save(fwTag); + } + }else{ + fwTag.setUserModifiedBy(this.getUserInfo(userId)); + fwTag.setModifiedDate(new Date()); + commonClassDao.update(fwTag); + } + + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(FWTag.class)); + } + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + responseString = "Success"; + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{fwTagDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + return null; + } + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/fw_dictionary/remove_tagList"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeFirewallTagDictionary(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()); + FWTag fwTag = (FWTag)mapper.readValue(root.get("data").toString(), FWTag.class); + commonClassDao.delete(fwTag); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(FWTag.class)); + JSONObject j = new JSONObject("{fwTagDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } +} + +class TagGridValues{ + private ArrayList tags; + + public ArrayList getTags() { + return tags; + } + + public void setTags(ArrayList tags) { + this.tags = tags; + } +} + +class AGGridData{ + private ArrayList attributes; + + public ArrayList getAttributes() { + return attributes; + } + + public void setAttributes(ArrayList attributes) { + this.attributes = attributes; + } +} + +class TermListData{ + private ArrayList fromZoneDatas; + private ArrayList toZoneDatas; + private ArrayList sourceListDatas; + private ArrayList destinationListDatas; + private ArrayList sourceServiceDatas; + private ArrayList destinationServiceDatas; + private ArrayList actionListDatas; + public ArrayList getFromZoneDatas() { + return fromZoneDatas; + } + public void setFromZoneDatas(ArrayList fromZoneDatas) { + this.fromZoneDatas = fromZoneDatas; + } + public ArrayList getToZoneDatas() { + return toZoneDatas; + } + public void setToZoneDatas(ArrayList toZoneDatas) { + this.toZoneDatas = toZoneDatas; + } + public ArrayList getSourceListDatas() { + return sourceListDatas; + } + public void setSourceListDatas(ArrayList sourceListDatas) { + this.sourceListDatas = sourceListDatas; + } + public ArrayList getDestinationListDatas() { + return destinationListDatas; + } + public void setDestinationListDatas(ArrayList destinationListDatas) { + this.destinationListDatas = destinationListDatas; + } + public ArrayList getSourceServiceDatas() { + return sourceServiceDatas; + } + public void setSourceServiceDatas(ArrayList sourceServiceDatas) { + this.sourceServiceDatas = sourceServiceDatas; + } + public ArrayList getDestinationServiceDatas() { + return destinationServiceDatas; + } + public void setDestinationServiceDatas(ArrayList destinationServiceDatas) { + this.destinationServiceDatas = destinationServiceDatas; + } + public ArrayList getActionListDatas() { + return actionListDatas; + } + public void setActionListDatas(ArrayList actionListDatas) { + this.actionListDatas = actionListDatas; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java new file mode 100644 index 000000000..621f0c474 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java @@ -0,0 +1,1051 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.controller; + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.DCAEuuid; +import org.onap.policy.rest.jpa.MicroServiceAttribute; +import org.onap.policy.rest.jpa.MicroServiceConfigName; +import org.onap.policy.rest.jpa.MicroServiceLocation; +import org.onap.policy.rest.jpa.MicroServiceModels; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.rest.util.MSAttributeObject; +import org.onap.policy.rest.util.MSModelUtils; +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; +import com.google.gson.Gson; + +@Controller +public class MicroServiceDictionaryController { + private static final Logger LOGGER = FlexLogger.getLogger(MicroServiceDictionaryController.class); + + private static CommonClassDao commonClassDao; + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + MicroServiceDictionaryController.commonClassDao = commonClassDao; + } + + @Autowired + public MicroServiceDictionaryController(CommonClassDao commonClassDao){ + MicroServiceDictionaryController.commonClassDao = commonClassDao; + } + + public MicroServiceDictionaryController(){} + + public UserInfo getUserInfo(String loginId){ + UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + return name; + } + + private static String SUCCESSKEY= "successMapKey"; + private static String SUCCESS = "success"; + private static String OPERATION = "operation"; + private static String GETDICTIONARY = "getDictionary"; + private static String ERROR = "error"; + private static String DICTIONARYDBQUERY = "dictionaryDBQuery"; + private HashMap classMap; + private List modelList = new ArrayList<>(); + + + + MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); + private MicroServiceModels newModel; + + + @RequestMapping(value={"/get_DCAEUUIDDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getDCAEUUIDDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("dcaeUUIDDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(DCAEuuid.class, "name"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(e); + } + } + + @RequestMapping(value={"/get_DCAEUUIDData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getDCAEUUIDDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("dcaeUUIDDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(DCAEuuid.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader(SUCCESSKEY, SUCCESS); + response.addHeader(OPERATION, GETDICTIONARY); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader(ERROR, DICTIONARYDBQUERY); + LOGGER.error(e.getMessage()); + } + } + + @RequestMapping(value={"/ms_dictionary/save_dcaeUUID"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + DCAEuuid dCAEuuid; + if (fromAPI) { + dCAEuuid = (DCAEuuid)mapper.readValue(root.get("dictionaryFields").toString(), DCAEuuid.class); + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter(OPERATION).equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(dCAEuuid.getName(), "name", DCAEuuid.class); + int id = 0; + DCAEuuid data = (DCAEuuid) duplicateData.get(0); + id = data.getId(); + if(id==0){ + isFakeUpdate=true; + dCAEuuid.setId(1); + } else { + dCAEuuid.setId(id); + } + } + } else { + dCAEuuid = (DCAEuuid)mapper.readValue(root.get("dcaeUUIDDictionaryData").toString(), DCAEuuid.class); + } + if(dCAEuuid.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(dCAEuuid.getName(), "name", DCAEuuid.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(dCAEuuid); + } + }else{ + if(!isFakeUpdate) { + commonClassDao.update(dCAEuuid); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(DCAEuuid.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{dcaeUUIDDictionaryDatas: " + 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; + } + + @RequestMapping(value={"/ms_dictionary/remove_dcaeuuid"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeDCAEUUIDDictionary(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()); + DCAEuuid dCAEuuid = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class); + commonClassDao.delete(dCAEuuid); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(DCAEuuid.class)); + JSONObject j = new JSONObject("{dcaeUUIDDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + + @RequestMapping(value={"/get_MicroServiceConfigNameDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getMicroServiceConfigNameByNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("microServiceCongigNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(MicroServiceConfigName.class, "name"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(e); + } + } + + + + @RequestMapping(value={"/get_MicroServiceConfigNameData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getMicroServiceConfigNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("microServiceCongigNameDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(MicroServiceConfigName.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader(SUCCESSKEY, SUCCESS); + response.addHeader(OPERATION, GETDICTIONARY); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader(ERROR, DICTIONARYDBQUERY); + LOGGER.error(e.getMessage()); + } + } + + @RequestMapping(value={"/ms_dictionary/save_configName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + MicroServiceConfigName microServiceConfigName; + if (fromAPI) { + microServiceConfigName = (MicroServiceConfigName)mapper.readValue(root.get("dictionaryFields").toString(), MicroServiceConfigName.class); + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter(OPERATION).equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(microServiceConfigName.getName(), "name", MicroServiceConfigName.class); + int id = 0; + MicroServiceConfigName data = (MicroServiceConfigName) duplicateData.get(0); + id = data.getId(); + + if(id==0){ + isFakeUpdate=true; + microServiceConfigName.setId(1); + } else { + microServiceConfigName.setId(id); + } + } + } else { + microServiceConfigName = (MicroServiceConfigName)mapper.readValue(root.get("microServiceCongigNameDictionaryData").toString(), MicroServiceConfigName.class); + } + if(microServiceConfigName.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(microServiceConfigName.getName(), "name", MicroServiceConfigName.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(microServiceConfigName); + } + }else{ + if(!isFakeUpdate) { + commonClassDao.update(microServiceConfigName); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceConfigName.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{microServiceCongigNameDictionaryDatas: " + 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; + } + + @RequestMapping(value={"/ms_dictionary/remove_msConfigName"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeMicroServiceConfigNameDictionary(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()); + MicroServiceConfigName microServiceConfigName = (MicroServiceConfigName)mapper.readValue(root.get("data").toString(), MicroServiceConfigName.class); + commonClassDao.delete(microServiceConfigName); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceConfigName.class)); + JSONObject j = new JSONObject("{microServiceCongigNameDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/get_MicroServiceLocationDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getMicroServiceLocationByNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("microServiceLocationDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(MicroServiceLocation.class, "name"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(e); + } + } + + @RequestMapping(value={"/get_MicroServiceLocationData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getMicroServiceLocationDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("microServiceLocationDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(MicroServiceLocation.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader(SUCCESSKEY, SUCCESS); + response.addHeader(OPERATION, GETDICTIONARY); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader(ERROR, DICTIONARYDBQUERY); + LOGGER.error(e.getMessage()); + } + } + + @RequestMapping(value={"/ms_dictionary/save_location"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + MicroServiceLocation microServiceLocation; + if (fromAPI) { + microServiceLocation = (MicroServiceLocation)mapper.readValue(root.get("dictionaryFields").toString(), MicroServiceLocation.class); + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter(OPERATION).equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(microServiceLocation.getName(), "name", MicroServiceLocation.class); + int id = 0; + MicroServiceLocation data = (MicroServiceLocation) duplicateData.get(0); + id = data.getId(); + + if(id==0){ + isFakeUpdate=true; + microServiceLocation.setId(1); + } else { + microServiceLocation.setId(id); + } + } + } else { + microServiceLocation = (MicroServiceLocation)mapper.readValue(root.get("microServiceLocationDictionaryData").toString(), MicroServiceLocation.class); + } + if(microServiceLocation.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(microServiceLocation.getName(), "name", MicroServiceLocation.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(microServiceLocation); + } + }else{ + if(!isFakeUpdate) { + commonClassDao.update(microServiceLocation); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceLocation.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{microServiceLocationDictionaryDatas: " + 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; + } + + @RequestMapping(value={"/ms_dictionary/remove_msLocation"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeMicroServiceLocationDictionary(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()); + MicroServiceLocation microServiceLocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class); + commonClassDao.delete(microServiceLocation); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceLocation.class)); + JSONObject j = new JSONObject("{microServiceLocationDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/get_MicroServiceAttributeDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getMicroServiceAttributeByNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("microServiceAttributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(MicroServiceAttribute.class, "name"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(e.getMessage()); + } + } + + @RequestMapping(value={"/get_MicroServiceAttributeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getMicroServiceAttributeDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("microServiceAttributeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(MicroServiceAttribute.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader(SUCCESSKEY, SUCCESS); + response.addHeader(OPERATION, GETDICTIONARY); + response.getWriter().write(j.toString()); + + } + catch (Exception e){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader(ERROR, DICTIONARYDBQUERY); + LOGGER.error(e.getMessage()); + } + } + + @RequestMapping(value={"/ms_dictionary/save_modelAttribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveMicroServiceAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + MicroServiceAttribute microServiceAttribute; + if (fromAPI) { + microServiceAttribute = (MicroServiceAttribute)mapper.readValue(root.get("dictionaryFields").toString(), MicroServiceAttribute.class); + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter(OPERATION).equals("update")) { + MicroServiceAttribute initialAttribute = (MicroServiceAttribute)mapper.readValue(root.get("initialFields").toString(), MicroServiceAttribute.class); + + String checkValue = initialAttribute.getName() + ":" + initialAttribute.getValue() + ":" + initialAttribute.getModelName(); + List duplicateData = commonClassDao.checkDuplicateEntry(checkValue, "name:value:modelName", MicroServiceAttribute.class); + int id=0; + for (int i= 0; i duplicateData = commonClassDao.checkDuplicateEntry(checkValue, "name:value:modelName", MicroServiceAttribute.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(microServiceAttribute); + } + }else{ + commonClassDao.update(microServiceAttribute); + } + + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceAttribute.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + responseString = "Success"; + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{microServiceAttributeDictionaryDatas: " + 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; + } + + @RequestMapping(value={"/ms_dictionary/remove_modelAttribute"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeMicroServiceAttributeDictionary(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()); + MicroServiceAttribute microServiceAttribute = (MicroServiceAttribute)mapper.readValue(root.get("data").toString(), MicroServiceAttribute.class); + commonClassDao.delete(microServiceAttribute); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(MicroServiceDictionaryController.commonClassDao.getData(MicroServiceAttribute.class)); + JSONObject j = new JSONObject("{microServiceAttributeDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(e.getMessage()); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + + @RequestMapping(value={"/get_MicroServiceModelsDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getMicroServiceModelsDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("microServiceModelsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(MicroServiceModels.class, "modelName"))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(e.getMessage()); + } + } + + @RequestMapping(value={"/get_MicroServiceModelsDataByVersion"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getMicroServiceModelsDictionaryByVersionEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + JsonNode root = mapper.readTree(request.getReader()); + String modelName = null; + if (root.get("microServiceModelsDictionaryData").has("modelName")){ + modelName = root.get("microServiceModelsDictionaryData").get("modelName").asText().replace("\"", ""); + } + if (modelName!=null){ + model.put("microServiceModelsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataById(MicroServiceModels.class, "modelName", modelName))); + } else{ + model.put(ERROR, "No model name given"); + } + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + LOGGER.error(e.getMessage()); + } + } + + @RequestMapping(value={"/get_MicroServiceModelsData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getMicroServiceModelsDictionaryEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("microServiceModelsDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(MicroServiceModels.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader(SUCCESSKEY, SUCCESS); + response.addHeader(OPERATION, GETDICTIONARY); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader(ERROR, DICTIONARYDBQUERY); + LOGGER.error(e.getMessage()); + } + } + + @RequestMapping(value={"/get_MicroServiceModelsDataServiceVersion"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getMicroServiceModelsDictionaryEntityDataServiceVersion(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + List data = new ArrayList<>(); + List datas = commonClassDao.getData(MicroServiceModels.class); + for(int i = 0; i < datas.size(); i++){ + MicroServiceModels msmodel = (MicroServiceModels) datas.get(i); + if (!data.contains(msmodel.getModelName())){ + data.add(msmodel.getModelName() + "-v" + msmodel.getVersion()); + } + } + model.put("microServiceModelsDictionaryDatas", mapper.writeValueAsString(data)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + + } + catch (Exception e){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + LOGGER.error(e); + } + } + + @RequestMapping(value={"/get_MicroServiceModelsDataByClass"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getMicroServiceModelsDictionaryClassEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("microServiceModelsDictionaryClassDatas", mapper.writeValueAsString(modelList)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader(SUCCESSKEY, SUCCESS); + response.addHeader(OPERATION, GETDICTIONARY); + response.getWriter().write(j.toString()); + + } + catch (Exception e){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader(ERROR, DICTIONARYDBQUERY); + LOGGER.error(e.getMessage()); + } + } + + @RequestMapping(value={"/ms_dictionary/save_model"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean fromAPI = false; + this.newModel = new MicroServiceModels(); + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + MicroServiceModels microServiceModels = new MicroServiceModels(); + String userId = null; + + if(root.has("modelType")){ + JsonNode dataType = root.get("modelType"); + String modelType= dataType.toString(); + if(modelType.contains("yml")){ + if (root.has("microServiceModelsDictionaryData")){ + if (root.get("microServiceModelsDictionaryData").has("description")){ + microServiceModels.setDescription(root.get("microServiceModelsDictionaryData").get("description").asText().replace("\"", "")); + } + if (root.get("microServiceModelsDictionaryData").has("modelName")){ + microServiceModels.setModelName(root.get("microServiceModelsDictionaryData").get("modelName").asText().replace("\"", "")); + this.newModel.setModelName(microServiceModels.getModelName()); + } + if (root.get("microServiceModelsDictionaryData").has("version")){ + microServiceModels.setVersion(root.get("microServiceModelsDictionaryData").get("version").asText().replace("\"", "")); + this.newModel.setVersion(microServiceModels.getVersion()); + } + } + + MSAttributeObject mainClass = null; + classMap = new HashMap<>(); + JsonNode data = root.get("classMap"); + ObjectMapper mapper1 = new ObjectMapper(); + String data1 = data.toString().substring(1, data.toString().length()-1); + data1 = data1.replace("\\", ""); + data1=data1.replace("\"{","{"); + data1=data1.replace("}\"","}"); + JSONObject jsonObject = new JSONObject(data1); + Set keys = jsonObject.keySet(); + for(String key : keys){ + String value = jsonObject.get(key).toString(); + MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class); + classMap.put(key, msAttributeObject); + } + + userId = root.get("userid").textValue(); + mainClass = classMap.get(this.newModel.getModelName()); + this.newModel.setDependency("[]"); + String value = new Gson().toJson(mainClass.getSubClass()); + this.newModel.setSub_attributes(value); + String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndexForAttributes= attributes.indexOf("="); + String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1); + this.newModel.setAttributes(atttributesAfterFirstEquals); + String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndex= refAttributes.indexOf("="); + String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1); + this.newModel.setRef_attributes(refAttributesAfterFirstEquals); + this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); + this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); + + }else{ + if (fromAPI) { + microServiceModels = (MicroServiceModels)mapper.readValue(root.get("dictionaryFields").toString(), MicroServiceModels.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter(OPERATION).equals("update")) { + String checkName = microServiceModels.getModelName() + ":" + microServiceModels.getVersion(); + List duplicateData = commonClassDao.checkDuplicateEntry(checkName, "modelName:version", MicroServiceModels.class); + int id = 0; + for (int i=0; i< duplicateData.size(); i++){ + MicroServiceModels data = (MicroServiceModels) duplicateData.get(0); + id = data.getId(); + } + microServiceModels.setId(id); + microServiceModels.setUserCreatedBy(this.getUserInfo(userId)); + + } + } else { + if (root.has("microServiceModelsDictionaryData")){ + if (root.get("microServiceModelsDictionaryData").has("description")){ + microServiceModels.setDescription(root.get("microServiceModelsDictionaryData").get("description").asText().replace("\"", "")); + } + if (root.get("microServiceModelsDictionaryData").has("modelName")){ + microServiceModels.setModelName(root.get("microServiceModelsDictionaryData").get("modelName").asText().replace("\"", "")); + this.newModel.setModelName(microServiceModels.getModelName()); + } + if (root.get("microServiceModelsDictionaryData").has("version")){ + microServiceModels.setVersion(root.get("microServiceModelsDictionaryData").get("version").asText().replace("\"", "")); + this.newModel.setVersion(microServiceModels.getVersion()); + } + } + if(root.has("classMap")){ + classMap = new HashMap<>(); + JsonNode data = root.get("classMap"); + ObjectMapper mapper1 = new ObjectMapper(); + String data1 = data.toString().substring(1, data.toString().length()-1); + data1 = data1.replace("\\", ""); + JSONObject jsonObject = new JSONObject(data1); + Set keys = jsonObject.keySet(); + for(String key : keys){ + String value = jsonObject.get(key).toString(); + MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class); + classMap.put(key, msAttributeObject); + } + } + userId = root.get("userid").textValue(); + addValuesToNewModel(classMap); + } + } + + } + microServiceModels.setAttributes(this.newModel.getAttributes()); + microServiceModels.setRef_attributes(this.newModel.getRef_attributes()); + microServiceModels.setDependency(this.newModel.getDependency()); + microServiceModels.setModelName(this.newModel.getModelName()); + microServiceModels.setSub_attributes(this.newModel.getSub_attributes()); + microServiceModels.setVersion(this.newModel.getVersion()); + microServiceModels.setEnumValues(this.newModel.getEnumValues()); + microServiceModels.setAnnotation(this.newModel.getAnnotation()); + + if(microServiceModels.getId() == 0){ + String checkName = microServiceModels.getModelName() + ":" + microServiceModels.getVersion(); + List duplicateData = commonClassDao.checkDuplicateEntry(checkName, "modelName:version", MicroServiceModels.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + microServiceModels.setUserCreatedBy(this.getUserInfo(userId)); + commonClassDao.save(microServiceModels); + } + }else{ + commonClassDao.update(microServiceModels); + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceModels.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + responseString = "Success"; + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{microServiceModelsDictionaryDatas: " + 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; + } + + @RequestMapping(value={"/ms_dictionary/remove_msModel"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removeMicroServiceModelsDictionary(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()); + MicroServiceModels microServiceModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class); + commonClassDao.delete(microServiceModels); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(MicroServiceModels.class)); + JSONObject j = new JSONObject("{microServiceModelsDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error(e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + private void addValuesToNewModel(HashMap classMap) { + new MicroServiceModels(); + //Loop through the classmap and pull out the required info for the new file. + MSAttributeObject mainClass = null; + ArrayList dependency = null; + String subAttribute = null; + + mainClass = classMap.get(this.newModel.getModelName()); + + if (mainClass !=null){ + String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""}); + dependency = new ArrayList(Arrays.asList(dependTemp.split(","))); + dependency = getFullDependencyList(dependency); + for (String element : dependency){ + MSAttributeObject temp = new MSAttributeObject(); + temp = classMap.get(element); + if (temp!=null){ + mainClass.addAllRefAttribute(temp.getRefAttribute()); + mainClass.addAllAttribute(temp.getAttribute()); + } + } + subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName()); + }else{ + subAttribute = "{}"; + this.newModel.setDependency(""); + } + + if (mainClass != null && mainClass.getDependency()==null){ + mainClass.setDependency(""); + } + if(mainClass != null){ + this.newModel.setDependency(mainClass.getDependency()); + this.newModel.setSub_attributes(subAttribute); + this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", "")); + this.newModel.setRef_attributes(mainClass.getRefAttribute().toString().replace("{", "").replace("}", "")); + this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); + this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); + } + } + + private ArrayList getFullDependencyList(ArrayList dependency) { + ArrayList returnList = new ArrayList<>(); + ArrayList workingList = new ArrayList<>(); + returnList.addAll(dependency); + for (String element : dependency ){ + if (classMap.containsKey(element)){ + MSAttributeObject value = classMap.get(element); + String rawValue = StringUtils.replaceEach(value.getDependency(), new String[]{"[", "]"}, new String[]{"", ""}); + workingList = new ArrayList(Arrays.asList(rawValue.split(","))); + for(String depend : workingList){ + if (!returnList.contains(depend) && !depend.isEmpty()){ + returnList.add(depend.trim()); + //getFullDepedency(workingList) + } + } + } + } + + return returnList; + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java new file mode 100644 index 000000000..c2dcbc651 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java @@ -0,0 +1,927 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.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.apache.commons.lang.StringUtils; +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.GroupPolicyScopeList; +import org.onap.policy.rest.jpa.PolicyScopeClosedLoop; +import org.onap.policy.rest.jpa.PolicyScopeResource; +import org.onap.policy.rest.jpa.PolicyScopeService; +import org.onap.policy.rest.jpa.PolicyScopeType; +import org.onap.policy.rest.jpa.UserInfo; +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 +public class PolicyScopeDictionaryController { + + private static final Logger LOGGER = FlexLogger.getLogger(PolicyScopeDictionaryController.class); + + private static CommonClassDao commonClassDao; + + @Autowired + public PolicyScopeDictionaryController(CommonClassDao commonClassDao){ + PolicyScopeDictionaryController.commonClassDao = commonClassDao; + } + + public PolicyScopeDictionaryController(){} + + private static String SUCCESSMAPKEY = "successMapKey"; + + public UserInfo getUserInfo(String loginId){ + UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + return name; + } + + @RequestMapping(value={"/get_GroupPolicyScopeDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getGroupPolicyScopeEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("groupPolicyScopeListDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(GroupPolicyScopeList.class, "name"))); + 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={"/get_GroupPolicyScopeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getGroupPolicyScopeEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("groupPolicyScopeListDatas", mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader(SUCCESSMAPKEY, "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + LOGGER.error(e); + } + } + + @RequestMapping(value={"/ps_dictionary/save_psGroupPolicyScope"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean duplicateGroupFlag = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + //GroupPolicyScopeList gpdata = (GroupPolicyScopeList)mapper.readValue(root.get("groupPolicyScopeListData").toString(), GroupPolicyScopeList.class); + GroupPolicyScopeList gpdata = null; + GroupPolicyScope groupData = null; + if (fromAPI) { + gpdata = (GroupPolicyScopeList)mapper.readValue(root.get("dictionaryFields").toString(), GroupPolicyScopeList.class); + try{ + groupData = (GroupPolicyScope)mapper.readValue(root.get("groupPolicyScopeListData1").toString(), GroupPolicyScope.class); + }catch(Exception e){ + groupData = new GroupPolicyScope(); + groupData.setResource(root.get("dictionaryFields").get("resource").toString().replace("\"", "")); + groupData.setClosedloop(root.get("dictionaryFields").get("closedloop").toString().replace("\"", "")); + groupData.setService(root.get("dictionaryFields").get("service").toString().replace("\"", "")); + groupData.setType(root.get("dictionaryFields").get("type").toString().replace("\"", "")); + } + + if(!gpdata.getGroupName().startsWith("PolicyScope")){ + String name = "PolicyScope_" + gpdata.getGroupName(); + gpdata.setGroupName(name); + } + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + + List duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupName(), "name", GroupPolicyScopeList.class); + int id = 0; + for (int i =0; i< duplicateData.size(); i++){ + GroupPolicyScopeList data = (GroupPolicyScopeList) duplicateData.get(0); + id = data.getId(); + } + + if(id==0){ + isFakeUpdate=true; + gpdata.setId(1); + } else { + gpdata.setId(id); + } + + } + } else { + gpdata = (GroupPolicyScopeList)mapper.readValue(root.get("groupPolicyScopeListData").toString(), GroupPolicyScopeList.class); + + try{ + groupData = (GroupPolicyScope)mapper.readValue(root.get("groupPolicyScopeListData1").toString(), GroupPolicyScope.class); + }catch(Exception e){ + groupData = new GroupPolicyScope(); + groupData.setResource(root.get("groupPolicyScopeListData1").get("resource").toString().replace("\"", "")); + groupData.setClosedloop(root.get("groupPolicyScopeListData1").get("closedloop").toString().replace("\"", "")); + groupData.setService(root.get("groupPolicyScopeListData1").get("service").toString().replace("\"", "")); + groupData.setType(root.get("groupPolicyScopeListData1").get("type").toString().replace("\"", "")); + } + if(!gpdata.getGroupName().startsWith("PolicyScope")){ + String name = "PolicyScope_" + gpdata.getGroupName(); + gpdata.setGroupName(name); + } + + } + ArrayList valueList = new ArrayList<>(); + String list = null; + String resourceValue = groupData.getResource(); + String typeValue = groupData.getType(); + String serviceValue = groupData.getService(); + String closedLoopValue = groupData.getClosedloop(); + valueList.add("resource=" + resourceValue); + valueList.add("service=" + serviceValue); + valueList.add("type=" + typeValue); + valueList.add("closedLoopControlName=" + closedLoopValue); + list = StringUtils.replaceEach(valueList.toString(), new String[]{"[", "]", " "}, new String[]{"", "", ""}); + gpdata.setGroupList(list); + if(!gpdata.getGroupName().startsWith("PolicyScope")){ + String name = "PolicyScope_" + gpdata.getGroupName(); + gpdata.setGroupName(name); + } + if(gpdata.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupName(), "name", GroupPolicyScopeList.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupList(), "groupList", GroupPolicyScopeList.class); + if(!duplicateData.isEmpty()){ + duplicateGroupFlag = true; + }else{ + commonClassDao.save(gpdata); + } + } + }else{ + if(!isFakeUpdate) { + List duplicateGroupList = commonClassDao.checkExistingGroupListforUpdate(gpdata.getGroupList(), gpdata.getGroupName()); + if(!duplicateGroupList.isEmpty()) { + duplicateGroupFlag = true; + } else { + commonClassDao.update(gpdata); + } + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else if(duplicateGroupFlag){ + responseString = "DuplicateGroup"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate") && !responseString.equals("DuplicateGroup")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{groupPolicyScopeListDatas: " + 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; + } + + @RequestMapping(value={"/ps_dictionary/remove_GroupPolicyScope"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removePSGroupScopeDictionary(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()); + GroupPolicyScopeList onapData = (GroupPolicyScopeList)mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class); + commonClassDao.delete(onapData); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class)); + JSONObject j = new JSONObject("{groupPolicyScopeListDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + System.out.println(e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/get_PSClosedLoopDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPSClosedLoopEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("psClosedLoopDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PolicyScopeClosedLoop.class, "name"))); + 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={"/get_PSClosedLoopData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPSClosedLoopEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("psClosedLoopDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader(SUCCESSMAPKEY, "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + LOGGER.error(e); + } + } + + @RequestMapping(value={"/ps_dictionary/save_psClosedLoop"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyScopeClosedLoop onapData; + if (fromAPI) { + onapData = (PolicyScopeClosedLoop)mapper.readValue(root.get("dictionaryFields").toString(), PolicyScopeClosedLoop.class); + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeClosedLoop.class); + int id = 0; + for (int i =0; i< duplicateData.size(); i++){ + PolicyScopeClosedLoop data = (PolicyScopeClosedLoop) duplicateData.get(0); + id = data.getId(); + } + + if(id==0){ + isFakeUpdate=true; + onapData.setId(1); + } else { + onapData.setId(id); + } + + } + } else { + onapData = (PolicyScopeClosedLoop)mapper.readValue(root.get("psClosedLoopDictionaryData").toString(), PolicyScopeClosedLoop.class); + } + if(onapData.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeClosedLoop.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(onapData); + } + }else{ + if(!isFakeUpdate) { + commonClassDao.update(onapData); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{psClosedLoopDictionaryDatas: " + 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; + } + + @RequestMapping(value={"/ps_dictionary/remove_PSClosedLoop"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removePSClosedLoopDictionary(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()); + PolicyScopeClosedLoop onapData = (PolicyScopeClosedLoop)mapper.readValue(root.get("data").toString(), PolicyScopeClosedLoop.class); + commonClassDao.delete(onapData); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class)); + JSONObject j = new JSONObject("{psClosedLoopDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + System.out.println(e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/get_PSServiceDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPSServiceEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("psServiceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PolicyScopeService.class, "name"))); + 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={"/get_PSServiceData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPSServiceEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("psServiceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader(SUCCESSMAPKEY, "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + LOGGER.error(e); + } + } + + @RequestMapping(value={"/ps_dictionary/save_psService"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyScopeService onapData; + if (fromAPI) { + onapData = (PolicyScopeService)mapper.readValue(root.get("dictionaryFields").toString(), PolicyScopeService.class); + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeService.class); + int id = 0; + for (int i =0; i< duplicateData.size(); i++){ + PolicyScopeService data = (PolicyScopeService) duplicateData.get(0); + id = data.getId(); + } + if(id==0){ + isFakeUpdate=true; + onapData.setId(1); + } else { + onapData.setId(id); + } + } + } else { + onapData = (PolicyScopeService)mapper.readValue(root.get("psServiceDictionaryData").toString(), PolicyScopeService.class); + } + if(onapData.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeService.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(onapData); + } + }else{ + if(!isFakeUpdate) { + commonClassDao.update(onapData); + } + } + + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{psServiceDictionaryDatas: " + 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; + } + + @RequestMapping(value={"/ps_dictionary/remove_PSService"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removePSServiceDictionary(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()); + PolicyScopeService onapData = (PolicyScopeService)mapper.readValue(root.get("data").toString(), PolicyScopeService.class); + commonClassDao.delete(onapData); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class)); + JSONObject j = new JSONObject("{psServiceDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + System.out.println(e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/get_PSTypeDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPSTypeEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("psTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PolicyScopeType.class, "name"))); + 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={"/get_PSTypeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPSTypeEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("psTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader(SUCCESSMAPKEY, "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + LOGGER.error(e); + } + } + + @RequestMapping(value={"/ps_dictionary/save_psType"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyScopeType onapData; + if (fromAPI) { + onapData = (PolicyScopeType)mapper.readValue(root.get("dictionaryFields").toString(), PolicyScopeType.class); + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeType.class); + int id = 0; + for (int i =0; i< duplicateData.size(); i++){ + PolicyScopeType data = (PolicyScopeType) duplicateData.get(0); + id = data.getId(); + } + + if(id==0){ + isFakeUpdate=true; + onapData.setId(1); + } else { + onapData.setId(id); + } + + } + } else { + onapData = (PolicyScopeType)mapper.readValue(root.get("psTypeDictionaryData").toString(), PolicyScopeType.class); + } + if(onapData.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeType.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(onapData); + } + }else{ + if(!isFakeUpdate) { + commonClassDao.update(onapData); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + + } else { + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{psTypeDictionaryDatas: " + 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; + } + + @RequestMapping(value={"/ps_dictionary/remove_PSType"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removePSTypeDictionary(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()); + PolicyScopeType onapData = (PolicyScopeType)mapper.readValue(root.get("data").toString(), PolicyScopeType.class); + commonClassDao.delete(onapData); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class)); + JSONObject j = new JSONObject("{psTypeDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + System.out.println(e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/get_PSResourceDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPSResourceEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("psResourceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(PolicyScopeResource.class, "name"))); + 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={"/get_PSResourceData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPSResourceEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("psResourceDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + LOGGER.error(e); + } + } + + @RequestMapping(value={"/ps_dictionary/save_psResource"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyScopeResource onapData; + if (fromAPI) { + onapData = (PolicyScopeResource)mapper.readValue(root.get("dictionaryFields").toString(), PolicyScopeResource.class); + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeResource.class); + int id = 0; + PolicyScopeResource data = (PolicyScopeResource) duplicateData.get(0); + id = data.getId(); + + if(id==0){ + isFakeUpdate=true; + onapData.setId(1); + } else { + onapData.setId(id); + } + } + } else { + onapData = (PolicyScopeResource)mapper.readValue(root.get("psResourceDictionaryData").toString(), PolicyScopeResource.class); + } + if(onapData.getId() == 0){ + List duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeResource.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(onapData); + } + }else{ + if(!isFakeUpdate) { + commonClassDao.update(onapData); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = "Duplicate"; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals("Duplicate")) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + + } else { + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{psResourceDictionaryDatas: " + 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; + } + + @RequestMapping(value={"/ps_dictionary/remove_PSResource"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removePSResourceDictionary(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()); + PolicyScopeResource onapData = (PolicyScopeResource)mapper.readValue(root.get("data").toString(), PolicyScopeResource.class); + commonClassDao.delete(onapData); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class)); + JSONObject j = new JSONObject("{psResourceDictionaryDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + System.out.println(e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } +} + +class GroupPolicyScope{ + String resource; + String type; + String service; + String closedloop; + public String getResource() { + return resource; + } + public void setResource(String resource) { + this.resource = resource; + } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public String getService() { + return service; + } + public void setService(String service) { + this.service = service; + } + public String getClosedloop() { + return closedloop; + } + public void setClosedloop(String closedloop) { + this.closedloop = closedloop; + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyController.java new file mode 100644 index 000000000..a545bb409 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyController.java @@ -0,0 +1,229 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.controller; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.net.URI; +import java.util.List; +import java.util.UUID; + +import javax.persistence.EntityManager; +import javax.persistence.Query; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +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.std.pap.StdPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.att.research.xacml.api.pap.PAPException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +public class PushPolicyController { + private static final Logger LOGGER = FlexLogger.getLogger(PushPolicyController.class); + + private static CommonClassDao commonClassDao; + + @Autowired + public PushPolicyController(CommonClassDao commonClassDao){ + PushPolicyController.commonClassDao = commonClassDao; + } + + public PushPolicyController(){} + + @RequestMapping(value="/pushPolicy", method=RequestMethod.POST) + public void pushPolicy(HttpServletRequest request, HttpServletResponse response){ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + try { + JsonNode root = mapper.readTree(request.getInputStream()); + String policyScope = root.get("policyScope").asText(); + String filePrefix = root.get("filePrefix").asText(); + String policyName = root.get("policyName").asText(); + String pdpGroup = root.get("pdpGroup").asText(); + String requestID = request.getHeader("X-ECOMP-RequestID"); + if(requestID==null){ + requestID = UUID.randomUUID().toString(); + LOGGER.info("No request ID provided, sending generated ID: " + requestID.toString()); + } + LOGGER.info("Push policy Request : " + root.asText()); + String policyVersionName = policyScope.replace(".", File.separator) + File.separator + + filePrefix + policyName; + List policyVersionObject = commonClassDao.getDataById(PolicyVersion.class, "policyName", policyVersionName); + if(policyVersionObject!=null){ + PolicyVersion policyVersion = (PolicyVersion) policyVersionObject.get(0); + String policyID = policyVersionName.replace(File.separator, "."); // This is before adding version. + policyVersionName += "." + policyVersion.getActiveVersion() + ".xml"; + addPolicyToGroup(policyScope, policyID, policyVersionName.replace(File.separator, "."), pdpGroup, response); + }else{ + String message = "Unknown Policy '" + policyName + "'"; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); + response.addHeader("error", "unknownPolicy"); + response.addHeader("operation", "push"); + response.addHeader("message", message); + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + return; + } + //safetyChecker(policyName); + } catch (NullPointerException | IOException e) { + LOGGER.error(e); + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + response.addHeader("error", "unknown"); + response.addHeader("operation", "push"); + return; + } + } + + private void addPolicyToGroup(String policyScope, String policyID, String policyName, String pdpGroup, HttpServletResponse response) { + StdPDPGroup selectedPDPGroup = null; + StdPDPPolicy selectedPolicy = null; + //Get the current policies from the Group and Add the new one + //Set currentPoliciesInGroup = null; + try { + selectedPDPGroup = (StdPDPGroup) XACMLPapServlet.getPAPEngine().getGroup(pdpGroup); + } catch (PAPException e1) { + PolicyLogger.error(e1); + } + if(selectedPDPGroup==null){ + String message = "Unknown groupId '" + selectedPDPGroup + "'"; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); + response.addHeader("error", "unknownGroupId"); + response.addHeader("operation", "push"); + response.addHeader("message", message); + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + return; + } + //Get PolicyEntity from DB; + EntityManager em = XACMLPapServlet.getEmf().createEntityManager(); + Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:policyName"); + createPolicyQuery.setParameter("scope", policyScope); + createPolicyQuery.setParameter("policyName", policyName.substring(policyScope.length()+1)); + List createPolicyQueryList = createPolicyQuery.getResultList(); + PolicyEntity policyEntity = null; + if(createPolicyQueryList.size()>0){ + policyEntity = (PolicyEntity)createPolicyQueryList.get(0); + }else{ + PolicyLogger.error("Somehow, more than one policy with the same scope, name, and deleted status were found in the database"); + String message = "Unknown Policy '" + policyName + "'"; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); + response.addHeader("error", "unknownPolicy"); + response.addHeader("operation", "push"); + response.addHeader("message", message); + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + return; + } + File temp = new File(policyName); + try { + BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); + bw.write(policyEntity.getPolicyData()); + bw.close(); + URI selectedURI = temp.toURI(); + // Create the policy Object + selectedPolicy = new StdPDPPolicy(policyName, true, policyID, selectedURI); + } catch (IOException e) { + LOGGER.error("Unable to create policy '" + policyName + "': "+ e.getMessage()); + } + try { + new ObjectOutputStream(response.getOutputStream()).writeObject(selectedPolicy); + } catch (IOException e) { + LOGGER.error(e); + response.addHeader("error", "policyCopyError"); + response.addHeader("message", e.getMessage()); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + response.addHeader("Content-Type","application/json"); + response.setStatus(HttpServletResponse.SC_ACCEPTED); + response.addHeader("operation", "push"); + response.addHeader("policyId", policyName); + return; + // TODO : Check point to push policies within PAP. + /*PolicyDBDaoTransaction addPolicyToGroupTransaction = XACMLPapServlet.getDbDaoTransaction(); + try{ + if (selectedPolicy != null) { + // Add Current policies from container + currentPoliciesInGroup = selectedPDPGroup.getPolicies(); + // copy policy to PAP + addPolicyToGroupTransaction.addPolicyToGroup(selectedPDPGroup.getId(), policyName,"XACMLPapServlet.pushPolicyController"); + ((StdPDPGroup) selectedPDPGroup).copyPolicyToFile(policyName, policyID, new FileInputStream(temp)); + addPolicyToGroupTransaction.commitTransaction(); + } + }catch (Exception e) { + addPolicyToGroupTransaction.rollbackTransaction(); + String message = "Policy '" + policyName + "' not copied to group '" + pdpGroup +"': " + e; + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.addHeader("error", "policyCopyError"); + response.addHeader("message", message); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + //If the selected policy is in the group we must remove it because the name is default + for (PDPPolicy existingPolicy : currentPoliciesInGroup) { + if (existingPolicy.getId().equals(selectedPolicy.getId())) { + selectedPDPGroup.removePolicyFromGroup(existingPolicy); + LOGGER.debug("Removing existing policy: " + existingPolicy); + break; + } + } + //Update the PDP Group after removing old version of policy + //Set updatedPoliciesInGroup = selectedPDPGroup.getPolicies(); + //need to remove the policy with default name from group + for (PDPPolicy updatedPolicy : currentPoliciesInGroup) { + if (updatedPolicy.getName().equalsIgnoreCase("default")) { + selectedPDPGroup.removePolicyFromGroup(updatedPolicy); + } + } + Set policies = selectedPDPGroup.getPolicies(); + policies.add(selectedPolicy); + selectedPDPGroup.setPolicies(policies); + // Update now. + try { + XACMLPapServlet.getPAPEngine().updateGroup(selectedPDPGroup); + } catch (PAPException e) { + // TODO Auto-generated catch block + logger.error("Exception Occured"+e); + } + // policy file copied ok and the Group was updated on the PDP + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + response.addHeader("operation", "push"); + response.addHeader("policyId", policyName); + response.addHeader("groupId", pdpGroup); + return;*/ + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java new file mode 100644 index 000000000..fad6a871f --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java @@ -0,0 +1,385 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.controller; + +import java.io.PrintWriter; +import java.util.Date; +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.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.RiskType; +import org.onap.policy.rest.jpa.SafePolicyWarning; +import org.onap.policy.rest.jpa.UserInfo; +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 +public class SafePolicyController { + + private static final Logger LOGGER = FlexLogger.getLogger(SafePolicyController.class); + + private static CommonClassDao commonClassDao; + + @Autowired + public SafePolicyController(CommonClassDao commonClassDao){ + SafePolicyController.commonClassDao = commonClassDao; + } + + public SafePolicyController(){} + + public UserInfo getUserInfo(String loginId){ + UserInfo name = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", loginId); + return name; + } + + private static String DUPLICATE = "Duplicate"; + + @RequestMapping(value = { "/get_RiskTypeDataByName" }, method = { + org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + public void getRiskTypeDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response) { + try { + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("riskTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getDataByColumn(RiskType.class, "name"))); + 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 = { "/get_RiskTypeData" }, method = { + org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + public void getOnapNameDictionaryEntityData(HttpServletRequest request, HttpServletResponse response) { + try { + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("riskTypeDictionaryDatas", mapper.writeValueAsString(commonClassDao.getData(RiskType.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } catch (Exception e) { + LOGGER.error(e.getMessage()); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + } + } + + @RequestMapping(value = { "/sp_dictionary/save_riskType" }, method = { + org.springframework.web.bind.annotation.RequestMethod.POST }) + public ModelAndView saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) + throws Exception { + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + RiskType riskTypeData; + String userId = null; + if (fromAPI) { + riskTypeData = (RiskType) mapper.readValue(root.get("dictionaryFields").toString(), + RiskType.class); + userId = "API"; + + //check if update operation or create, get id for data to be updated and update attributeData + if ("update".equalsIgnoreCase(request.getParameter("operation"))){ + List duplicateData = commonClassDao.checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class); + int id = 0; + RiskType data = (RiskType) duplicateData.get(0); + id = data.getId(); + + if(id==0){ + isFakeUpdate=true; + riskTypeData.setId(1); + } else { + riskTypeData.setId(id); + } + + riskTypeData.setUserCreatedBy(this.getUserInfo(userId)); + } + } else { + riskTypeData = (RiskType) mapper.readValue(root.get("riskTypeDictionaryData").toString(), RiskType.class); + userId = root.get("userid").textValue(); + } + + if (riskTypeData.getId() == 0) { + List duplicateData = commonClassDao.checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + riskTypeData.setUserCreatedBy(getUserInfo(userId)); + riskTypeData.setUserModifiedBy(getUserInfo(userId)); + commonClassDao.save(riskTypeData); + } + } else { + if (!isFakeUpdate) { + riskTypeData.setUserModifiedBy(this.getUserInfo(userId)); + riskTypeData.setModifiedDate(new Date()); + commonClassDao.update(riskTypeData); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = DUPLICATE; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(RiskType.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals(DUPLICATE)) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{riskTypeDictionaryDatas: " + 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; + } + + @RequestMapping(value = { "/sp_dictionary/remove_riskType" }, method = { + org.springframework.web.bind.annotation.RequestMethod.POST }) + public ModelAndView removeOnapDictionary(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()); + RiskType onapData = (RiskType) mapper.readValue(root.get("data").toString(), RiskType.class); + commonClassDao.delete(onapData); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(RiskType.class)); + JSONObject j = new JSONObject("{riskTypeDictionaryDatas: " + 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; + } + + @RequestMapping(value = { "/get_SafePolicyWarningDataByName" }, method = { + org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + public void getSafePolicyWarningEntityDataByName(HttpServletRequest request, HttpServletResponse response) { + try { + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("safePolicyWarningDatas", + mapper.writeValueAsString(commonClassDao.getDataByColumn(SafePolicyWarning.class, "name"))); + 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 = { "/get_SafePolicyWarningData" }, method = { + org.springframework.web.bind.annotation.RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE) + public void getSafePolicyWarningeEntityData(HttpServletRequest request, HttpServletResponse response) { + try { + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + model.put("safePolicyWarningDatas", + mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getDictionary"); + response.getWriter().write(j.toString()); + } catch (Exception e) { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + LOGGER.error(e.getMessage()); + } + } + + @RequestMapping(value = { "/sp_dictionary/save_safePolicyWarning" }, method = { + org.springframework.web.bind.annotation.RequestMethod.POST }) + public ModelAndView saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) + throws Exception { + try { + boolean duplicateflag = false; + boolean isFakeUpdate = false; + boolean fromAPI = false; + if (request.getParameter("apiflag")!=null && request.getParameter("apiflag").equalsIgnoreCase("api")) { + fromAPI = true; + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + SafePolicyWarning safePolicyWarning; + if (fromAPI) { + safePolicyWarning = (SafePolicyWarning) mapper + .readValue(root.get("dictionaryFields").toString(), SafePolicyWarning.class); + + //check if update operation or create, get id for data to be updated and update attributeData + if (request.getParameter("operation").equals("update")) { + List duplicateData = commonClassDao.checkDuplicateEntry(safePolicyWarning.getName(), "name", SafePolicyWarning.class); + int id = 0; + SafePolicyWarning data = (SafePolicyWarning) duplicateData.get(0); + id = data.getId(); + + if(id==0){ + isFakeUpdate=true; + safePolicyWarning.setId(1); + } else { + safePolicyWarning.setId(id); + } + } + } else { + safePolicyWarning = (SafePolicyWarning) mapper.readValue(root.get("safePolicyWarningData").toString(), SafePolicyWarning.class); + } + + if (safePolicyWarning.getId() == 0) { + List duplicateData = commonClassDao.checkDuplicateEntry(safePolicyWarning.getName(), "name", SafePolicyWarning.class); + if(!duplicateData.isEmpty()){ + duplicateflag = true; + }else{ + commonClassDao.save(safePolicyWarning); + } + } else { + if(!isFakeUpdate) { + commonClassDao.update(safePolicyWarning); + } + } + String responseString = ""; + if(duplicateflag){ + responseString = DUPLICATE; + }else{ + responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)); + } + + if (fromAPI) { + if (responseString!=null && !responseString.equals(DUPLICATE)) { + if(isFakeUpdate){ + responseString = "Exists"; + } else { + responseString = "Success"; + } + } + ModelAndView result = new ModelAndView(); + result.setViewName(responseString); + return result; + } else { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{safePolicyWarningDatas: " + 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; + } + + @RequestMapping(value = { "/sp_dictionary/remove_SafePolicyWarning" }, method = { + org.springframework.web.bind.annotation.RequestMethod.POST }) + public ModelAndView removeSafePolicyWarningDictionary(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()); + SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) mapper.readValue(root.get("data").toString(), + SafePolicyWarning.class); + commonClassDao.delete(safePolicyWarningData); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + String responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)); + JSONObject j = new JSONObject("{groupPolicyScopeListDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } catch (Exception e) { + System.out.println(e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/package-info.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/package-info.java new file mode 100644 index 000000000..bb42fb6aa --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/package-info.java @@ -0,0 +1,22 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.controller; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java new file mode 100644 index 000000000..2cc211701 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java @@ -0,0 +1,443 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.daoimpl; + +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +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.Criterion; +import org.hibernate.criterion.Disjunction; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.ClosedLoops; +import org.onap.policy.rest.jpa.GroupPolicyScopeList; +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 Log LOGGER = LogFactory.getLog(CommonClassDaoImpl.class); + + + private static SessionFactory sessionFactory; + + @Autowired + private CommonClassDaoImpl(SessionFactory sessionFactory){ + CommonClassDaoImpl.sessionFactory = sessionFactory; + } + + public CommonClassDaoImpl(){ + //Default Constructor + } + + @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; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @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; + } + + @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 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; + } + + + @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") + @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; + } + + + @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; + } + + + @SuppressWarnings("unchecked") + @Override + public void updateClAlarms(String clName, String alarms) { + Session session = sessionFactory.openSession(); + List closedloopsdata = null; + Transaction tx = session.beginTransaction(); + try { + Criteria cr = session.createCriteria(ClosedLoops.class); + cr.add(Restrictions.eq("closedLoopControlName",clName)); + closedloopsdata = cr.list(); + ClosedLoops closedloop = closedloopsdata.get(0); + closedloop.setAlarmConditions(alarms); + session.update(closedloop); + tx.commit(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e); + }finally{ + session.close(); + } + } + + + @SuppressWarnings("unchecked") + @Override + public void updateClYaml(String clName, String yaml) { + Session session = sessionFactory.openSession(); + List closedloopsdata = null; + Transaction tx = session.beginTransaction(); + try { + Criteria cr = session.createCriteria(ClosedLoops.class); + cr.add(Restrictions.eq("closedLoopControlName",clName)); + closedloopsdata = cr.list(); + ClosedLoops closedloop = closedloopsdata.get(0); + closedloop.setYaml(yaml); + session.update(closedloop); + tx.commit(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table"+e); + }finally{ + session.close(); + } + } + + + @SuppressWarnings("unchecked") + @Override + public void deleteAll() { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + List closedloopsdata = null; + try { + Criteria cr = session.createCriteria(ClosedLoops.class); + closedloopsdata = cr.list(); + + if(closedloopsdata!=null && !closedloopsdata.isEmpty()) { + LOGGER.info("ClosedLoops exist in the database, we need to delete them in our first step to buildCache()."); + for(int i=0; i < closedloopsdata.size(); i++) { + ClosedLoops cl = closedloopsdata.get(i); + session.delete(cl); + } + } else { + LOGGER.info("No ClosedLoops exist in the database, no need to delete."); + } + + tx.commit(); + }catch(Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while deleting ClosedLoops from the table"+e); + }finally{ + session.close(); + } + } + + @SuppressWarnings({ "unchecked"}) + @Override + public List checkExistingGroupListforUpdate(String groupListValue, String groupNameValue) { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + List data = null; + try { + Criteria cr = session.createCriteria(GroupPolicyScopeList.class); + cr.add(Restrictions.eq("groupList",groupListValue)); + Criterion expression = Restrictions.eq("name", groupNameValue); + cr.add(Restrictions.not(expression)); + data = cr.list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for GroupPolicyScopeList 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 List getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, String columnName, List data) { + return null; + } + +} \ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java new file mode 100644 index 000000000..dcd44f84f --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java @@ -0,0 +1,311 @@ +/*- + * ============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.pap.xacml.rest.elk.client; + +import java.io.FileInputStream; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.Iterator; +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 com.google.gson.Gson; + +import io.searchbox.client.JestClientFactory; +import io.searchbox.client.config.HttpClientConfig; +import io.searchbox.client.http.JestHttpClient; +import io.searchbox.core.Bulk; +import io.searchbox.core.Bulk.Builder; +import io.searchbox.core.BulkResult; +import io.searchbox.core.Index; +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; + + + +/** + * This code will deals with parsing the XACML content on reading from + * database(PolicyEntity, ConfigurationDataEntity and ActionBodyEntity tables) + * and convert the data into json to do bulk operation on putting to elastic search database. + * Which is used to support Elastic Search in Policy Application GUI to search policies. + * + * + * + * properties should be configured in policyelk.properties + * + */ +public class ElasticSearchPolicyUpdate { + + private static final Logger LOGGER = FlexLogger.getLogger(ElasticSearchPolicyUpdate.class); + protected final static JestClientFactory jestFactory = new JestClientFactory(); + + public static void main(String[] args) { + + String elkURL = null; + String databseUrl = null; + String userName = null; + String password = null; + String databaseDriver = null; + + String propertyFile = System.getProperty("PROPERTY_FILE"); + Properties config = new Properties(); + Path file = Paths.get(propertyFile); + if(Files.notExists(file)){ + LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString()); + }else{ + if(file.toString().endsWith(".properties")){ + try { + InputStream in = new FileInputStream(file.toFile()); + config.load(in); + elkURL = config.getProperty("policy.elk.url"); + databseUrl = config.getProperty("policy.database.url"); + userName = config.getProperty("policy.database.username"); + password = config.getProperty("policy.database.password"); + databaseDriver = config.getProperty("policy.database.driver"); + if(elkURL == null || databseUrl == null || userName == null || password == null || databaseDriver == null){ + LOGGER.error("One of the Property is null in policyelk.properties = elkurl:databaseurl:username:password:databasedriver " + + elkURL + ":"+ databseUrl + ":"+ userName + ":"+ password + ":"+ databaseDriver + ":"); + } + } catch (Exception e) { + LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString()); + } + } + } + + Builder bulk = null; + + HttpClientConfig httpClientConfig = new HttpClientConfig.Builder(elkURL).multiThreaded(true).build(); + jestFactory.setHttpClientConfig(httpClientConfig); + JestHttpClient client = (JestHttpClient) jestFactory.getObject(); + + Connection conn = null; + Statement stmt = null; + + List listIndex = new ArrayList(); + + try { + Class.forName(databaseDriver); + conn = DriverManager.getConnection(databseUrl, userName, password); + stmt = conn.createStatement(); + + String policyEntityQuery = "Select * from PolicyEntity"; + ResultSet result = stmt.executeQuery(policyEntityQuery); + + while(result.next()){ + StringBuilder policyDataString = new StringBuilder("{"); + String scope = result.getString("scope"); + String policyName = result.getString("policyName"); + if(policyName != null){ + policyDataString.append("\"policyName\":\""+scope+"."+policyName+"\","); + } + String description = result.getString("description"); + if(description != null){ + policyDataString.append("\"policyDescription\":\""+description+"\","); + } + Object policyData = result.getString("policydata"); + + if(scope != null){ + policyDataString.append("\"scope\":\""+scope+"\","); + } + String actionbodyid = result.getString("actionbodyid"); + String configurationdataid = result.getString("configurationdataid"); + + + String policyWithScopeName = scope + "." + policyName; + String _type = null; + + if(policyWithScopeName.contains(".Config_")){ + policyDataString.append("\"policyType\":\"Config\","); + if(policyWithScopeName.contains(".Config_Fault_")){ + _type = "closedloop"; + policyDataString.append("\"configPolicyType\":\"ClosedLoop_Fault\","); + }else if(policyWithScopeName.contains(".Config_PM_")){ + _type = "closedloop"; + policyDataString.append("\"configPolicyType\":\"ClosedLoop_PM\","); + }else{ + _type = "config"; + policyDataString.append("\"configPolicyType\":\"Base\","); + } + }else if(policyWithScopeName.contains(".Action_")){ + _type = "action"; + policyDataString.append("\"policyType\":\"Action\","); + }else if(policyWithScopeName.contains(".Decision_")){ + _type = "decision"; + policyDataString.append("\"policyType\":\"Decision\","); + } + + if(!"decision".equals(_type)){ + if(configurationdataid != null){ + String configEntityQuery = "Select * from ConfigurationDataEntity where configurationDataId = "+configurationdataid+""; + Statement configstmt = conn.createStatement(); + ResultSet configResult = configstmt.executeQuery(configEntityQuery); + while(configResult.next()){ + String configBody = configResult.getString("configbody"); + String configType = configResult.getString("configtype"); + if("JSON".equalsIgnoreCase(configType)){ + policyDataString.append("\"jsonBodyData\":"+configBody+",\"configType\":\""+configType+"\","); + }else if("OTHER".equalsIgnoreCase(configType)){ + if(configBody!=null){ + configBody= configBody.replaceAll("\"", ""); + policyDataString.append("\"jsonBodyData\":\""+configBody+"\",\"configType\":\""+configType+"\","); + } + } + } + configResult.close(); + } + + if(actionbodyid != null){ + String actionEntityQuery = "Select * from ActionBodyEntity where actionBodyId = "+actionbodyid+""; + Statement actionstmt = conn.createStatement(); + ResultSet actionResult = actionstmt.executeQuery(actionEntityQuery); + while(actionResult.next()){ + String actionBody = actionResult.getString("actionbody"); + policyDataString.append("\"jsonBodyData\":"+actionBody+","); + } + actionResult.close(); + } + } + + String _id = policyWithScopeName; + + policyDataString.append(constructPolicyData(policyData, policyDataString)); + + String dataString = policyDataString.toString(); + dataString = dataString.substring(0, dataString.length()-1); + dataString = dataString.trim().replace(System.getProperty("line.separator"), "") + "}"; + dataString = dataString.replace("null", "\"\""); + dataString = dataString.replaceAll(" ", "").replaceAll("\n", ""); + + try{ + Gson gson = new Gson(); + gson.fromJson(dataString, Object.class); + }catch(Exception e){ + continue; + } + + if("config".equals(_type)){ + listIndex.add(new Index.Builder(dataString).index("policy").type("config").id(_id).build()); + }else if("closedloop".equals(_type)){ + listIndex.add(new Index.Builder(dataString).index("policy").type("closedloop").id(_id).build()); + }else if("action".equals(_type)){ + listIndex.add(new Index.Builder(dataString).index("policy").type("action").id(_id).build()); + }else if("decision".equals(_type)){ + listIndex.add(new Index.Builder(dataString).index("policy").type("decision").id(_id).build()); + } + } + + result.close(); + bulk = new Bulk.Builder(); + for(int i =0; i < listIndex.size(); i++){ + bulk.addAction(listIndex.get(i)); + } + BulkResult searchResult = client.execute(bulk.build()); + if(searchResult.isSucceeded()){ + LOGGER.debug("Success"); + }else{ + LOGGER.error("Failure"); + } + } catch (Exception e) { + LOGGER.error("Exception Occured while performing database Operation for Elastic Search Policy Upgrade"+e); + }finally{ + if(conn != null){ + try { + conn.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the connection"+e); + } + } + } + } + + private static String constructPolicyData(Object policyData, StringBuilder policyDataString){ + if(policyData instanceof PolicyType){ + PolicyType policy = (PolicyType) policyData; + 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 ("ONAPName".equals(attributeId)) { + policyDataString.append("\"onapName\":\""+value+"\","); + } + if ("RiskType".equals(attributeId)){ + policyDataString.append("\"riskType\":\""+value+"\","); + } + if ("RiskLevel".equals(attributeId)){ + policyDataString.append("\"riskLevel\":\""+value+"\","); + } + if ("guard".equals(attributeId)){ + policyDataString.append("\"guard\":\""+value+"\","); + } + if ("ConfigName".equals(attributeId)){ + policyDataString.append("\"configName\":\""+value+"\","); + } + } + } + } + } + } + } + } + } + return policyDataString.toString(); + } + +} \ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java new file mode 100644 index 000000000..1dea5dd4b --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.elk.client; + + +import java.util.Map; + +import org.onap.policy.rest.adapter.PolicyRestAdapter; + +import io.searchbox.client.JestResult; + +public interface ElkConnector { + + public static final String ELK_URL = "http://localhost:9200"; + public static final String ELK_INDEX_POLICY = "policy"; + + public enum PolicyIndexType { + config, + action, + decision, + closedloop, + all, + } + + public enum PolicyType { + Config, + Action, + Decision, + Config_Fault, + Config_PM, + Config_FW, + Config_MS, + none, + } + + public enum PolicyBodyType { + json, + xml, + properties, + txt, + none, + } + + public boolean delete(PolicyRestAdapter policyData) + throws IllegalStateException; + + public JestResult search(PolicyIndexType type, String text) + throws IllegalStateException, IllegalArgumentException; + + public JestResult search(PolicyIndexType type, String text, + Map searchKeyValue) + throws IllegalStateException, IllegalArgumentException; + + public boolean update(PolicyRestAdapter policyData) throws IllegalStateException; + + public ElkConnector singleton = new ElkConnectorImpl(); + + public static PolicyIndexType toPolicyIndexType(String policyName) + throws IllegalArgumentException { + if (policyName == null) + throw new IllegalArgumentException("Unsupported NULL policy name conversion"); + + if (policyName.startsWith("Config_Fault")) { + return PolicyIndexType.closedloop; + } else if (policyName.startsWith("Config_PM")) { + return PolicyIndexType.closedloop; + } else if (policyName.startsWith("Config_FW")) { + return PolicyIndexType.config; + } else if (policyName.startsWith("Config_MS")) { + return PolicyIndexType.config; + }else if (policyName.startsWith("Action")) { + return PolicyIndexType.action; + } else if (policyName.startsWith("Decision")) { + return PolicyIndexType.decision; + } else if (policyName.startsWith("Config")) { + return PolicyIndexType.config; + } else { + throw new IllegalArgumentException + ("Unsupported policy name conversion to index: " + + policyName); + } + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java new file mode 100644 index 000000000..8868db3bc --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java @@ -0,0 +1,418 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.elk.client; + +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; + +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.index.query.QueryStringQueryBuilder; +import org.elasticsearch.search.builder.SearchSourceBuilder; +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.xacml.api.XACMLErrorConstants; + +import io.searchbox.action.Action; +import io.searchbox.client.JestClient; +import io.searchbox.client.JestClientFactory; +import io.searchbox.client.JestResult; +import io.searchbox.client.config.HttpClientConfig; +import io.searchbox.core.Delete; +import io.searchbox.core.Index; +import io.searchbox.core.Search; +import io.searchbox.core.Search.Builder; +import io.searchbox.indices.IndicesExists; +import io.searchbox.indices.type.TypeExist; +import io.searchbox.params.Parameters; + +public class ElkConnectorImpl implements ElkConnector{ + + private static final Logger LOGGER = FlexLogger.getLogger(ElkConnector.class); + + protected final JestClientFactory jestFactory = new JestClientFactory(); + protected final JestClient jestClient; + protected static int QUERY_MAXRECORDS = 1000; + + public ElkConnectorImpl() { + if (LOGGER.isDebugEnabled()){ + LOGGER.debug("ENTER: -"); + } + HttpClientConfig jestClientConfig = new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build(); + jestFactory.setHttpClientConfig(jestClientConfig); + jestClient = jestFactory.getObject(); + } + + protected boolean isType(PolicyIndexType type) throws IOException { + if (LOGGER.isDebugEnabled()){ + LOGGER.debug("ENTER: -"); + } + + try { + Action typeQuery = new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build(); + JestResult result = jestClient.execute(typeQuery); + + if (LOGGER.isInfoEnabled()) { + LOGGER.info("JSON:" + result.getJsonString()); + LOGGER.info("ERROR:" + result.getErrorMessage()); + LOGGER.info("PATH:" + result.getPathToResult()); + LOGGER.info(result.getJsonObject()); + } + return result.isSucceeded(); + } catch (IOException e) { + LOGGER.warn("Error checking type existance of " + type.toString() + ": " + e.getMessage(), e); + throw e; + } + } + + protected boolean isIndex() throws IOException { + try { + Action indexQuery = new IndicesExists.Builder(ELK_INDEX_POLICY).build(); + + JestResult result = jestClient.execute(indexQuery); + if (LOGGER.isInfoEnabled()) { + LOGGER.info("JSON:" + result.getJsonString()); + LOGGER.info("ERROR:" + result.getErrorMessage()); + LOGGER.info("PATH:" + result.getPathToResult()); + LOGGER.info(result.getJsonObject()); + } + return result.isSucceeded(); + } catch (IOException e) { + LOGGER.warn("Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), e); + throw e; + } + } + + @Override + public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException { + if (LOGGER.isTraceEnabled()){ + LOGGER.trace("ENTER: " + text); + } + + if (text == null || text.isEmpty()) { + throw new IllegalArgumentException("No search string provided"); + } + + QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery("*"+text+"*"); + SearchSourceBuilder searchSourceBuilder = + new SearchSourceBuilder().query(mQ); + + Builder searchBuilder = new Search.Builder(searchSourceBuilder.toString()). + addIndex(ELK_INDEX_POLICY). + setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS); + + if (type == null || type == PolicyIndexType.all) { + for (PolicyIndexType pT: PolicyIndexType.values()) { + if (pT != PolicyIndexType.all) { + searchBuilder.addType(pT.toString()); + } + } + } else { + searchBuilder.addType(type.toString()); + } + + Search search = searchBuilder.build(); + JestResult result; + try { + result = jestClient.execute(search); + } catch (IOException ioe) { + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + search + ": " + ioe.getMessage(), ioe); + throw new IllegalStateException(ioe); + } + + if (result.isSucceeded()) { + if (LOGGER.isInfoEnabled()){ + LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + + result.getPathToResult() + ":" + System.lineSeparator() + + result.getJsonString()); + } + } else { + /* Unsuccessful search */ + if (LOGGER.isWarnEnabled()){ + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + + result.getResponseCode() + ": " + + search.getURI() + ":" + + result.getPathToResult() + ":" + + result.getJsonString() + ":" + + result.getErrorMessage()); + } + + String errorMessage = result.getErrorMessage(); + if (errorMessage != null && !errorMessage.isEmpty()) { + String xMessage = errorMessage; + if (errorMessage.contains("TokenMgrError")) { + int indexError = errorMessage.lastIndexOf("TokenMgrError"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("QueryParsingException")) { + int indexError = errorMessage.lastIndexOf("QueryParsingException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("JsonParseException")) { + int indexError = errorMessage.lastIndexOf("JsonParseException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("Parse Failure")) { + int indexError = errorMessage.lastIndexOf("Parse Failure"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("SearchParseException")) { + int indexError = errorMessage.lastIndexOf("SearchParseException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else { + xMessage = result.getErrorMessage(); + } + throw new IllegalStateException(xMessage); + } + } + + return result; + } + + + @Override + public JestResult search(PolicyIndexType type, String text, + Map filter_s) + throws IllegalStateException, IllegalArgumentException { + if (LOGGER.isTraceEnabled()){ + LOGGER.trace("ENTER: " + text); + } + + if (filter_s == null || filter_s.size() == 0) { + return search(type, text); + } + + String matches_s = ""; + matches_s = "{\n" + + " \"size\" : "+ ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + + " \"query\": {\n" + + " \"bool\" : {\n" + + " \"must\" : ["; + + String match_params = ""; + boolean first = true; + for(Entry entry : filter_s.entrySet()){ + String key = entry.getKey(); + String value = entry.getValue(); + if(first){ + match_params = "\"match\" : {\""+key+"\" : \""+value+"\" }},"; + first = false; + }else{ + match_params = match_params + "{\"match\" : { \""+key+"\" : \""+value+"\" } },"; + } + } + if(match_params.endsWith(",")){ + match_params = match_params.substring(0, match_params.length()-2); + } + + matches_s = matches_s + "{\n" + match_params + "\n}" ; + + boolean query = false; + String query_String = ""; + if(text != null){ + query = true; + query_String = "{\n \"query_string\" : {\n \"query\" : \"*"+text+"*\"\n} \n}"; + } + + if(query){ + matches_s = matches_s + "," + query_String + "]\n}\n}\n}"; + }else{ + matches_s = matches_s + "]\n}\n}\n}"; + } + + Builder searchBuilder = new Search.Builder(matches_s).addIndex(ELK_INDEX_POLICY); + + if (type == null || type == PolicyIndexType.all) { + for (PolicyIndexType pT: PolicyIndexType.values()) { + if (pT != PolicyIndexType.all) { + searchBuilder.addType(pT.toString()); + } + } + } else { + searchBuilder.addType(type.toString()); + } + + Search search = searchBuilder.build(); + + JestResult result; + try { + result = jestClient.execute(search); + } catch (IOException ioe) { + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + + search + ": " + ioe.getMessage(), ioe); + throw new IllegalStateException(ioe); + } + + if (result.isSucceeded()) { + if (LOGGER.isInfoEnabled()){ + LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + + result.getPathToResult() + ":" + System.lineSeparator() + + result.getJsonString()); + } + } else { + /* Unsuccessful search */ + if (LOGGER.isWarnEnabled()){ + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + + result.getResponseCode() + ": " + + search.getURI() + ":" + + result.getPathToResult() + ":" + + result.getJsonString() + ":" + + result.getErrorMessage()); + } + + String errorMessage = result.getErrorMessage(); + if (errorMessage != null && !errorMessage.isEmpty()) { + String xMessage = errorMessage; + if (errorMessage.contains("TokenMgrError")) { + int indexError = errorMessage.lastIndexOf("TokenMgrError"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("QueryParsingException")) { + int indexError = errorMessage.lastIndexOf("QueryParsingException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("JsonParseException")) { + int indexError = errorMessage.lastIndexOf("JsonParseException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("Parse Failure")) { + int indexError = errorMessage.lastIndexOf("Parse Failure"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else if (errorMessage.contains("SearchParseException")) { + int indexError = errorMessage.lastIndexOf("SearchParseException"); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); + } else { + xMessage = result.getErrorMessage(); + } + throw new IllegalStateException(xMessage); + } + } + + return result; + } + + public boolean put(PolicyRestAdapter policyData) + throws IOException, IllegalStateException { + if (LOGGER.isTraceEnabled()) LOGGER.trace("ENTER"); + + PolicyIndexType indexType; + try { + String policyName = policyData.getNewFileName(); + if(policyName.contains("Config_")){ + policyName = policyName.replace(".Config_", ":Config_"); + }else if(policyName.contains("Action_")){ + policyName = policyName.replace(".Action_", ":Action_"); + }else if(policyName.contains("Decision_")){ + policyName = policyName.replace(".Decision_", ":Decision_"); + } + + String[] splitPolicyName = policyName.split(":"); + indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]); + } catch (IllegalArgumentException e) { + throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + e.getMessage()); + } + PolicyElasticData elasticData = new PolicyElasticData(policyData); + JSONObject jsonObj = new JSONObject(elasticData); + Index elkPut = new Index.Builder(jsonObj.toString()). + index(ELK_INDEX_POLICY). + type(indexType.name()). + id(elasticData.getPolicyName()). + refresh(true). + build(); + + JestResult result = jestClient.execute(elkPut); + + if (result.isSucceeded()) { + if (LOGGER.isInfoEnabled()) + LOGGER.info("OK: PUT operation of " + "->" + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); + } else { + if (LOGGER.isWarnEnabled()) + LOGGER.warn("FAILURE: PUT operation of "+ "->" + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); + + } + + return result.isSucceeded(); + } + + @Override + public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException { + PolicyIndexType indexType = null; + JestResult result; + try { + String policyName = policyData.getNewFileName(); + if(policyName.contains("Config_")){ + policyName = policyName.replace(".Config_", ":Config_"); + }else if(policyName.contains("Action_")){ + policyName = policyName.replace(".Action_", ":Action_"); + }else if(policyName.contains("Decision_")){ + policyName = policyName.replace(".Decision_", ":Decision_"); + } + + String[] splitPolicyName = policyName.split(":"); + indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]); + if (!isType(indexType)) { + throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + + " Type: " + indexType + + " is not configured"); + } + PolicyElasticData elasticData = new PolicyElasticData(policyData); + Delete deleteRequest = new Delete.Builder(elasticData.getPolicyName()).index(ELK_INDEX_POLICY). + type(indexType.name()).build(); + result = jestClient.execute(deleteRequest); + } catch (IllegalArgumentException | IOException e) { + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ": delete:" + + indexType + ": null" + ":" + policyData.getNewFileName() + ": " + + e.getMessage(), e); + throw new IllegalStateException(e); + } + + if (result.isSucceeded()) { + if (LOGGER.isInfoEnabled()) + LOGGER.info("OK: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); + } else { + if (LOGGER.isWarnEnabled()) + LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + + result.getJsonString()); + } + + return result.isSucceeded(); + } + + @Override + public boolean update(PolicyRestAdapter policyData) throws IllegalStateException { + if (LOGGER.isDebugEnabled()){ + LOGGER.debug("ENTER"); + } + try { + boolean success = put(policyData); + return success; + } catch (Exception e) { + LOGGER.warn(XACMLErrorConstants.ERROR_UNKNOWN + ":" + "cannot test and update", e); + throw new IllegalStateException(e); + } + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java new file mode 100644 index 000000000..2b0c94bf3 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.elk.client; + +public class Pair { + private L left; + private R right; + public Pair(L l, R r){ + this.left = l; + this.right = r; + } + public L left(){ return left; } + public R right(){ return right; } + public void left(L l){ this.left = l; } + public void right(R r){ this.right = r; } +} \ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java new file mode 100644 index 000000000..3e065ff05 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java @@ -0,0 +1,623 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.elk.client; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.adapter.YAMLParams; + +public class PolicyElasticData { + + private String scope; + private String policyType; + private String configPolicyType; + private String configBodyData; + private String policyName; + private String policyDescription; + private String onapName; + private String configName; + private String configType; + private String jsonBody; + private Object jsonBodyData; + + private LinkedHashMap serviceTypePolicyName; + private LinkedHashMap verticaMetrics; + private LinkedHashMap description; + private LinkedHashMap attributeFields; + + //Safe Policy + private String policyScope; + private String providerComboBox; + private String riskType; + private String riskLevel; + private String guard; + private String ttlDate; + private Map matching; + + private ArrayList triggerSignatures; + private ArrayList symptomSignatures; + private String logicalConnector; + private String policyStatus; + public String gocServerScope; + private String supressionType; + + //MicroSerice + private String serviceType; + private String uuid; + private String location; + private String priority; + private String msLocation; + + //BRMS Policies + private String ruleName; + private Map brmsParamBody; + private String brmsController; + private ArrayList brmsDependency; + private LinkedHashMap ruleData; + private LinkedHashMap ruleListData; + private Map drlRuleAndUIParams; + + //ClosedLoop + private String clearTimeOut; + private String trapMaxAge; + private String verificationclearTimeOut; + public Map dynamicLayoutMap; + + //FireWall + private String fwPolicyType; + private ArrayList fwattributes; + private String parentForChild; + private String securityZone; + + //Action & Decision + private String ruleCombiningAlgId; + private Map dynamicFieldConfigAttributes; + private Map dynamicSettingsMap; + private Map dropDownMap; + private String actionPerformer; + private String actionAttribute; + private List dynamicRuleAlgorithmLabels; + private List dynamicRuleAlgorithmCombo; + private List dynamicRuleAlgorithmField1; + private List dynamicRuleAlgorithmField2; + private List dynamicVariableList; + private List dataTypeList; + private String actionAttributeValue; + private String ruleProvider; + private String actionBody; + private String actionDictHeader; + private String actionDictType; + private String actionDictUrl; + private String actionDictMethod; + private YAMLParams yamlparams; + + public PolicyElasticData(PolicyRestAdapter policyData) { + this.scope = policyData.getDomain(); + this.policyType = policyData.getPolicyType(); + this.configPolicyType = policyData.getConfigPolicyType(); + this.configBodyData = policyData.getConfigBodyData(); + this.policyName = policyData.getNewFileName(); + this.policyDescription = policyData.getPolicyDescription(); + this.onapName = policyData.getOnapName(); + this.configName = policyData.getConfigName(); + this.configType = policyData.getConfigType(); + this.jsonBody = policyData.getJsonBody(); + if(configPolicyType.startsWith("ClosedLoop")){ + this.jsonBodyData = jsonBody; + }else{ + this.jsonBodyData = policyData.getJsonBodyData(); + } + + this.serviceTypePolicyName = policyData.getServiceTypePolicyName(); + this.verticaMetrics = policyData.getVerticaMetrics(); + this.description = policyData.getDescription(); + this.attributeFields = policyData.getAttributeFields(); + + //Safe Policy + this.policyScope = policyData.getPolicyScope(); + this.providerComboBox = policyData.getProviderComboBox(); + this.riskType = policyData.getRiskType(); + this.riskLevel = policyData.getRiskLevel(); + this.guard = policyData.getGuard(); + this.ttlDate = policyData.getTtlDate(); + this.matching = policyData.getMatching(); + + this.triggerSignatures = policyData.getTriggerSignatures(); + this.symptomSignatures = policyData.getSymptomSignatures(); + this.logicalConnector = policyData.getLogicalConnector(); + this.policyStatus = policyData.getPolicyStatus(); + this.gocServerScope = policyData.getGocServerScope(); + this.supressionType = policyData.getSupressionType(); + + //MicroSerice + this.serviceType = policyData.getServiceType(); + this.uuid = policyData.getUuid(); + this.location = policyData.getLocation(); + this.priority = policyData.getPriority(); + this.msLocation = policyData.getMsLocation(); + + //BRMS Policies + this.ruleName = policyData.getRuleName(); + this.brmsParamBody = policyData.getBrmsParamBody(); + this.brmsController = policyData.getBrmsController(); + this.brmsDependency = policyData.getBrmsDependency(); + this.ruleData = policyData.getRuleData(); + this.ruleListData = policyData.getRuleListData(); + this.drlRuleAndUIParams = policyData.getDrlRuleAndUIParams(); + + //ClosedLoop + this.clearTimeOut = policyData.getClearTimeOut(); + this.trapMaxAge = policyData.getTrapMaxAge(); + this.verificationclearTimeOut = policyData.getVerificationclearTimeOut(); + this.dynamicLayoutMap = policyData.getDynamicLayoutMap(); + + //FireWall + this.fwPolicyType = policyData.getFwPolicyType(); + this.fwattributes = policyData.getFwattributes(); + this.parentForChild = policyData.getParentForChild(); + this.securityZone = policyData.getSecurityZone(); + + //Action & Decision + this.ruleCombiningAlgId = policyData.getRuleCombiningAlgId(); + this.dynamicFieldConfigAttributes = policyData.getDynamicFieldConfigAttributes(); + this.dynamicSettingsMap = policyData.getDynamicSettingsMap(); + this.dropDownMap = policyData.getDropDownMap(); + this.actionPerformer = policyData.getActionPerformer(); + this.actionAttribute = policyData.getActionAttribute(); + this.dynamicRuleAlgorithmLabels = policyData.getDynamicRuleAlgorithmLabels(); + this.dynamicRuleAlgorithmCombo = policyData.getDynamicRuleAlgorithmCombo(); + this.dynamicRuleAlgorithmField1 = policyData.getDynamicRuleAlgorithmField1(); + this.dynamicRuleAlgorithmField2 = policyData.getDynamicRuleAlgorithmField2(); + this.dynamicVariableList = policyData.getDynamicVariableList(); + this.dataTypeList = policyData.getDataTypeList(); + this.actionAttributeValue = policyData.getActionAttributeValue(); + this.ruleProvider = policyData.getRuleProvider(); + this.actionBody = policyData.getActionBody(); + this.actionDictHeader = policyData.getActionDictHeader(); + this.actionDictType = policyData.getActionDictType(); + this.actionDictUrl = policyData.getActionDictUrl(); + this.actionDictMethod = policyData.getActionDictMethod(); + this.yamlparams = policyData.getYamlparams(); + } + + public String getScope() { + return scope; + } + public void setScope(String scope) { + this.scope = scope; + } + public String getPolicyType() { + return policyType; + } + public void setPolicyType(String policyType) { + this.policyType = policyType; + } + public String getConfigPolicyType() { + return configPolicyType; + } + public void setConfigPolicyType(String configPolicyType) { + this.configPolicyType = configPolicyType; + } + public String getConfigBodyData() { + return configBodyData; + } + + public void setConfigBodyData(String configBodyData) { + this.configBodyData = configBodyData; + } + public String getPolicyName() { + return policyName; + } + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + public String getPolicyDescription() { + return policyDescription; + } + public void setPolicyDescription(String policyDescription) { + this.policyDescription = policyDescription; + } + public String getOnapName() { + return onapName; + } + public void setOnapName(String onapName) { + this.onapName = onapName; + } + public String getConfigName() { + return configName; + } + public void setConfigName(String configName) { + this.configName = configName; + } + public String getConfigType() { + return configType; + } + public void setConfigType(String configType) { + this.configType = configType; + } + public String getJsonBody() { + return jsonBody; + } + public void setJsonBody(String jsonBody) { + this.jsonBody = jsonBody; + } + public LinkedHashMap getServiceTypePolicyName() { + return serviceTypePolicyName; + } + + public void setServiceTypePolicyName(LinkedHashMap serviceTypePolicyName) { + this.serviceTypePolicyName = serviceTypePolicyName; + } + + public LinkedHashMap getVerticaMetrics() { + return verticaMetrics; + } + + public void setVerticaMetrics(LinkedHashMap verticaMetrics) { + this.verticaMetrics = verticaMetrics; + } + + public LinkedHashMap getDescription() { + return description; + } + + public void setDescription(LinkedHashMap description) { + this.description = description; + } + + public LinkedHashMap getAttributeFields() { + return attributeFields; + } + + public void setAttributeFields(LinkedHashMap attributeFields) { + this.attributeFields = attributeFields; + } + public String getPolicyScope() { + return policyScope; + } + public void setPolicyScope(String policyScope) { + this.policyScope = policyScope; + } + public String getProviderComboBox() { + return providerComboBox; + } + public void setProviderComboBox(String providerComboBox) { + this.providerComboBox = providerComboBox; + } + 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 getGuard() { + return guard; + } + public void setGuard(String guard) { + this.guard = guard; + } + public String getTtlDate() { + return ttlDate; + } + public void setTtlDate(String ttlDate) { + this.ttlDate = ttlDate; + } + public Map getMatching() { + return matching; + } + public void setMatching(Map matching) { + this.matching = matching; + } + public ArrayList getTriggerSignatures() { + return triggerSignatures; + } + public void setTriggerSignatures(ArrayList triggerSignatures) { + this.triggerSignatures = triggerSignatures; + } + public ArrayList getSymptomSignatures() { + return symptomSignatures; + } + public void setSymptomSignatures(ArrayList symptomSignatures) { + this.symptomSignatures = symptomSignatures; + } + public String getLogicalConnector() { + return logicalConnector; + } + public void setLogicalConnector(String logicalConnector) { + this.logicalConnector = logicalConnector; + } + public String getPolicyStatus() { + return policyStatus; + } + public void setPolicyStatus(String policyStatus) { + this.policyStatus = policyStatus; + } + public String getGocServerScope() { + return gocServerScope; + } + public void setGocServerScope(String gocServerScope) { + this.gocServerScope = gocServerScope; + } + public String getSupressionType() { + return supressionType; + } + public void setSupressionType(String supressionType) { + this.supressionType = supressionType; + } + public String getServiceType() { + return serviceType; + } + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + public String getLocation() { + return location; + } + public void setLocation(String location) { + this.location = location; + } + public String getPriority() { + return priority; + } + public void setPriority(String priority) { + this.priority = priority; + } + public String getMsLocation() { + return msLocation; + } + public void setMsLocation(String msLocation) { + this.msLocation = msLocation; + } + public String getRuleName() { + return ruleName; + } + public void setRuleName(String ruleName) { + this.ruleName = ruleName; + } + public Map getBrmsParamBody() { + return brmsParamBody; + } + public void setBrmsParamBody(Map brmsParamBody) { + this.brmsParamBody = brmsParamBody; + } + public String getBrmsController() { + return brmsController; + } + public void setBrmsController(String brmsController) { + this.brmsController = brmsController; + } + public ArrayList getBrmsDependency() { + return brmsDependency; + } + public void setBrmsDependency(ArrayList brmsDependency) { + this.brmsDependency = brmsDependency; + } + public LinkedHashMap getRuleData() { + return ruleData; + } + public void setRuleData(LinkedHashMap ruleData) { + this.ruleData = ruleData; + } + public LinkedHashMap getRuleListData() { + return ruleListData; + } + public void setRuleListData(LinkedHashMap ruleListData) { + this.ruleListData = ruleListData; + } + public Map getDrlRuleAndUIParams() { + return drlRuleAndUIParams; + } + public void setDrlRuleAndUIParams(Map drlRuleAndUIParams) { + this.drlRuleAndUIParams = drlRuleAndUIParams; + } + 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 Map getDynamicLayoutMap() { + return dynamicLayoutMap; + } + public void setDynamicLayoutMap(Map dynamicLayoutMap) { + this.dynamicLayoutMap = dynamicLayoutMap; + } + public String getFwPolicyType() { + return fwPolicyType; + } + public void setFwPolicyType(String fwPolicyType) { + this.fwPolicyType = fwPolicyType; + } + public ArrayList getFwattributes() { + return fwattributes; + } + public void setFwattributes(ArrayList fwattributes) { + this.fwattributes = fwattributes; + } + public String getParentForChild() { + return parentForChild; + } + public void setParentForChild(String parentForChild) { + this.parentForChild = parentForChild; + } + public String getSecurityZone() { + return securityZone; + } + public void setSecurityZone(String securityZone) { + this.securityZone = securityZone; + } + public String getRuleCombiningAlgId() { + return ruleCombiningAlgId; + } + public void setRuleCombiningAlgId(String ruleCombiningAlgId) { + this.ruleCombiningAlgId = ruleCombiningAlgId; + } + public Map getDynamicFieldConfigAttributes() { + return dynamicFieldConfigAttributes; + } + public void setDynamicFieldConfigAttributes(Map dynamicFieldConfigAttributes) { + this.dynamicFieldConfigAttributes = dynamicFieldConfigAttributes; + } + public Map getDynamicSettingsMap() { + return dynamicSettingsMap; + } + public void setDynamicSettingsMap(Map dynamicSettingsMap) { + this.dynamicSettingsMap = dynamicSettingsMap; + } + public Map getDropDownMap() { + return dropDownMap; + } + public void setDropDownMap(Map dropDownMap) { + this.dropDownMap = dropDownMap; + } + public String getActionPerformer() { + return actionPerformer; + } + public void setActionPerformer(String actionPerformer) { + this.actionPerformer = actionPerformer; + } + public String getActionAttribute() { + return actionAttribute; + } + public void setActionAttribute(String actionAttribute) { + this.actionAttribute = actionAttribute; + } + public List getDynamicRuleAlgorithmLabels() { + return dynamicRuleAlgorithmLabels; + } + public void setDynamicRuleAlgorithmLabels(List dynamicRuleAlgorithmLabels) { + this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; + } + public List getDynamicRuleAlgorithmCombo() { + return dynamicRuleAlgorithmCombo; + } + public void setDynamicRuleAlgorithmCombo(List dynamicRuleAlgorithmCombo) { + this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; + } + public List getDynamicRuleAlgorithmField1() { + return dynamicRuleAlgorithmField1; + } + public void setDynamicRuleAlgorithmField1(List dynamicRuleAlgorithmField1) { + this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; + } + public List getDynamicRuleAlgorithmField2() { + return dynamicRuleAlgorithmField2; + } + public void setDynamicRuleAlgorithmField2(List dynamicRuleAlgorithmField2) { + this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; + } + public List getDynamicVariableList() { + return dynamicVariableList; + } + public void setDynamicVariableList(List dynamicVariableList) { + this.dynamicVariableList = dynamicVariableList; + } + public List getDataTypeList() { + return dataTypeList; + } + public void setDataTypeList(List dataTypeList) { + this.dataTypeList = dataTypeList; + } + public String getActionAttributeValue() { + return actionAttributeValue; + } + public void setActionAttributeValue(String actionAttributeValue) { + this.actionAttributeValue = actionAttributeValue; + } + public String getRuleProvider() { + return ruleProvider; + } + public void setRuleProvider(String ruleProvider) { + this.ruleProvider = ruleProvider; + } + public String getActionBody() { + return actionBody; + } + public void setActionBody(String actionBody) { + this.actionBody = actionBody; + } + public String getActionDictHeader() { + return actionDictHeader; + } + public void setActionDictHeader(String actionDictHeader) { + this.actionDictHeader = actionDictHeader; + } + public String getActionDictType() { + return actionDictType; + } + public void setActionDictType(String actionDictType) { + this.actionDictType = actionDictType; + } + public String getActionDictUrl() { + return actionDictUrl; + } + public void setActionDictUrl(String actionDictUrl) { + this.actionDictUrl = actionDictUrl; + } + public String getActionDictMethod() { + return actionDictMethod; + } + public void setActionDictMethod(String actionDictMethod) { + this.actionDictMethod = actionDictMethod; + } + public YAMLParams getYamlparams() { + return yamlparams; + } + + public void setYamlparams(YAMLParams yamlparams) { + this.yamlparams = yamlparams; + } + + public Object getJsonBodyData() { + return jsonBodyData; + } + + public void setJsonBodyData(Object jsonBodyData) { + this.jsonBodyData = jsonBodyData; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java new file mode 100644 index 000000000..2f4dc59cf --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java @@ -0,0 +1,563 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.elk.client; + + +import java.io.PrintWriter; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +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.pap.xacml.rest.elk.client.ElkConnector.PolicyIndexType; +import org.onap.policy.pap.xacml.rest.util.JsonMessage; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.ActionPolicyDict; +import org.onap.policy.rest.jpa.Attribute; +import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.ClosedLoopD2Services; +import org.onap.policy.rest.jpa.ClosedLoopSite; +import org.onap.policy.rest.jpa.DCAEuuid; +import org.onap.policy.rest.jpa.DecisionSettings; +import org.onap.policy.rest.jpa.DescriptiveScope; +import org.onap.policy.rest.jpa.OnapName; +import org.onap.policy.rest.jpa.GroupPolicyScopeList; +import org.onap.policy.rest.jpa.MicroServiceLocation; +import org.onap.policy.rest.jpa.MicroServiceModels; +import org.onap.policy.rest.jpa.PEPOptions; +import org.onap.policy.rest.jpa.RiskType; +import org.onap.policy.rest.jpa.SafePolicyWarning; +import org.onap.policy.rest.jpa.TermList; +import org.onap.policy.rest.jpa.VNFType; +import org.onap.policy.rest.jpa.VSCLAction; +import org.onap.policy.rest.jpa.VarbindDictionary; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.beans.factory.annotation.Autowired; +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 com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.JsonArray; + +import io.searchbox.client.JestResult; + +@Controller +@RequestMapping({"/"}) +public class PolicyElasticSearchController{ + + private static final Logger LOGGER = FlexLogger.getLogger(PolicyElasticSearchController.class); + + enum Mode{ + attribute, onapName, actionPolicy, brmsParam, pepOptions, + clSite, clService, clVarbind, clVnf, clVSCL, decision, + fwTerm, msDCAEUUID, msConfigName, msLocation, msModels, + psGroupPolicy, safeRisk, safePolicyWarning + } + + public static final HashMap name2jsonPath = new HashMap() { + private static final long serialVersionUID = 1L; + }; + + public static CommonClassDao commonClassDao; + + @Autowired + public PolicyElasticSearchController(CommonClassDao commonClassDao) { + PolicyElasticSearchController.commonClassDao = commonClassDao; + } + + public PolicyElasticSearchController() {} + + public static void TurnOffCertsCheck() { + // Create a trust manager that does not validate certificate chains + TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + public void checkClientTrusted(X509Certificate[] certs, + String authType) { + } + public void checkServerTrusted(X509Certificate[] certs, + String authType) { + } + } }; + + // Install all-trusting trust manager + SSLContext ctx; + try { + ctx = SSLContext.getInstance("SSL"); + ctx.init(null, trustAllCerts, new java.security.SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(ctx + .getSocketFactory()); + } catch (NoSuchAlgorithmException | KeyManagementException e) { + LOGGER.error("SSL Security Error: " + e); + } + + // Create all-trusting host name verifier + HostnameVerifier allHostsValid = new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + + // Install the all-trusting host verifier + HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); + } + + + + + public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException { + if (type == null || type.isEmpty()){ + return PolicyIndexType.all; + } + return PolicyIndexType.valueOf(type); + } + + public boolean updateElk(PolicyRestAdapter policyData) { + boolean success = true; + try { + success = ElkConnector.singleton.update(policyData); + if (!success) { + if (LOGGER.isWarnEnabled()) { + LOGGER.warn("FAILURE to create ELK record created for " + policyData.getNewFileName()); + } + } else { + if (LOGGER.isInfoEnabled()) { + LOGGER.warn("SUCCESS creating ELK record created for " + policyData.getNewFileName()); + } + } + } catch (Exception e) { + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e); + success = false; + } + return success; + } + + public boolean deleteElk(PolicyRestAdapter policyData) { + boolean success = true; + try { + success = ElkConnector.singleton.delete(policyData); + if (!success) { + if (LOGGER.isWarnEnabled()) { + LOGGER.warn("FAILURE to delete ELK record created for " + policyData.getNewFileName()); + } + } else { + if (LOGGER.isInfoEnabled()) { + LOGGER.warn("SUCCESS deleting ELK record created for " + policyData.getNewFileName()); + } + } + } catch (Exception e) { + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": " + e.getMessage(), e); + success = false; + } + return success; + } + + + @RequestMapping(value="/searchPolicy", method= RequestMethod.POST) + public void searchPolicy(HttpServletRequest request, HttpServletResponse response) { + try{ + boolean result = false; + boolean policyResult = false; + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + PolicyRestAdapter policyData = new PolicyRestAdapter(); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + Map searchKeyValue = new HashMap<>(); + List policyList = new ArrayList<>(); + if(request.getParameter("policyName") != null){ + String policyName = request.getParameter("policyName"); + policyData.setNewFileName(policyName); + if("delete".equalsIgnoreCase(request.getParameter("action"))){ + result = controller.deleteElk(policyData); + }else{ + result = controller.updateElk(policyData); + } + } + if("search".equalsIgnoreCase(request.getParameter("action"))){ + try { + JsonNode root = mapper.readTree(request.getReader()); + SearchData searchData = (SearchData)mapper.readValue(root.get("searchdata").toString(), SearchData.class); + + String policyType = searchData.getPolicyType(); + + String searchText = searchData.getQuery(); + String descriptivevalue = searchData.getDescriptiveScope(); + if(descriptivevalue != null){ + DescriptiveScope dsSearch = (DescriptiveScope) commonClassDao.getEntityItem(DescriptiveScope.class, "descriptiveScopeName", descriptivevalue); + if(dsSearch != null){ + String[] descriptiveList = dsSearch.getSearch().split("AND"); + for(String keyValue : descriptiveList){ + String[] entry = keyValue.split(":"); + if(searchData.getPolicyType() != null && "closedLoop".equals(searchData.getPolicyType())){ + searchKeyValue.put("jsonBodyData", "*" +entry[1] +"*"); + }else{ + searchKeyValue.put(entry[0], entry[1]); + } + } + } + } + + if(searchData.getClosedLooppolicyType() != null){ + String closedLoopType; + if("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())){ + closedLoopType = "ClosedLoop_Fault"; + }else{ + closedLoopType = "ClosedLoop_PM"; + } + searchKeyValue.put("configPolicyType", closedLoopType); + } + if(searchData.getOnapName() != null){ + searchKeyValue.put("onapName", searchData.getOnapName()); + } + if(searchData.getD2Service() != null){ + String d2Service = searchData.getD2Service().trim(); + if(d2Service.equalsIgnoreCase("Hosted Voice (Trinity)")){ + d2Service = "trinity"; + }else if(d2Service.equalsIgnoreCase("vUSP")){ + d2Service = "vUSP"; + }else if(d2Service.equalsIgnoreCase("MCR")){ + d2Service = "mcr"; + }else if(d2Service.equalsIgnoreCase("Gamma")){ + d2Service = "gamma"; + }else if(d2Service.equalsIgnoreCase("vDNS")){ + d2Service = "vDNS"; + } + searchKeyValue.put("jsonBodyData."+d2Service+"", "true"); + } + if(searchData.getVnfType() != null){ + searchKeyValue.put("jsonBodyData", "*" +searchData.getVnfType() +"*"); + } + if(searchData.getPolicyStatus() != null){ + searchKeyValue.put("jsonBodyData", "*" +searchData.getPolicyStatus()+"*"); + } + if(searchData.getVproAction() != null){ + searchKeyValue.put("jsonBodyData", "*" +searchData.getVproAction()+"*"); + } + if(searchData.getServiceType() != null){ + searchKeyValue.put("serviceType", searchData.getServiceType()); + } + if(searchData.getBindTextSearch() != null){ + searchKeyValue.put(searchData.getBindTextSearch(), searchText); + searchText = null; + } + PolicyIndexType type = null; + if(policyType != null){ + if(policyType.equalsIgnoreCase("action")){ + type = ElkConnector.PolicyIndexType.action; + }else if(policyType.equalsIgnoreCase("decision")){ + type = ElkConnector.PolicyIndexType.decision; + }else if(policyType.equalsIgnoreCase("config")){ + type = ElkConnector.PolicyIndexType.config; + }else { + type = ElkConnector.PolicyIndexType.closedloop; + } + }else{ + type = ElkConnector.PolicyIndexType.all; + } + JestResult policyResultList = controller.search(type, searchText, searchKeyValue); + if(policyResultList.isSucceeded()){ + result = true; + policyResult = true; + JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); + for(int i =0; i < resultObject.size(); i++){ + String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString(); + policyList.add(policyName); + } + }else{ + LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs"); + } + }catch(Exception e){ + LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server" + e); + } + } + String message=""; + if(result){ + message = "Elastic Server Transaction is success"; + }else{ + message = "Elastic Server Transaction is failed, please check the logs"; + } + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(message)); + JSONObject j = new JSONObject(msg); + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("success", "success"); + if(policyResult){ + JSONObject k = new JSONObject("{policyresult: " + policyList + "}"); + response.getWriter().write(k.toString()); + }else{ + response.getWriter().write(j.toString()); + } + }catch(Exception e){ + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "Exception Occured While Performing Elastic Transaction"); + LOGGER.error("Exception Occured While Performing Elastic Transaction"+e.getMessage()); + } + } + + @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try{ + PolicyIndexType config = PolicyIndexType.config; + PolicyIndexType closedloop = PolicyIndexType.closedloop; + PolicyIndexType action = PolicyIndexType.action; + PolicyIndexType decision = PolicyIndexType.decision; + PolicyIndexType all = PolicyIndexType.all; + + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + String dictionaryType = root.get("type").textValue(); + Mode mode = Mode.valueOf(dictionaryType); + String value; + List policyList = new ArrayList<>(); + switch (mode){ + case attribute : + Attribute attributedata = (Attribute)mapper.readValue(root.get("data").toString(), Attribute.class); + value = attributedata.getXacmlId(); + policyList = searchElkDatabase(all, "pholder",value); + break; + case onapName : + OnapName onapName = (OnapName)mapper.readValue(root.get("data").toString(), OnapName.class); + value = onapName.getOnapName(); + policyList = searchElkDatabase(all, "onapName",value); + break; + case actionPolicy : + ActionPolicyDict actionPolicyDict = (ActionPolicyDict)mapper.readValue(root.get("data").toString(), ActionPolicyDict.class); + value = actionPolicyDict.getAttributeName(); + policyList = searchElkDatabase(action, "actionAttributeValue",value); + break; + case brmsParam : + BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate)mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class); + value = bRMSParamTemplate.getRuleName(); + policyList = searchElkDatabase(config, "ruleName",value); + break; + case pepOptions : + PEPOptions pEPOptions = (PEPOptions)mapper.readValue(root.get("data").toString(), PEPOptions.class); + value = pEPOptions.getPepName(); + policyList = searchElkDatabase(closedloop,"jsonBodyData.pepName",value); + break; + case clSite : + ClosedLoopSite closedLoopSite = (ClosedLoopSite)mapper.readValue(root.get("data").toString(), ClosedLoopSite.class); + value = closedLoopSite.getSiteName(); + policyList = searchElkDatabase(closedloop,"siteNames",value); + break; + case clService : + ClosedLoopD2Services closedLoopD2Services = (ClosedLoopD2Services)mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class); + value = closedLoopD2Services.getServiceName(); + policyList = searchElkDatabase(closedloop, "pholder",value); + break; + case clVarbind : + VarbindDictionary varbindDictionary = (VarbindDictionary)mapper.readValue(root.get("data").toString(), VarbindDictionary.class); + value = varbindDictionary.getVarbindName(); + policyList = searchElkDatabase(closedloop, "jsonBodyData.triggerSignaturesUsedForUI.signatures",value); + break; + case clVnf : + VNFType vNFType = (VNFType)mapper.readValue(root.get("data").toString(), VNFType.class); + value = vNFType.getVnftype(); + policyList = searchElkDatabase(closedloop, "jsonBodyData.vnfType",value); + break; + case clVSCL : + VSCLAction vsclAction = (VSCLAction)mapper.readValue(root.get("data").toString(), VSCLAction.class); + value = vsclAction.getVsclaction(); + policyList = searchElkDatabase(closedloop, "jsonBodyData.actions",value); + break; + case decision : + DecisionSettings decisionSettings = (DecisionSettings)mapper.readValue(root.get("data").toString(), DecisionSettings.class); + value = decisionSettings.getXacmlId(); + policyList = searchElkDatabase(decision,"pholder",value); + break; + case fwTerm : + TermList term = (TermList)mapper.readValue(root.get("data").toString(), TermList.class); + value = term.getTermName(); + policyList = searchElkDatabase(config, "pholder",value); + break; + case msDCAEUUID : + DCAEuuid dcaeUUID = (DCAEuuid)mapper.readValue(root.get("data").toString(), DCAEuuid.class); + value = dcaeUUID.getName(); + policyList = searchElkDatabase(config, "uuid",value); + break; + case msLocation : + MicroServiceLocation mslocation = (MicroServiceLocation)mapper.readValue(root.get("data").toString(), MicroServiceLocation.class); + value = mslocation.getName(); + policyList = searchElkDatabase(config, "location",value); + break; + case msModels : + MicroServiceModels msModels = (MicroServiceModels)mapper.readValue(root.get("data").toString(), MicroServiceModels.class); + value = msModels.getModelName(); + policyList = searchElkDatabase(config, "serviceType",value); + break; + case psGroupPolicy : + GroupPolicyScopeList groupPoilicy = (GroupPolicyScopeList)mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class); + value = groupPoilicy.getGroupName(); + policyList = searchElkDatabase(config, "pholder",value); + break; + case safeRisk : + RiskType riskType= (RiskType)mapper.readValue(root.get("data").toString(), RiskType.class); + value = riskType.getRiskName(); + policyList = searchElkDatabase(config, "riskType",value); + break; + case safePolicyWarning : + SafePolicyWarning safePolicy = (SafePolicyWarning)mapper.readValue(root.get("data").toString(), SafePolicyWarning.class); + value = safePolicy.getName(); + policyList = searchElkDatabase(config, "pholder",value); + break; + default: + } + + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("success", "success"); + JSONObject k = new JSONObject("{policyresult: " + policyList + "}"); + response.getWriter().write(k.toString()); + }catch(Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + //Search the Elk database + public List searchElkDatabase(PolicyIndexType type, String key, String value){ + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + Map searchKeyValue = new HashMap<>(); + if(!"pholder".equals(key)){ + searchKeyValue.put(key, value); + } + + List policyList = new ArrayList<>(); + JestResult policyResultList = controller.search(type, value, searchKeyValue); + if(policyResultList.isSucceeded()){ + JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); + for(int i =0; i < resultObject.size(); i++){ + String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString(); + policyList.add(policyName); + } + }else{ + LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs"); + } + return policyList; + } + + public JestResult search(PolicyIndexType type, String text, Map searchKeyValue) { + return ElkConnector.singleton.search(type, text, searchKeyValue); + } + +} + +class SearchData{ + private String query; + private String policyType; + private String descriptiveScope; + private String closedLooppolicyType; + private String onapName; + private String d2Service; + private String vnfType; + private String policyStatus; + private String vproAction; + private String serviceType; + private String bindTextSearch; + public String getQuery() { + return query; + } + public void setQuery(String query) { + this.query = query; + } + public String getPolicyType() { + return policyType; + } + public void setPolicyType(String policyType) { + this.policyType = policyType; + } + public String getDescriptiveScope() { + return descriptiveScope; + } + public void setDescriptiveScope(String descriptiveScope) { + this.descriptiveScope = descriptiveScope; + } + public String getClosedLooppolicyType() { + return closedLooppolicyType; + } + public void setClosedLooppolicyType(String closedLooppolicyType) { + this.closedLooppolicyType = closedLooppolicyType; + } + public String getOnapName() { + return onapName; + } + public void setOnapName(String onapName) { + this.onapName = onapName; + } + public String getD2Service() { + return d2Service; + } + public void setD2Service(String d2Service) { + this.d2Service = d2Service; + } + public String getVnfType() { + return vnfType; + } + public void setVnfType(String vnfType) { + this.vnfType = vnfType; + } + public String getPolicyStatus() { + return policyStatus; + } + public void setPolicyStatus(String policyStatus) { + this.policyStatus = policyStatus; + } + public String getVproAction() { + return vproAction; + } + public void setVproAction(String vproAction) { + this.vproAction = vproAction; + } + public String getServiceType() { + return serviceType; + } + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + public String getBindTextSearch() { + return bindTextSearch; + } + public void setBindTextSearch(String bindTextSearch) { + this.bindTextSearch = bindTextSearch; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java new file mode 100644 index 000000000..58c89f781 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.elk.client; + +public class PolicyLocator { + public final String policyType; + public final String policyName; + public final String owner; + public final String scope; + public final String policyId; + public final String version; + + public PolicyLocator(String policyType, String policyName, + String owner, String scope, String policyId, + String version) { + this.policyType = policyType; + this.policyName= policyName; + this.owner = owner; + this.scope = scope; + this.policyId = policyId; + this.version = version; + } + + public String toString() { + return "[" + + this.owner + "|" + + this.scope + "|" + + this.policyType + "|" + + this.policyName + "|" + + this.policyId + "|" + + "v" + this.version + "|" + "]"; + + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java new file mode 100644 index 000000000..36d7c29ef --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.handler; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.policy.common.logging.ONAPLoggingContext; +import org.onap.policy.pap.xacml.rest.service.ImportService; +import org.onap.policy.pap.xacml.rest.service.MetricService; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; + +public class APIRequestHandler { + + private OnapPDPGroup newGroup; + + public void doGet(HttpServletRequest request, HttpServletResponse response, String apiflag) throws IOException{ + // Request from the API to get Dictionary Items + if ("api".equalsIgnoreCase(apiflag)) { + DictionaryHandler dictionaryHandler = DictionaryHandler.getInstance(); + dictionaryHandler.doDictionaryAPIGet(request, response); + return; + } + // Request from the API to get the ActiveVersion from the PolicyVersion table + if ("version".equalsIgnoreCase(apiflag)){ + PushPolicyHandler pushHandler = new PushPolicyHandler(); + pushHandler.getActiveVersion(request, response); + return; + } + // Request from the API to get the URI from the gitpath + if ("uri".equalsIgnoreCase(apiflag)){ + PushPolicyHandler pushHandler = new PushPolicyHandler(); + pushHandler.getSelectedURI(request, response); + return; + } + if ("getMetrics".equalsIgnoreCase(apiflag)){ + MetricService.doGetPolicyMetrics(request, response); + return; + } + } + + public void doPut(HttpServletRequest request, HttpServletResponse response, String service) throws IOException { + if ("MICROSERVICE".equalsIgnoreCase(service) || "BRMSPARAM".equalsIgnoreCase(service)){ + ImportService importService = new ImportService(); + importService.doImportMicroServicePut(request, response); + return; + } + if ("dictionaryItem".equalsIgnoreCase(service)) { + DictionaryHandler dictionaryHandler = DictionaryHandler.getInstance(); + dictionaryHandler.doDictionaryAPIPut(request, response); + return; + } else { + SavePolicyHandler savePolicy = SavePolicyHandler.getInstance(); + savePolicy.doPolicyAPIPut(request, response); + } + } + + public void doDelete(HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext, String apiflag) throws Exception { + DeleteHandler deleteHandler = DeleteHandler.getInstance(); + if ("deletePapApi".equalsIgnoreCase(apiflag)) { + deleteHandler.doAPIDeleteFromPAP(request, response, loggingContext); + return; + } else if ("deletePdpApi".equalsIgnoreCase(apiflag)) { + deleteHandler.doAPIDeleteFromPDP(request, response, loggingContext); + setNewGroup(deleteHandler.getDeletedGroup()); + return; + } + } + + private void setNewGroup(OnapPDPGroup newGroup) { + this.newGroup = newGroup; + } + + public OnapPDPGroup getNewGroup() { + return newGroup; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java new file mode 100644 index 000000000..17fd2c12b --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java @@ -0,0 +1,477 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.handler; + +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.Query; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.policy.common.logging.ONAPLoggingContext; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; +import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController; +import org.onap.policy.pap.xacml.rest.model.RemoveGroupPolicy; +import org.onap.policy.pap.xacml.rest.util.JPAUtils; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.jpa.PolicyVersion; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; +import org.onap.policy.xacml.std.pap.StdPDPGroup; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.util.XACMLProperties; + +public class DeleteHandler { + + private OnapPDPGroup newgroup; + + private static String papDbDriver = null; + private static String papDbUrl = null; + private static String papDbUser = null; + private static String papDbPassword = null; + + public void doAPIDeleteFromPAP(HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext) throws Exception { + // get the request content into a String + String json = null; + java.util.Scanner scanner = new java.util.Scanner(request.getInputStream()); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + PolicyLogger.info("JSON request from API: " + json); + // convert Object sent as JSON into local object + StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class); + String policyName = policy.getPolicyName(); + Boolean policyVersionDeleted = false; + String removeXMLExtension; + int currentVersion; + String removeVersionExtension; + String splitPolicyName = null; + String[] split = null; + String status = "error"; + PolicyEntity policyEntity = null; + JPAUtils jpaUtils = null; + + papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER); + papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); + papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER); + papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD); + Connection con = null; + + try { + jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf()); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " Could not create JPAUtils instance on the PAP"); + response.addHeader("error", "jpautils"); + response.addHeader("operation", "delete"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } + if (jpaUtils.dbLockdownIgnoreErrors()) { + PolicyLogger.warn("Policies are locked down"); + response.addHeader("operation", "delete"); + response.addHeader("lockdown", "true"); + response.setStatus(HttpServletResponse.SC_ACCEPTED); + return; + } + EntityManager em = (EntityManager) XACMLPapServlet.getEmf().createEntityManager(); + Query policyEntityQuery = null; + try{ + if(policyName.endsWith(".xml")){ + removeXMLExtension = policyName.replace(".xml", ""); + currentVersion = Integer.parseInt(removeXMLExtension.substring(removeXMLExtension.lastIndexOf(".")+1)); + removeVersionExtension = removeXMLExtension.substring(0, removeXMLExtension.lastIndexOf(".")); + boolean queryCheck = true; + if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){ + if(policyName.contains("Config_")){ + splitPolicyName = removeVersionExtension.replace(".Config_", ":Config_"); + }else if(policyName.contains("Action_")){ + splitPolicyName = removeVersionExtension.replace(".Action_", ":Action_"); + }else if(policyName.contains("Decision_")){ + splitPolicyName = removeVersionExtension.replace(".Decision_", ":Decision_"); + } + if(splitPolicyName != null){ + split = splitPolicyName.split(":"); + }else{ + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy. Please, provide the valid policyname."); + response.addHeader("error", "unknown"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + return; + } + policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName LIKE :pName and p.scope=:pScope"); + }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")) { + if(policyName.contains("Config_")){ + splitPolicyName = policyName.replace(".Config_", ":Config_"); + }else if(policyName.contains("Action_")){ + splitPolicyName = policyName.replace(".Action_", ":Action_"); + }else if(policyName.contains("Decision_")){ + splitPolicyName = policyName.replace(".Decision_", ":Decision_"); + } + split = splitPolicyName.split(":"); + queryCheck = false; + policyEntityQuery = em.createQuery("SELECT p FROM PolicyEntity p WHERE p.policyName=:pName and p.scope=:pScope"); + } + + if(queryCheck){ + policyEntityQuery.setParameter("pName", "%"+split[1]+"%"); + }else{ + policyEntityQuery.setParameter("pName", split[1]); + } + + policyEntityQuery.setParameter("pScope", split[0]); + List peResult = policyEntityQuery.getResultList(); + if(!peResult.isEmpty()){ + Query getPolicyVersion = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname"); + getPolicyVersion.setParameter("pname", removeVersionExtension.replace(".", File.separator)); + List pvResult = getPolicyVersion.getResultList(); + PolicyVersion pVersion = (PolicyVersion) pvResult.get(0); + int newVersion = 0; + em.getTransaction().begin(); + Class.forName(papDbDriver); + con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword); + + if(policy.getDeleteCondition().equalsIgnoreCase("All Versions")){ + boolean groupCheck = checkPolicyGroupEntity(em, con, peResult); + if(!groupCheck){ + for(Object peData : peResult){ + policyEntity = (PolicyEntity) peData; + status = deletePolicyEntityData(em, policyEntity); + } + }else{ + status = "PolicyInPDP"; + } + if(status.equals("error")){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database."); + response.addHeader("error", "unknown"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + return; + }else if(status.equals("PolicyInPDP")){ + PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups."); + response.addHeader("error", "PolicyInPDP"); + response.setStatus(HttpServletResponse.SC_CONFLICT); + return; + }else{ + try{ + policyVersionDeleted = true; + em.remove(pVersion); + }catch(Exception e){ + policyVersionDeleted = false; + } + } + }else if(policy.getDeleteCondition().equalsIgnoreCase("Current Version")){ + boolean groupCheck = checkPolicyGroupEntity(em, con, peResult); + if(!groupCheck){ + policyEntity = (PolicyEntity) peResult.get(0); + status = deletePolicyEntityData(em, policyEntity); + }else{ + status = "PolicyInPDP"; + } + + if(status.equals("error")){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Exception Occured while deleting the Entity from Database."); + response.addHeader("error", "unknown"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + return; + }else if(status.equals("PolicyInPDP")){ + PolicyLogger.error(MessageCodes.GENERAL_WARNING + "Policy can't be deleted, it is active in PDP Groups."); + response.addHeader("error", "unknown"); + response.setStatus(HttpServletResponse.SC_CONFLICT); + return; + }else{ + if(currentVersion > 1){ + if(!peResult.isEmpty()){ + for(Object object : peResult){ + policyEntity = (PolicyEntity) object; + String policyEntityName = policyEntity.getPolicyName().replace(".xml", ""); + int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1)); + if(policyEntityVersion > newVersion){ + newVersion = policyEntityVersion-1; + } + } + } + pVersion.setActiveVersion(newVersion); + pVersion.setHigherVersion(newVersion); + try{ + policyVersionDeleted = true; + em.persist(pVersion); + }catch(Exception e){ + policyVersionDeleted = false; + } + }else{ + try{ + policyVersionDeleted = true; + em.remove(pVersion); + }catch(Exception e){ + policyVersionDeleted = false; + } + } + } + } + }else{ + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."); + response.addHeader("error", "unknown"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + return; + } + } + em.getTransaction().commit(); + }catch(Exception e){ + em.getTransaction().rollback(); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR"); + response.addHeader("error", "deleteDB"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + } finally { + em.close(); + if(con != null){ + con.close(); + } + } + + if (policyVersionDeleted) { + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "delete"); + return; + } else { + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."); + response.addHeader("error", "unknown"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + return; + } + } + + public String deletePolicyEntityData(EntityManager em, PolicyEntity policyEntity) throws SQLException{ + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + PolicyRestAdapter policyData = new PolicyRestAdapter(); + String policyName = policyEntity.getPolicyName(); + try{ + if(policyName.contains("Config_")){ + em.remove(policyEntity.getConfigurationData()); + }else if(policyName.contains("Action_")){ + em.remove(policyEntity.getActionBodyEntity()); + } + String searchPolicyName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); + policyData.setNewFileName(searchPolicyName); + controller.deleteElk(policyData); + em.remove(policyEntity); + }catch(Exception e){ + return "error"; + } + return "success"; + } + + public boolean checkPolicyGroupEntity(EntityManager em, Connection con, List peResult) throws SQLException{ + for(Object peData : peResult){ + PolicyEntity policyEntity = (PolicyEntity) peData; + Statement st = null; + ResultSet rs = null; + try{ + st = con.createStatement(); + rs = st.executeQuery("Select * from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"); + boolean gEntityList = rs.next(); + rs.close(); + if(gEntityList){ + return true; + } + }finally{ + if(st != null){ + st.close(); + } + } + } + return false; + } + + public void doAPIDeleteFromPDP(HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext) throws IOException { + String policyName = request.getParameter("policyName"); + String groupId = request.getParameter("groupId"); + String responseString = null; + // for PUT operations the group may or may not need to exist before the operation can be done + OnapPDPGroup group = null; + try { + group = XACMLPapServlet.getPAPEngine().getGroup(groupId); + } catch (PAPException e) { + PolicyLogger.error("Exception occured While PUT operation is performing for PDP Group"+e); + } + if (group == null) { + String message = "Unknown groupId '" + groupId + "'"; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.addHeader("error", "UnknownGroup"); + response.sendError(HttpServletResponse.SC_NOT_FOUND, message); + return; + } else { + loggingContext.setServiceName("API:PAP.deletPolicyFromPDPGroup"); + if (policyName.contains("xml")) { + PolicyLogger.debug("The full file name including the extension was provided for policyName.. continue."); + } else { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... " + + "policyName must be the full name of the file to be deleted including version and extension"; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Invalid policyName... " + + "policyName must be the full name of the file to be deleted including version and extension"); + response.addHeader("error", message); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; + } + RemoveGroupPolicy removePolicy = new RemoveGroupPolicy((StdPDPGroup) group); + PDPPolicy policy = group.getPolicy(policyName); + if (policy != null) { + + if ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param"))) { + if (preSafetyCheck(policy)) { + PolicyLogger.debug("Precheck Successful."); + } + } + + removePolicy.prepareToRemove(policy); + OnapPDPGroup updatedGroup = removePolicy.getUpdatedObject(); + responseString = deletePolicyFromPDPGroup(updatedGroup, loggingContext); + } else { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP."; + PolicyLogger.error(message); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Policy does not exist on the PDP."); + response.addHeader("error", message); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + return; + } + } + if (responseString.equals("success")) { + PolicyLogger.info("Policy successfully deleted!"); + PolicyLogger.audit("Policy successfully deleted!"); + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "delete"); + return; + } else if (responseString.equals("No Group")) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Group update had bad input."; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input."); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader("error", "groupUpdate"); + response.addHeader("message", message); + return; + } else if (responseString.equals("DB Error")) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " Error while updating group in the database"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader("error", "deleteDB"); + return; + } else { + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN + " Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."); + response.addHeader("error", "unknown"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR ); + return; + } + } + + private String deletePolicyFromPDPGroup (OnapPDPGroup group, ONAPLoggingContext loggingContext){ + PolicyDBDaoTransaction acPutTransaction = XACMLPapServlet.getDbDaoTransaction(); + String response = null; + loggingContext.setServiceName("API:PAP.DeleteHandler"); + OnapPDPGroup existingGroup = null; + try { + existingGroup = XACMLPapServlet.getPAPEngine().getGroup(group.getId()); + } catch (PAPException e1) { + PolicyLogger.error("Exception occured While Deleting Policy From PDP Group"+e1); + } + if (group == null || ! (group instanceof StdPDPGroup) || existingGroup == null || ! (group.getId().equals(existingGroup.getId()))) { + String existingID = null; + if(existingGroup != null){ + existingID = existingGroup.getId(); + } + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Group update had bad input. id=" + existingID + " objectFromJSON="+group); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response = "No Group"; + return response; + } + // The Path on the PAP side is not carried on the RESTful interface with the AC + // (because it is local to the PAP) + // so we need to fill that in before submitting the group for update + ((StdPDPGroup)group).setDirectory(((StdPDPGroup)existingGroup).getDirectory()); + try{ + acPutTransaction.updateGroup(group, "XACMLPapServlet.doAPIDelete"); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " Error while updating group in the database: " + +"group="+existingGroup.getId()); + response = "DB Error"; + return response; + } + try { + XACMLPapServlet.getPAPEngine().updateGroup(group); + } catch (PAPException e) { + PolicyLogger.error("Exception occured While Updating PDP Groups"+e); + response = "error in updateGroup method"; + } + PolicyLogger.debug("Group '" + group.getId() + "' updated"); + acPutTransaction.commitTransaction(); + // Group changed, which might include changing the policies + try { + newgroup = existingGroup; + } catch (Exception e) { + PolicyLogger.error("Exception occured in Group Change Method"+e); + response = "error in groupChanged method"; + } + if (response==null){ + response = "success"; + PolicyLogger.audit("Policy successfully deleted!"); + PolicyLogger.audit("Transaction Ended Successfully"); + } + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended"); + return response; + } + + public OnapPDPGroup getDeletedGroup(){ + return newgroup; + } + + public boolean preSafetyCheck(PDPPolicy policy) { + return true; + } + + public static DeleteHandler getInstance() { + try { + Class deleteHandler = Class.forName(XACMLProperties.getProperty("deletePolicy.impl.className", DeleteHandler.class.getName())); + DeleteHandler instance = (DeleteHandler) deleteHandler.newInstance(); + return instance; + } catch (Exception e) { + PolicyLogger.error(e.getMessage()); + } + return null; + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java new file mode 100644 index 000000000..4fe126fd9 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.handler; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.policy.common.logging.eelf.PolicyLogger; + +import com.att.research.xacml.util.XACMLProperties; + +public interface DictionaryHandler { + String DICTIONARY_DEFAULT_CLASS = DictionaryHandlerImpl.class.getName(); + + /* + * Get Instance + */ + public static DictionaryHandler getInstance(){ + try { + Class dictionaryHandler = Class.forName(XACMLProperties.getProperty("dictionary.impl.className", DICTIONARY_DEFAULT_CLASS)); + DictionaryHandler instance = (DictionaryHandler) dictionaryHandler.newInstance(); + return instance; + } catch (Exception e) { + PolicyLogger.error(e.getMessage()); + } + return null; + } + + /* + * Get Equivalent for Dictionary Services. + */ + public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response); + /* + * Put Equivalent for Dictionary Services. + */ + public void doDictionaryAPIPut(HttpServletRequest request, HttpServletResponse response); + + /** + * Can be used to extend the services. + * + * getflag=true indicates Get Request. + * getflag=false indicates Put Request. + * @return + */ + public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag); +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java new file mode 100644 index 000000000..e0304d079 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java @@ -0,0 +1,323 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.handler; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.pap.xacml.rest.service.DictionaryService; +import org.onap.policy.xacml.api.XACMLErrorConstants; + +public class DictionaryHandlerImpl implements DictionaryHandler{ + /* + * Get Equivalent for Dictionary Services. + */ + public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response) { + String dictionaryType = request.getParameter("dictionaryType"); + try { + DictionaryService dictionary = new DictionaryService(); + switch (dictionaryType) { + case "OnapName": + dictionary.getOnapDictionary(request, response); + break; + case "Attribute": + dictionary.getAttributeDictionary(request, response); + break; + case "Action": + dictionary.getActionPolicyDictionary(request, response); + break; + case "BRMSParamTemplate": + dictionary.getBRMSParamDictionary(request, response); + break; + case "VSCLAction": + dictionary.getVSCLAction(request, response); + break; + case "VNFType": + dictionary.getVnfType(request, response); + break; + case "PEPOptions": + dictionary.getPEPOptions(request, response); + break; + case "Varbind": + dictionary.getVarbind(request, response); + break; + case "Service": + dictionary.getServiceType(request, response); + break; + case "Site": + dictionary.getSiteType(request, response); + break; + case "Settings": + dictionary.getSettingsDictionary(request, response); + break; + case "DescriptiveScope": + dictionary.getDescriptiveDictionary(request, response); + break; + case "Enforcer": + dictionary.getEnforcerDictionary(request, response); + break; + case "ActionList": + dictionary.getActionListDictionary(request, response); + break; + case "ProtocolList": + dictionary.getProtocolListDictionary(request, response); + break; + case "Zone": + dictionary.getZoneDictionary(request, response); + break; + case "SecurityZone": + dictionary.getSecurityZoneDictionary(request, response); + break; + case "PrefixList": + dictionary.getPrefixListDictionary(request, response); + break; + case "AddressGroup": + dictionary.getAddressGroupDictionary(request, response); + break; + case "ServiceGroup": + dictionary.getServiceGroupDictionary(request, response); + break; + case "ServiceList": + dictionary.getServiceListDictionary(request, response); + break; + case "TermList": + case "RuleList": + case "FirewallRuleList": + case "Term": + dictionary.getTermListDictionary(request, response); + break; + case "MicroServiceLocation": + dictionary.getMicroServiceLocationDictionary(request, response); + break; + case "MicroServiceConfigName": + dictionary.getMicroServiceConfigNameDictionary(request, response); + break; + case "DCAEUUID": + dictionary.getDCAEUUIDDictionary(request, response); + break; + case "MicroServiceModels": + dictionary.getMicroServiceModelsDictionary(request, response); + break; + case "PolicyScopeService": + dictionary.getPSServiceDictionary(request, response); + break; + case "PolicyScopeResource": + dictionary.getPSResourceDictionary(request, response); + break; + case "PolicyScopeType": + dictionary.getPSTypeDictionary(request, response); + break; + case "PolicyScopeClosedLoop": + dictionary.getPSClosedLoopDictionary(request, response); + break; + case "GroupPolicyScopeList": + dictionary.getPSGroupScopeDictionary(request, response); + break; + case "RiskType": + dictionary.getRiskTypeDictionary(request, response); + break; + case "SafePolicyWarning": + dictionary.getSafePolicyWarningDictionary(request, response); + break; + case "MicroServiceDictionary": + dictionary.getMicroServiceDictionary(request, response); + break; + default: + extendedOptions(dictionaryType, request, response, true); + return; + } + } catch (Exception e) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Querying the Database: " + e.getMessage(); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DictionaryHandler", " Error Querying the Database."); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "dictionaryDBQuery"); + response.addHeader("error", message); + return; + } + } + + /** + * Can be used to extend the services. + * + * getflag=true indicates Get Request. + * getflag=false indicates Put Request. + * @return + */ + public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag) { + // Default code + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Invalid Dictionary in Request."; + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "DictionaryHandler", " Invalid Dictionary in Request."); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.setHeader("error", "dictionary"); + response.addHeader("error", message); + return null; + } + + public void doDictionaryAPIPut(HttpServletRequest request, HttpServletResponse response) { + String result = null; + String dictionaryType = request.getParameter("dictionaryType"); + String operation = request.getParameter("operation"); + try { + DictionaryService dictionary = new DictionaryService(); + switch (dictionaryType) { + case "OnapName": + result = dictionary.saveOnapDictionary(request, response); + break; + case "Attribute": + result = dictionary.saveAttributeDictionary(request, response); + break; + case "Action": + result = dictionary.saveActionPolicyDictionary(request, response); + break; + case "BRMSParamTemplate": + result = dictionary.saveBRMSParamDictionary(request, response); + break; + case "VSCLAction": + result = dictionary.saveVSCLAction(request, response); + break; + case "VNFType": + result = dictionary.saveVnfType(request, response); + break; + case "PEPOptions": + result = dictionary.savePEPOptions(request, response); + break; + case "Varbind": + result = dictionary.saveVarbind(request, response); + break; + case "Service": + result = dictionary.saveServiceType(request, response); + break; + case "Site": + result = dictionary.saveSiteType(request, response); + break; + case "Settings": + result = dictionary.saveSettingsDictionary(request, response); + break; + case "DescriptiveScope": + result = dictionary.saveDescriptiveDictionary(request, response); + break; + case "Enforcer": + result = dictionary.saveEnforcerDictionary(request, response); + break; + case "ActionList": + result = dictionary.saveActionListDictionary(request, response); + break; + case "ProtocolList": + result = dictionary.saveProtocolListDictionary(request, response); + break; + case "Zone": + result = dictionary.saveZoneDictionary(request, response); + break; + case "SecurityZone": + result = dictionary.saveSecurityZoneDictionary(request, response); + break; + case "PrefixList": + result = dictionary.savePrefixListDictionary(request, response); + break; + case "AddressGroup": + result = dictionary.saveAddressGroupDictionary(request, response); + break; + case "ServiceGroup": + result = dictionary.saveServiceGroupDictionary(request, response); + break; + case "ServiceList": + result = dictionary.saveServiceListDictionary(request, response); + break; + case "TermList": + case "RuleList": + case "FirewallRuleList": + case "Term": + result = dictionary.saveTermListDictionary(request, response); + break; + case "MicroServiceLocation": + result = dictionary.saveMicroServiceLocationDictionary(request, response); + break; + case "MicroServiceConfigName": + result = dictionary.saveMicroServiceConfigNameDictionary(request, response); + break; + case "DCAEUUID": + result = dictionary.saveDCAEUUIDDictionary(request, response); + break; + case "MicroServiceModels": + result = dictionary.saveMicroServiceModelsDictionary(request, response); + break; + case "PolicyScopeService": + result = dictionary.savePSServiceDictionary(request, response); + break; + case "PolicyScopeResource": + result = dictionary.savePSResourceDictionary(request, response); + break; + case "PolicyScopeType": + result = dictionary.savePSTypeDictionary(request, response); + break; + case "PolicyScopeClosedLoop": + result = dictionary.savePSClosedLoopDictionary(request, response); + break; + case "GroupPolicyScopeList": + result = dictionary.savePSGroupScopeDictionary(request, response); + break; + case "RiskType": + result = dictionary.saveRiskTypeDictionary(request, response); + break; + case "SafePolicyWarning": + result = dictionary.saveSafePolicyWarningDictionary(request, response); + break; + case "MicroServiceDictionary": + result = dictionary.saveMicroServiceDictionary(request, response); + break; + default: + result = extendedOptions(dictionaryType, request, response, false); + if(result==null){ + return; + }else{ + break; + } + } + } catch (Exception e) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Updating the Database: " + e.getMessage(); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error Updating the Database."); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", message); + return; + } + if (result.equalsIgnoreCase("Success")) { + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("successMapKey", "success"); + if (operation.equalsIgnoreCase("update")) { + response.addHeader("operation", "updateDictionary"); + } else { + response.addHeader("operation", "createDictionary"); + } + } else if (result.equalsIgnoreCase("Duplicate")) { + response.setStatus(HttpServletResponse.SC_CONFLICT); + response.addHeader("error", "dictionaryItemExists"); + } else if (result.equalsIgnoreCase("DuplicateGroup")) { + response.setStatus(HttpServletResponse.SC_CONFLICT); + response.addHeader("error", "duplicateGroup"); + } else { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Updating the Database."; + PolicyLogger.error(message); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", message); + } + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java new file mode 100644 index 000000000..9ef0e6f1e --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java @@ -0,0 +1,123 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.handler; + +import java.io.File; +import java.net.URI; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.Query; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.rest.jpa.PolicyVersion; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; + +import com.att.research.xacml.util.XACMLProperties; + +public class PushPolicyHandler { + + /* + * Get Active Version. + */ + public void getActiveVersion(HttpServletRequest request, HttpServletResponse response) { + EntityManager em = null; + if(XACMLPapServlet.getEmf()!=null){ + em = (EntityManager) XACMLPapServlet.getEmf().createEntityManager(); + } + if (em==null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + XACMLPapServlet.getPersistenceUnit()); + return; + } + String policyScope = request.getParameter("policyScope"); + String filePrefix = request.getParameter("filePrefix"); + String policyName = request.getParameter("policyName"); + + String pvName = policyScope + File.separator + filePrefix + policyName; + int activeVersion = 0; + + //Get the Active Version to use in the ID + em.getTransaction().begin(); + Query query = em.createQuery("Select p from PolicyVersion p where p.policyName=:pname"); + query.setParameter("pname", pvName); + + @SuppressWarnings("rawtypes") + List result = query.getResultList(); + PolicyVersion versionEntity = null; + if (!result.isEmpty()) { + versionEntity = (PolicyVersion) result.get(0); + em.persist(versionEntity); + activeVersion = versionEntity.getActiveVersion(); + em.getTransaction().commit(); + } else { + PolicyLogger.debug("No PolicyVersion using policyName found"); + } + + //clean up connection + em.close(); + if (String.valueOf(activeVersion)!=null || !String.valueOf(activeVersion).equalsIgnoreCase("")) { + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("version", String.valueOf(activeVersion)); + } else { + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + } + } + + /* + * Get Selected URI path. + */ + public void getSelectedURI(HttpServletRequest request, HttpServletResponse response) { + String gitPath = request.getParameter("gitPath"); + File file = new File(gitPath); + PolicyLogger.debug("The fileItem is : " + file.toString()); + URI selectedURI = file.toURI(); + String uri = selectedURI.toString(); + if (!uri.equalsIgnoreCase("")) { + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("selectedURI", uri); + } else { + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + } + } + + public boolean preSafetyCheck(StdPDPPolicy policy, String configHome){ + return true; + } + + public boolean preSafetyCheck(OnapPDPGroup policy, String configHome){ + return true; + } + + public static PushPolicyHandler getInstance() { + try { + Class pushPolicyHandler = Class.forName(XACMLProperties.getProperty("pushPolicy.impl.className", PushPolicyHandler.class.getName())); + PushPolicyHandler instance = (PushPolicyHandler) pushPolicyHandler.newInstance(); + return instance; + } catch (Exception e) { + PolicyLogger.error(e.getMessage()); + } + return null; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java new file mode 100644 index 000000000..d88aee0cb --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java @@ -0,0 +1,157 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.handler; + +import java.io.IOException; +import java.util.HashMap; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.parsers.ParserConfigurationException; + +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.pap.xacml.rest.policycontroller.PolicyCreation; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; +import org.xml.sax.SAXException; + +import com.att.research.xacml.util.XACMLProperties; + +public class SavePolicyHandler { + private HashMap ErrorHeaders = null; + + public void doPolicyAPIPut(HttpServletRequest request, HttpServletResponse response) throws IOException { + String operation = request.getParameter("operation"); + String policyType = request.getParameter("policyType"); + String apiflag = request.getParameter("apiflag"); + PolicyCreation creation = new PolicyCreation(); + if ( policyType != null ) { + PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); + if("update".equalsIgnoreCase(operation)){ + policyAdapter.setEditPolicy(true); + }else{ + policyAdapter.setEditPolicy(false); + } + + // get the request 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(request.getInputStream()); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + PolicyLogger.info("JSON request from API: " + json); + // convert Object sent as JSON into local object + StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class); + //Set policyAdapter values including parentPath (Common to all policy types) + try { + policyAdapter = setDataToPolicyAdapter(policy, policyType, apiflag); + + if(!extendedPolicyOptions(policyAdapter, response)){ + creation.savePolicy(policyAdapter, response); + } + if ("update".equalsIgnoreCase(operation)) { + response.addHeader("operation", "update"); + } else { + response.addHeader("operation", "create"); + } + } catch (Exception e1) { + PolicyLogger.error(XACMLErrorConstants.ERROR_UNKNOWN + + "Could not set data to policy adapter "+ e1.getMessage()); + } + } + } + + private PolicyRestAdapter setDataToPolicyAdapter(StdPAPPolicy policy, String policyType, String apiflag) throws ParserConfigurationException, ServletException, SAXException, IOException{ + PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); + policyAdapter.setApiflag(apiflag); + /* + * set policy adapter values for Building JSON object containing policy data + */ + //Common among policy types + policyAdapter.setPolicyName(policy.getPolicyName()); + policyAdapter.setPolicyDescription(policy.getPolicyDescription()); + policyAdapter.setOnapName(policy.getOnapName()); //Config Base and Decision Policies + policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"); + + policyAdapter.setPolicyType(policyType); + policyAdapter.setDynamicFieldConfigAttributes(policy.getDynamicFieldConfigAttributes()); + policyAdapter.setEditPolicy(policy.isEditPolicy()); + policyAdapter.setEntityManagerFactory(XACMLPapServlet.getEmf()); + //Config Specific + policyAdapter.setConfigName(policy.getConfigName()); //Base and Firewall + policyAdapter.setConfigBodyData(policy.getConfigBodyData()); //Base + policyAdapter.setConfigType((policy.getConfigType()!=null) ? policy.getConfigType().toUpperCase(): null); //Base + policyAdapter.setJsonBody(policy.getJsonBody()); //Firewall, ClosedLoop + policyAdapter.setConfigPolicyType(policy.getConfigPolicyType()); + policyAdapter.setDraft(policy.isDraft()); //ClosedLoop_Fault + policyAdapter.setServiceType(policy.getServiceType()); //ClosedLoop_PM + policyAdapter.setUuid(policy.getUuid()); //Micro Service + policyAdapter.setLocation(policy.getMsLocation()); //Micro Service + policyAdapter.setPriority(policy.getPriority()); //Micro Service + policyAdapter.setPolicyScope(policy.getDomainDir()); + policyAdapter.setRiskType(policy.getRiskType()); //Safe Policy Attributes + policyAdapter.setRiskLevel(policy.getRiskLevel());//Safe Policy Attributes + policyAdapter.setGuard(policy.getGuard());//Safe Policy Attributes + policyAdapter.setTtlDate(policy.getTTLDate());//Safe Policy Attributes + policyAdapter.setBrmsParamBody(policy.getDrlRuleAndUIParams()); + policyAdapter.setBrmsDependency(policy.getBrmsDependency()); // BRMS Policies. + policyAdapter.setBrmsController(policy.getBrmsController()); // BRMS Policies. + //Action Policy Specific + policyAdapter.setActionAttribute(policy.getActionAttribute()); //comboDictValue + policyAdapter.setActionPerformer(policy.getActionPerformer()); + policyAdapter.setDynamicRuleAlgorithmLabels(policy.getDynamicRuleAlgorithmLabels()); + policyAdapter.setDynamicRuleAlgorithmCombo(policy.getDynamicRuleAlgorithmCombo()); + policyAdapter.setDynamicRuleAlgorithmField1(policy.getDynamicRuleAlgorithmField1()); + policyAdapter.setDynamicRuleAlgorithmField2(policy.getDynamicRuleAlgorithmField2()); + //Decision Policy Specific + policyAdapter.setDynamicSettingsMap(policy.getDynamicSettingsMap()); + policyAdapter.setRuleProvider(policy.getProviderComboBox()); + policyAdapter.setDomainDir(policyAdapter.getPolicyScope()); + policyAdapter.setDomain(policyAdapter.getPolicyScope()); + return policyAdapter; + } + + public boolean extendedPolicyOptions(PolicyRestAdapter policyAdapter, HttpServletResponse response){ + return false; + } + + public void addErrorHeader(String key, String value){ + if(ErrorHeaders==null){ + ErrorHeaders= new HashMap<>(); + } + ErrorHeaders.put(key, value); + } + + public static SavePolicyHandler getInstance() { + try { + Class savePolicyHandler = Class.forName(XACMLProperties.getProperty("savePolicy.impl.className", SavePolicyHandler.class.getName())); + SavePolicyHandler instance = (SavePolicyHandler) savePolicyHandler.newInstance(); + return instance; + } catch (Exception e) { + PolicyLogger.error(e.getMessage()); + } + return null; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/PDPPolicyContainer.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/PDPPolicyContainer.java new file mode 100644 index 000000000..cbcb7e04b --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/PDPPolicyContainer.java @@ -0,0 +1,348 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.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.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.util.PolicyContainer; +import org.onap.policy.pap.xacml.rest.util.PolicyItemSetChangeNotifier; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; + +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.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. + */ + public static String PROPERTY_ID = "Id"; + + /** + * String identifier of a file's "name" property. + */ + public static String PROPERTY_NAME = "Name"; + + /** + * String identifier of a file's "name" property. + */ + public static String PROPERTY_VERSION = "Version"; + + /** + * String identifier of a file's "Description" property. + */ + public static String PROPERTY_DESCRIPTION = "Description"; + + /** + * String identifier of a file's "IsRoot" property. + */ + public static String PROPERTY_ISROOT = "Root"; + + /** + * List of the string identifiers for the available properties. + */ + public 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/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java new file mode 100644 index 000000000..7645535b0 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.model; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDPGroup; + +import com.att.research.xacml.api.pap.PDPPolicy; + +public class RemoveGroupPolicy { + + + //Container from where we are fetching the policies + private static PDPPolicyContainer policyContainer; + + private final RemoveGroupPolicy self = this; + private StdPDPGroup updatedObject; + private final StdPDPGroup group; + private boolean isSaved = false; + + public RemoveGroupPolicy(StdPDPGroup group) { + + this.group = group; + + } + + public void prepareToRemove(PDPPolicy policy) { + + if (this.group == null) { + return; + } + + RemoveGroupPolicy.policyContainer = new PDPPolicyContainer(group); + + RemoveGroupPolicy.policyContainer.removeItem(policy); + + self.doSave(); + + self.isSaved = true; + + } + + @SuppressWarnings("unchecked") + protected void doSave() { + if (this.group == null) { + return; + } + + //StdPDPGroup pdpGroup = (StdPDPGroup) group; + StdPDPGroup updatedGroupObject = new StdPDPGroup( + group.getId(), + group.isDefaultGroup(), + group.getName(), + group.getDescription(), + null); + + // replace the original set of Policies with the set from the container (possibly modified by the user) + Set changedPolicies = new HashSet<>(); + changedPolicies.addAll((Collection) RemoveGroupPolicy.policyContainer.getItemIds()); + updatedGroupObject.setPolicies(changedPolicies); + updatedGroupObject.setOnapPdps(this.group.getOnapPdps()); + + // replace the original set of PIP Configs with the set from the container + updatedGroupObject.setPipConfigs(this.group.getPipConfigs()); + + // copy those things that the user cannot change from the original to the new object + updatedGroupObject.setStatus(this.group.getStatus()); + + this.updatedObject = updatedGroupObject; + } + + public boolean isRemoved() { + return this.isSaved; + } + + public OnapPDPGroup getUpdatedObject() { + return this.updatedObject; + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/package-info.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/package-info.java new file mode 100644 index 000000000..51d988887 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/package-info.java @@ -0,0 +1,20 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.model; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java new file mode 100644 index 000000000..80657fcd6 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java @@ -0,0 +1,550 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.policycontroller; + +import java.io.File; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.pap.xacml.rest.components.ActionPolicy; +import org.onap.policy.pap.xacml.rest.components.ClosedLoopPolicy; +import org.onap.policy.pap.xacml.rest.components.ConfigPolicy; +import org.onap.policy.pap.xacml.rest.components.CreateBrmsParamPolicy; +import org.onap.policy.pap.xacml.rest.components.CreateBrmsRawPolicy; +import org.onap.policy.pap.xacml.rest.components.CreateClosedLoopPerformanceMetrics; +import org.onap.policy.pap.xacml.rest.components.DecisionPolicy; +import org.onap.policy.pap.xacml.rest.components.FirewallConfigPolicy; +import org.onap.policy.pap.xacml.rest.components.MicroServiceConfigPolicy; +import org.onap.policy.pap.xacml.rest.components.Policy; +import org.onap.policy.pap.xacml.rest.components.PolicyDBDao; +import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTransaction; +import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticSearchController; +import org.onap.policy.pap.xacml.rest.util.AbstractPolicyCreation; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.ActionPolicyDict; +import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.PolicyEditorScopes; +import org.onap.policy.rest.jpa.PolicyVersion; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import com.fasterxml.jackson.databind.ObjectMapper; + + +@RestController +@RequestMapping("/") +public class PolicyCreation extends AbstractPolicyCreation{ + + private static final Logger LOGGER = FlexLogger.getLogger(PolicyCreation.class); + + private String ruleID = ""; + private PolicyDBDao policyDBDao; + String CLName = null; + + private static CommonClassDao commonClassDao; + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + PolicyCreation.commonClassDao = commonClassDao; + } + + @Autowired + public PolicyCreation(CommonClassDao commonClassDao){ + PolicyCreation.commonClassDao = commonClassDao; + } + + public PolicyCreation(){} + + @RequestMapping(value="/policycreation/save_policy", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity savePolicy(@RequestBody PolicyRestAdapter policyData, HttpServletResponse response) throws Exception{ + String body = null; + HttpStatus status = HttpStatus.BAD_REQUEST; + Map successMap = new HashMap<>(); + Map attributeMap = new HashMap<>(); + PolicyVersion policyVersionDao; + try { + + Policy newPolicy = null; + String policyConfigType = null; + String userId = policyData.getUserId(); + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL, false); + policyData.setTtlDate(newDate); + } + + String policyType = policyData.getPolicyType(); + + String filePrefix = null; + if (policyType.equalsIgnoreCase("Config")) { + policyConfigType = policyData.getConfigPolicyType(); + if (policyConfigType.equalsIgnoreCase("Firewall Config")) { + filePrefix = "Config_FW_"; + }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_Fault")) { + filePrefix = "Config_Fault_"; + }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_PM")) { + filePrefix = "Config_PM_"; + }else if (policyConfigType.equalsIgnoreCase("Micro Service")) { + filePrefix = "Config_MS_"; + }else if (policyConfigType.equalsIgnoreCase("BRMS_Raw")) { + filePrefix = "Config_BRMS_Raw_"; + }else if (policyConfigType.equalsIgnoreCase("BRMS_Param")) { + filePrefix = "Config_BRMS_Param_"; + }else { + filePrefix = "Config_"; + } + } else if (policyType.equalsIgnoreCase("Action")) { + filePrefix = "Action_"; + } else if (policyType.equalsIgnoreCase("Decision")) { + filePrefix = "Decision_"; + } + + int version = 0; + int highestVersion = 0; + String createdBy = ""; + String modifiedBy = userId; + String scopeCheck = policyData.getDomainDir().replace(".", File.separator); + PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scopeCheck); + if(policyEditorScope == null){ + UserInfo userInfo = new UserInfo(); + userInfo.setUserName("API"); + userInfo.setUserLoginId("API"); + PolicyEditorScopes editorScope = new PolicyEditorScopes(); + editorScope.setScopeName(scopeCheck); + editorScope.setUserCreatedBy(userInfo); + editorScope.setUserModifiedBy(userInfo); + commonClassDao.save(editorScope); + } + //get the highest version of policy from policy version table. + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + filePrefix + policyData.getPolicyName(); + PolicyVersion policyVersion = getPolicyVersionData(dbCheckPolicyName); + if(policyVersion == null){ + highestVersion = 0; + }else{ + highestVersion = policyVersion.getHigherVersion(); + } + + if(highestVersion != 0 && policyVersion != null){ + if(policyData.isEditPolicy()){ + version = highestVersion +1; + if(userId ==null){ + modifiedBy = "API"; + }else{ + modifiedBy = userId; + } + policyData.setUserId("API"); + createdBy = policyVersion.getCreatedBy(); + policyVersionDao = policyVersion; + policyVersionDao.setActiveVersion(version); + policyVersionDao.setHigherVersion(version); + policyVersionDao.setModifiedBy(modifiedBy); + }else{ + body = "policyExists"; + status = HttpStatus.CONFLICT; + response.setStatus(HttpServletResponse.SC_CONFLICT); + response.addHeader("error", "policyExists"); + response.addHeader("policyName", policyData.getPolicyName()); + return new ResponseEntity(body, status); + } + }else{ + version = 1; + if(userId == null){ + createdBy = "API"; + modifiedBy = "API"; + policyData.setUserId("API"); + }else{ + createdBy = userId; + modifiedBy = userId; + policyData.setUserId("API"); + } + policyVersionDao = new PolicyVersion(); + policyVersionDao.setPolicyName(dbCheckPolicyName); + policyVersionDao.setActiveVersion(version); + policyVersionDao.setHigherVersion(version); + policyVersionDao.setCreatedBy(createdBy); + policyVersionDao.setModifiedBy(modifiedBy); + } + + policyData.setPolicyID(newPolicyID()); + policyData.setRuleID(ruleID); + + String policyFileName = dbCheckPolicyName.replace(File.separator, ".")+ "." + version + ".xml"; + policyData.setNewFileName(policyFileName); + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + policyData.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"); + if(policyData.getApiflag() == null){ + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + if(policyData.getAttributes() != null){ + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("key").toString(); + String value = ((LinkedHashMap) attribute).get("value").toString(); + attributeMap.put(key, value); + } + } + } + } + policyData.setDynamicFieldConfigAttributes(attributeMap); + } + + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + + // Calling Component class per policy type + if (policyType.equalsIgnoreCase("Config")) { + if (policyConfigType.equalsIgnoreCase("Firewall Config")) { + newPolicy = new FirewallConfigPolicy(policyData); + }else if (policyConfigType.equalsIgnoreCase("BRMS_Raw")) { + policyData.setOnapName("DROOLS"); + policyData.setConfigName("BRMS_RAW_RULE"); + newPolicy = new CreateBrmsRawPolicy(policyData); + }else if (policyConfigType.equalsIgnoreCase("BRMS_Param")) { + policyData.setOnapName("DROOLS"); + policyData.setConfigName("BRMS_PARAM_RULE"); + Map drlRuleAndUIParams = new HashMap<>(); + if(policyData.getApiflag() == null){ + // If there is any dynamic field create the matches here + String key="templateName"; + String value=(String) policyData.getRuleName(); + drlRuleAndUIParams.put(key, value); + if(policyData.getRuleData().size() > 0){ + for(Object keyValue: policyData.getRuleData().keySet()){ + drlRuleAndUIParams.put(keyValue.toString(), policyData.getRuleData().get(keyValue).toString()); + } + } + policyData.setBrmsParamBody(drlRuleAndUIParams); + }else{ + drlRuleAndUIParams=policyData.getBrmsParamBody(); + String modelName= drlRuleAndUIParams.get("templateName"); + PolicyLogger.info("Template name from API is: "+modelName); + + BRMSParamTemplate template = (BRMSParamTemplate) commonClassDao.getEntityItem(BRMSParamTemplate.class, "ruleName", modelName); + if(template == null){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, " + + modelName + " was not found in the dictionary."; + body = message; + status = HttpStatus.BAD_REQUEST; + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", message); + response.addHeader("modelName", modelName); + return new ResponseEntity(body, status); + } + } + newPolicy = new CreateBrmsParamPolicy(policyData); + }else if (policyConfigType.equalsIgnoreCase("Base")) { + newPolicy = new ConfigPolicy(policyData); + }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_Fault")) { + newPolicy = new ClosedLoopPolicy(policyData); + }else if (policyConfigType.equalsIgnoreCase("ClosedLoop_PM")) { + if(policyData.getApiflag() == null){ + policyData.setServiceType(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString()); + ObjectMapper jsonMapper = new ObjectMapper(); + String jsonBody = jsonMapper.writeValueAsString(policyData.getJsonBodyData()); + jsonBody = jsonBody.replaceFirst("\\{", "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\","); + jsonBody = jsonBody.replace("serviceTypeFieldValue", policyData.getServiceType()); + policyData.setJsonBody(jsonBody); + } + newPolicy = new CreateClosedLoopPerformanceMetrics(policyData); + }else if (policyConfigType.equalsIgnoreCase("Micro Service")) { + newPolicy = new MicroServiceConfigPolicy(policyData); + } + }else if(policyType.equalsIgnoreCase("Action")) { + if(policyData.getApiflag() == null){ + List dynamicRuleAlgorithmLabels = new LinkedList<>(); + List dynamicRuleAlgorithmCombo = new LinkedList<>(); + List dynamicRuleAlgorithmField1 = new LinkedList<>(); + List dynamicRuleAlgorithmField2 = new LinkedList<>(); + + + if(policyData.getRuleAlgorithmschoices().size() > 0){ + for(Object attribute : policyData.getRuleAlgorithmschoices()){ + if(attribute instanceof LinkedHashMap){ + 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(); + dynamicRuleAlgorithmLabels.add(label); + dynamicRuleAlgorithmField1.add(key); + dynamicRuleAlgorithmCombo.add(rule); + dynamicRuleAlgorithmField2.add(value); + } + } + } + + String actionDictValue = policyData.getActionAttributeValue(); + ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", actionDictValue)); + String actionBodyString = jsonData.getBody(); + String actionDictHeader = jsonData.getHeader(); + String actionDictType = jsonData.getType(); + String actionDictUrl = jsonData.getUrl(); + String actionDictMethod = jsonData.getMethod(); + policyData.setActionDictHeader(actionDictHeader); + policyData.setActionDictType(actionDictType); + policyData.setActionDictUrl(actionDictUrl); + policyData.setActionDictMethod(actionDictMethod); + policyData.setActionAttribute(actionDictValue); + policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); + policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); + policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); + policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); + if (actionBodyString != null) { + policyData.setActionBody(actionBodyString); + } + } + newPolicy = new ActionPolicy(policyData); + } else if (policyType.equalsIgnoreCase("Decision")) { + if(policyData.getApiflag() == null){ + Map settingsMap = new HashMap<>(); + Map treatmentMap = new HashMap<>(); + List dynamicRuleAlgorithmLabels = new LinkedList<>(); + List dynamicRuleAlgorithmCombo = new LinkedList<>(); + List dynamicRuleAlgorithmField1 = new LinkedList<>(); + List dynamicRuleAlgorithmField2 = new LinkedList<>(); + List dynamicVariableList = new LinkedList<>(); + List dataTypeList = new LinkedList<>(); + List errorCodeList = new LinkedList<>(); + List treatmentList = new LinkedList<>(); + + if(policyData.getSettings().size() > 0){ + for(Object settingsData : policyData.getSettings()){ + if(settingsData instanceof LinkedHashMap){ + String key = ((LinkedHashMap) settingsData).get("key").toString(); + String value = ((LinkedHashMap) settingsData).get("value").toString(); + settingsMap.put(key, value); + } + } + } + if(policyData.getRuleAlgorithmschoices()!=null && policyData.getRuleAlgorithmschoices().size() > 0){ + for(Object attribute : policyData.getRuleAlgorithmschoices()){ + if(attribute instanceof LinkedHashMap){ + 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(); + dynamicRuleAlgorithmLabels.add(label); + dynamicRuleAlgorithmField1.add(key); + dynamicRuleAlgorithmCombo.add(rule); + dynamicRuleAlgorithmField2.add(value); + } + } + } + if(policyData.getRuleProvider()!=null && (policyData.getRuleProvider().equals(DecisionPolicy.GUARD_YAML)|| policyData.getRuleProvider().equals(DecisionPolicy.GUARD_BL_YAML)) + && policyData.getYamlparams()!=null){ + attributeMap.put("actor", policyData.getYamlparams().getActor()); + attributeMap.put("recipe", policyData.getYamlparams().getRecipe()); + attributeMap.put("clname", policyData.getYamlparams().getClname()); + attributeMap.put("limit", policyData.getYamlparams().getLimit()); + attributeMap.put("timeWindow", policyData.getYamlparams().getTimeWindow()); + attributeMap.put("timeUnits", policyData.getYamlparams().getTimeUnits()); + attributeMap.put("guardActiveStart", policyData.getYamlparams().getGuardActiveStart()); + attributeMap.put("guardActiveEnd", policyData.getYamlparams().getGuardActiveEnd()); + if(policyData.getYamlparams().getBlackList()!=null){ + String blackList = StringUtils.join(policyData.getYamlparams().getBlackList(), ","); + attributeMap.put("blackList", blackList); + } + if(policyData.getYamlparams().getTargets()!=null){ + String targets = StringUtils.join(policyData.getYamlparams().getTargets(),","); + attributeMap.put("targets", targets); + } + } + if(policyData.getRuleProvider()!=null && policyData.getRuleProvider().equals(DecisionPolicy.RAINY_DAY)){ + attributeMap.put("ServiceType", policyData.getRainyday().getServiceType()); + attributeMap.put("VNFType", policyData.getRainyday().getVnfType()); + attributeMap.put("BB_ID", policyData.getRainyday().getBbid()); + attributeMap.put("WorkStep", policyData.getRainyday().getWorkstep()); + + if(policyData.getRainyday().getTreatmentTableChoices()!=null && policyData.getRainyday().getTreatmentTableChoices().size() > 0){ + for (Object table : policyData.getRainyday().getTreatmentTableChoices()){ + if(table instanceof LinkedHashMap){ + String errorcode = ((LinkedHashMap) table).get("errorcode").toString(); + String treatment = ((LinkedHashMap) table).get("treatment").toString(); + treatmentMap.put(errorcode, treatment); + } + } + } + } + + policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); + policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); + policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); + policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); + policyData.setDynamicVariableList(dynamicVariableList); + policyData.setDynamicSettingsMap(settingsMap); + policyData.setDynamicFieldConfigAttributes(attributeMap); + policyData.setDataTypeList(dataTypeList); + policyData.setRainydayMap(treatmentMap); + policyData.setErrorCodeList(errorCodeList); + policyData.setTreatmentList(treatmentList); + } + newPolicy = new DecisionPolicy(policyData); + } + + if(newPolicy != null){ + newPolicy.prepareToSave(); + }else{ + body = "error"; + status = HttpStatus.INTERNAL_SERVER_ERROR; + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader("error", "error"); + return new ResponseEntity(body, status); + } + + PolicyDBDaoTransaction policyDBDaoTransaction = null; + try{ + policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(XACMLPapServlet.getEmf()); + policyDBDaoTransaction = policyDBDao.getNewTransaction(); + policyDBDaoTransaction.createPolicy(newPolicy, policyData.getUserId()); + successMap = newPolicy.savePolicies(); + if(successMap.containsKey("success")){ + policyDBDaoTransaction.commitTransaction(); + if(policyData.isEditPolicy()){ + commonClassDao.update(policyVersionDao); + }else{ + commonClassDao.save(policyVersionDao); + } + try{ + PolicyElasticSearchController search= new PolicyElasticSearchController(); + search.updateElk(policyData); + }catch(Exception e){ + LOGGER.error("Error Occured while saving policy to Elastic Database"+e); + } + body = "success"; + status = HttpStatus.OK; + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("successMapKey", "success"); + response.addHeader("policyName", policyData.getNewFileName()); + + //get message from the SafetyCheckerResults if present + String safetyCheckerResponse = policyData.getClWarning(); + String existingCLName = policyData.getExistingCLName(); + + //if safetyCheckerResponse is not null add a header to send back with response + if(safetyCheckerResponse!=null) { + PolicyLogger.info("SafetyCheckerResponse message: " + safetyCheckerResponse); + response.addHeader("safetyChecker", safetyCheckerResponse); + response.addHeader("newCLName", CLName); + response.addHeader("conflictCLName", existingCLName); + } else { + PolicyLogger.info("SafetyCheckerResponse was empty or null."); + } + + }else if (successMap.containsKey("invalidAttribute")) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Attribute"; + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine " + policyData.getActionAttribute() + " in the ActionPolicyDict table."); + body = "invalidAttribute"; + status = HttpStatus.BAD_REQUEST; + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("invalidAttribute", policyData.getActionAttribute()); + response.addHeader("error", message); + response.addHeader("policyName", policyData.getPolicyName()); + }else if (successMap.containsKey("fwdberror")) { + policyDBDaoTransaction.rollbackTransaction(); + body = "fwdberror"; + status = HttpStatus.BAD_REQUEST; + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Error when inserting Firewall ConfigBody data into the database."; + PolicyLogger.error(message); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", message); + response.addHeader("policyName", policyData.getPolicyName()); + } else if (successMap.get("error").equals("Validation Failed")) { + policyDBDaoTransaction.rollbackTransaction(); + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Error Validating the Policy on the PAP."; + PolicyLogger.error(message); + body = "Validation"; + status = HttpStatus.BAD_REQUEST; + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", message); + response.addHeader("policyName", policyData.getPolicyName()); + }else { + policyDBDaoTransaction.rollbackTransaction(); + body = "error"; + status = HttpStatus.INTERNAL_SERVER_ERROR; + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader("error", "error"); + } + }catch(Exception e){ + if(policyDBDaoTransaction != null){ + policyDBDaoTransaction.rollbackTransaction(); + } + } + } + catch (Exception e){ + LOGGER.error("Exception Occured : "+e); + body = "error"; + response.addHeader("error", e.getMessage()); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } + return new ResponseEntity<>(body, status); + } + + @ExceptionHandler({ HttpMessageNotReadableException.class }) + public ResponseEntity messageNotReadableExceptionHandler(HttpServletRequest req, HttpMessageNotReadableException exception) { + LOGGER.error("Request not readable: {}", exception); + StringBuilder message = new StringBuilder(); + message.append(exception.getMessage()); + if (exception.getCause() != null) { + message.append(" Reason Caused: " + + exception.getCause().getMessage()); + } + return new ResponseEntity<>(message.toString(), HttpStatus.BAD_REQUEST); + } + + public PolicyVersion getPolicyVersionData(String dbCheckPolicyName){ + PolicyVersion entityItem = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", dbCheckPolicyName); + if (entityItem != null) { + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + return entityItem; + } + } + return entityItem; + } +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/package-info.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/package-info.java new file mode 100644 index 000000000..bb5307573 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/package-info.java @@ -0,0 +1,20 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.policycontroller; \ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java new file mode 100644 index 000000000..df1916be9 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java @@ -0,0 +1,995 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.service; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.controller.ActionPolicyDictionaryController; +import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; +import org.onap.policy.pap.xacml.rest.controller.ClosedLoopDictionaryController; +import org.onap.policy.pap.xacml.rest.controller.DecisionPolicyDictionaryController; +import org.onap.policy.pap.xacml.rest.controller.DescriptiveDictionaryController; +import org.onap.policy.pap.xacml.rest.controller.DictionaryController; +import org.onap.policy.pap.xacml.rest.controller.EnforcerDictionaryController; +import org.onap.policy.pap.xacml.rest.controller.FirewallDictionaryController; +import org.onap.policy.pap.xacml.rest.controller.MicroServiceDictionaryController; +import org.onap.policy.pap.xacml.rest.controller.PolicyScopeDictionaryController; +import org.onap.policy.pap.xacml.rest.controller.SafePolicyController; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.stereotype.Service; +import org.springframework.web.servlet.ModelAndView; + + +@Service("DictionaryService") +public class DictionaryService { + + private static final Logger LOGGER = FlexLogger.getLogger(DictionaryService.class); + + /* + * Methods that call the controller method directly to Save and Update dictionary data + */ + public String saveOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + DictionaryController dictionary = new DictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveOnapDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + + return responseString; + + } + + public String saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + DictionaryController dictionary = new DictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveAttributeDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + + return responseString; + } + + public String saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ActionPolicyDictionaryController action = new ActionPolicyDictionaryController(); + String responseString = null; + try { + ModelAndView result = action.saveActionPolicyDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + + return responseString; + } + + public String saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + BRMSDictionaryController dictionary = new BRMSDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveBRMSParamDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + + return responseString; + } + + public String saveVSCLAction(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveVSCLAction(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + + return responseString; + } + + public String saveVnfType(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveVnfType(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + + return responseString; + } + + public String savePEPOptions(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.savePEPOptions(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + + return responseString; + } + + public String saveVarbind(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveVarbind(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + + return responseString; + } + + public String saveServiceType(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveServiceType(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + + return responseString; + } + + public String saveSiteType(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveSiteType(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + + return responseString; + } + + public String saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveSettingsDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveDescriptiveDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveEnforcerDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + EnforcerDictionaryController dictionary = new EnforcerDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveEnforcerDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveActionListDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveProtocolListDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveZoneDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveSecurityZoneDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.savePrefixListDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveAddressGroupDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveServiceGroupDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveServiceListDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveTermListDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + + + + public String saveMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveMicroServiceLocationDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveMicroServiceConfigNameDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveDCAEUUIDDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveMicroServiceModelsDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveMicroServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveMicroServiceAttributeDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.savePSServiceDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.savePSResourceDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.savePSTypeDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String savePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.savePSClosedLoopDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + String responseString = null; + try { + ModelAndView result = dictionary.savePSGroupScopeDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + SafePolicyController dictionary = new SafePolicyController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveRiskTypeDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + public String saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + SafePolicyController dictionary = new SafePolicyController(); + String responseString = null; + try { + ModelAndView result = dictionary.saveSafePolicyWarningDictionary(request, response); + responseString = result.getViewName(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + return responseString; + } + + + /* + * Methods that call the controller get methods directly to get dictionary data + */ + public void getOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + DictionaryController dictionary = new DictionaryController(); + try { + dictionary.getOnapNameDictionaryEntityData(request, response); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + DictionaryController dictionary = new DictionaryController(); + try { + dictionary.getAttributeDictionaryEntityData(request, response); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ActionPolicyDictionaryController action = new ActionPolicyDictionaryController(); + try { + action.getActionPolicyDictionaryEntityData(request, response); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + BRMSDictionaryController dictionary = new BRMSDictionaryController(); + try { + dictionary.getBRMSParamDictionaryEntityData(request, response); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + } + + public void getVSCLAction(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + try { + dictionary.getVSCLActionDictionaryEntityData(request, response); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getVnfType(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + try { + dictionary.getVNFTypeDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + } + + public void getPEPOptions(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + try { + dictionary.getPEPOptionsDictionaryEntityData(request, response); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getVarbind(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + try { + dictionary.getVarbindDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + + } + + public void getServiceType(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + try { + dictionary.getClosedLoopServiceDictionaryEntityData(request, response); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getSiteType(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + ClosedLoopDictionaryController dictionary = new ClosedLoopDictionaryController(); + try { + dictionary.getClosedLoopSiteDictionaryEntityData(request, response); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + DecisionPolicyDictionaryController dictionary = new DecisionPolicyDictionaryController(); + try { + dictionary.getSettingsDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + DescriptiveDictionaryController dictionary = new DescriptiveDictionaryController(); + try { + dictionary.getDescriptiveDictionaryEntityData(request, response); + + } catch (Exception e) { + + } + } + + public void getEnforcerDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + EnforcerDictionaryController dictionary = new EnforcerDictionaryController(); + try { + dictionary.getEnforcerDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getActionListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + try { + dictionary.getActionListDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + try { + dictionary.getProtocolListDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + try { + dictionary.getZoneDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + try { + dictionary.getSecurityZoneDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getPrefixListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + try { + dictionary.getPrefixListDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + try { + dictionary.getAddressGroupDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + try { + dictionary.getServiceGroupDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getServiceListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + try { + dictionary.getServiceListDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + FirewallDictionaryController dictionary = new FirewallDictionaryController(); + try { + dictionary.getTermListDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + + public void getMicroServiceLocationDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + try { + dictionary.getMicroServiceLocationDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getMicroServiceConfigNameDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + try { + dictionary.getMicroServiceConfigNameDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getDCAEUUIDDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + try { + dictionary.getDCAEUUIDDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getMicroServiceModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + try { + dictionary.getMicroServiceModelsDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getMicroServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + MicroServiceDictionaryController dictionary = new MicroServiceDictionaryController(); + try { + dictionary.getMicroServiceModelsDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getPSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + try { + dictionary.getPSServiceEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getPSResourceDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + try { + dictionary.getPSResourceEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getPSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + try { + dictionary.getPSTypeEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getPSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + try { + dictionary.getPSClosedLoopEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getPSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + PolicyScopeDictionaryController dictionary = new PolicyScopeDictionaryController(); + try { + dictionary.getGroupPolicyScopeEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + SafePolicyController dictionary = new SafePolicyController(); + try { + dictionary.getOnapNameDictionaryEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } + + public void getSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + SafePolicyController dictionary = new SafePolicyController(); + try { + dictionary.getSafePolicyWarningeEntityData(request, response); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + + } + } +} \ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java new file mode 100644 index 000000000..0a5da0ec3 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java @@ -0,0 +1,157 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.service; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.pap.xacml.rest.components.CreateBRMSRuleTemplate; +import org.onap.policy.pap.xacml.rest.components.CreateNewMicroServiceModel; + +public class ImportService { + + public void doImportMicroServicePut(HttpServletRequest request, HttpServletResponse response) { + String importServiceCreation = request.getParameter("importService");; + String fileName = request.getParameter("fileName"); + String version = request.getParameter("version"); + String serviceName = request.getParameter("serviceName"); + String description = request.getParameter("description"); + Map successMap = new HashMap<>(); + switch(importServiceCreation){ + case "BRMSPARAM": + StringBuilder builder = new StringBuilder(); + int ch; + try { + while((ch = request.getInputStream().read()) != -1){ + builder.append((char)ch); + } + } catch (IOException e) { + PolicyLogger.error("Error in reading in file from API call"); + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader("error", "missing"); + response.addHeader("operation", "import"); + response.addHeader("service", serviceName); + } + CreateBRMSRuleTemplate brmsRuleTemplate = new CreateBRMSRuleTemplate(); + successMap = brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API"); + break; + case "MICROSERVICE": + CreateNewMicroServiceModel newMS = null; + String randomID = UUID.randomUUID().toString(); + if ( fileName != null) { + File extracDir = new File("ExtractDir"); + if (!extracDir.exists()){ + extracDir.mkdirs(); + } + if (fileName.contains(".xmi")){ + // get the request content into a String + String xmi = null; + java.util.Scanner scanner; + try { + scanner = new java.util.Scanner(request.getInputStream()); + scanner.useDelimiter("\\A"); + xmi = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + } catch (IOException e1) { + PolicyLogger.error("Error in reading in file from API call"); + return; + } + PolicyLogger.info("XML request from API for import new Service"); + try (Writer writer = new BufferedWriter(new OutputStreamWriter( + new FileOutputStream("ExtractDir" + File.separator + randomID+".xmi"), "utf-8"))) { + writer.write(xmi); + } catch (IOException e) { + PolicyLogger.error("Error in reading in file from API call"); + return; + } + }else{ + InputStream inputStream = null; + try(FileOutputStream outputStream = new FileOutputStream("ExtractDir" + File.separator + randomID+".zip")) { + inputStream = request.getInputStream(); + byte[] buffer = new byte[4096]; + int bytesRead = -1 ; + while ((bytesRead = inputStream.read(buffer)) != -1) { + outputStream.write(buffer, 0, bytesRead) ; + } + } catch (IOException e) { + PolicyLogger.error("Error in reading in Zip File from API call"+e); + return; + }finally{ + try { + if(inputStream != null){ + inputStream.close(); + } + } catch (IOException e) { + PolicyLogger.error("Exception Occured while closing the input/output stream"+e); + } + } + } + newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, randomID); + successMap = newMS.addValuesToNewModel(); + if (successMap.containsKey("success")) { + successMap.clear(); + successMap = newMS.saveImportService(); + } + } + break; + } + // return a response to the PAP + if (successMap.containsKey("success")) { + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "import"); + response.addHeader("service", serviceName); + } else if (successMap.containsKey("DBError")) { + if (successMap.get("DBError").contains("EXISTS")){ + response.setStatus(HttpServletResponse.SC_CONFLICT); + response.addHeader("service", serviceName); + response.addHeader("error", "modelExistsDB"); + }else{ + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader("error", "importDB"); + } + response.addHeader("operation", "import"); + response.addHeader("service", serviceName); + }else if (successMap.get("error").contains("MISSING")){ + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader("error", "missing"); + response.addHeader("operation", "import"); + response.addHeader("service", serviceName); + }else if (successMap.get("error").contains("VALIDATION")){ + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + response.addHeader("error", "validation"); + response.addHeader("operation", "import"); + response.addHeader("service", serviceName); + } + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java new file mode 100644 index 000000000..416af4413 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.service; + +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.EntityManager; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; + +import com.att.research.xacml.api.pap.PDPPolicy; + +public class MetricService { + + public static void doGetPolicyMetrics(HttpServletRequest request, HttpServletResponse response) { + Set groups = new HashSet<>(); + try { + //get the count of policies on the PDP + if(XACMLPapServlet.getPAPEngine()!=null){ + groups = XACMLPapServlet.getPAPEngine().getOnapPDPGroups(); + } + int pdpCount = 0; + for (OnapPDPGroup group : groups) { + Set policies = group.getPolicies(); + pdpCount += policies.size(); + } + //get the count of policies on the PAP + EntityManager em = null; + if(XACMLPapServlet.getEmf()!=null){ + em = (EntityManager) XACMLPapServlet.getEmf().createEntityManager(); + } + if (em==null){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Error creating entity manager with persistence unit: " + XACMLPapServlet.getPersistenceUnit()); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", "Error creating entity manager with persistence unit"); + return; + } + int papCount = ((Number) em.createNamedQuery("PolicyVersion.findAllCount").getSingleResult()).intValue(); + em.close(); + int totalCount = pdpCount + papCount; + //create json string for API response + JSONObject json = new JSONObject(); + json.put("papCount", papCount); + json.put("pdpCount", pdpCount); + json.put("totalCount", totalCount); + if (pdpCount>0 && papCount>0 && totalCount>0) { + PolicyLogger.info("Metrics have been found on the Policy Engine for the number of policies on the PAP and PDP."); + response.setStatus(HttpServletResponse.SC_OK); + response.addHeader("successMapKey", "success"); + response.addHeader("operation", "getMetrics"); + response.addHeader("metrics", json.toString() ); + return; + }else{ + String message = "The policy count on the PAP and PDP is 0. Please check the database and file system to correct this error."; + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", message); + return; + } + } catch (Exception e) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + " Error Querying the Database: " + e.getMessage(); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error Querying the Database."); + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + response.addHeader("error", message); + return; + } + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java new file mode 100644 index 000000000..71de2b297 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.util; + + +import java.util.UUID; + +import org.onap.policy.rest.XACMLRestProperties; +import org.springframework.stereotype.Component; + +import com.att.research.xacml.util.XACMLProperties; +import com.google.common.base.Joiner; + +@Component +public abstract class AbstractPolicyCreation { + + public static String getDomain() { + return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn"); + } + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((getDomain().startsWith("urn") ? null: "urn"), + getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + public 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]; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + + + public void updatePolicyCreationToDatabase(){ + // Add it into our tree +/* Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List policyVersionList = commonClassDao.getDataById(PolicyVersion.class, "policyName", removeExtension); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = (PolicyVersion) policyVersionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + commonClassDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, commonClassDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + commonClassDao.save(entityItem); + } + }*/ + } + + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java new file mode 100644 index 000000000..732ed2f44 --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java @@ -0,0 +1,239 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Query; +import javax.servlet.ServletException; + +import org.onap.policy.rest.XacmlAdminAuthorization; +import org.onap.policy.rest.jpa.Attribute; +import org.onap.policy.rest.jpa.Datatype; +import org.onap.policy.rest.jpa.FunctionDefinition; +import org.onap.policy.rest.jpa.GlobalRoleSettings; + +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 org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +public class JPAUtils { + private static Logger LOGGER = FlexLogger.getLogger(JPAUtils.class); + + private EntityManagerFactory emf; + private static final Object mapAccess = new Object(); + private static Map> mapDatatype2Function = null; + private static Map mapID2Function = null; + private static JPAUtils currentInstance = null; + + + /** + * Get an instance of a JPAUtils. It creates one if it does not exist. + * Only one instance is allowed to be created per server. + * @param emf The EntityFactoryManager to be used for database connections + * @return The new instance of JPAUtils or throw exception if the given emf is null. + * @throws IllegalStateException if a JPAUtils has already been constructed. Call getJPAUtilsInstance() to get this. + */ + public static JPAUtils getJPAUtilsInstance(EntityManagerFactory emf) throws Exception{ + LOGGER.debug("getJPAUtilsInstance(EntityManagerFactory emf) as getJPAUtilsInstance("+emf+") called"); + if(currentInstance == null){ + if(emf != null){ + currentInstance = new JPAUtils(emf); + return currentInstance; + } + throw new IllegalStateException("The EntityManagerFactory is Null"); + } + return currentInstance; + } + + private JPAUtils(EntityManagerFactory emf){ + LOGGER.debug("JPAUtils(EntityManagerFactory emf) as JPAUtils("+emf+") called"); + this.emf = emf; + } + + /** + * Gets the current instance of JPAUtils. + * @return The instance of JPAUtils or throws exception if the given instance is null. + * @throws IllegalStateException if a JPAUtils instance is null. Call getJPAUtilsInstance(EntityManagerFactory emf) to get this. + */ + public static JPAUtils getJPAUtilsInstance() throws Exception{ + LOGGER.debug("getJPAUtilsInstance() as getJPAUtilsInstance() called"); + if(currentInstance != null){ + return currentInstance; + } + throw new IllegalStateException("The JPAUtils.currentInstance is Null. Use getJPAUtilsInstance(EntityManagerFactory emf)"); + } + + public static AttributeDesignatorType createDesignator(Attribute attribute) { + AttributeDesignatorType designator = new AttributeDesignatorType(); + designator.setAttributeId(attribute.getXacmlId()); + if (attribute.getCategoryBean() != null) { + designator.setCategory(attribute.getCategoryBean().getXacmlId()); + } else { + LOGGER.warn("No category bean"); + } + if (attribute.getDatatypeBean() != null) { + designator.setDataType(attribute.getDatatypeBean().getXacmlId()); + } else { + LOGGER.warn("No datatype bean"); + } + designator.setIssuer(attribute.getIssuer()); + designator.setMustBePresent(attribute.isMustBePresent()); + return designator; + } + + public static AttributeSelectorType createSelector(Attribute attribute) { + AttributeSelectorType selector = new AttributeSelectorType(); + selector.setContextSelectorId(attribute.getXacmlId()); + selector.setPath(attribute.getSelectorPath()); + if (attribute.getCategoryBean() != null) { + selector.setCategory(attribute.getCategoryBean().getXacmlId()); + } else { + LOGGER.warn("No category bean"); + } + if (attribute.getDatatypeBean() != null) { + selector.setDataType(attribute.getDatatypeBean().getXacmlId()); + } else { + LOGGER.warn("No datatype bean"); + } + selector.setMustBePresent(attribute.isMustBePresent()); + return selector; + } + + /** + * Builds a map in memory of a functions return datatype to function definition. Useful in limiting the number + * of SQL calls to DB especially when we don't expect these to change much. + * + * @return - A HashMap of Datatype JPA Container ID's to FunctionDefinition objects + */ + public Map> getFunctionDatatypeMap() { + + synchronized(mapAccess) { + if (mapDatatype2Function == null||mapDatatype2Function.isEmpty()) { + try { + buildFunctionMaps(); + } catch (ServletException e) { + LOGGER.error("Exception Occured"+e); + } + } + } + return mapDatatype2Function; + } + + public Map getFunctionIDMap() { + synchronized(mapAccess) { + if (mapID2Function == null||mapID2Function.equals("{}")) { + try { + buildFunctionMaps(); + } catch (ServletException e) { + LOGGER.error("Exception Occured"+e); + } + } + } + return mapID2Function; + } + + private void buildFunctionMaps() throws ServletException { + mapDatatype2Function = new HashMap<>(); + mapID2Function = new HashMap<>(); + + EntityManager em = emf.createEntityManager(); + Query getFunctionDefinitions = em.createNamedQuery("FunctionDefinition.findAll"); + List functionList = getFunctionDefinitions.getResultList(); + + for (Object id : functionList) { + FunctionDefinition value = (FunctionDefinition)id; + mapID2Function.put(value.getXacmlid(), value); + if (mapDatatype2Function.containsKey(value.getDatatypeBean()) == false) { + mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList()); + } + mapDatatype2Function.get(value.getDatatypeBean()).add(value); + } + + em.close(); + + } + + /** + * Returns the lockdown value, in case of exception it is assumed that lockdown functionality + * is not supported and returns false. + * + * + * @throws ReadOnlyException + * @throws ConversionException + */ + public boolean dbLockdownIgnoreErrors() { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + boolean lockdown = false; + try { + lockdown = dbLockdown(); + } catch (Exception e) { + LOGGER.warn("Cannot access DB lockdown value", e); + } + return lockdown; + } + + /** + * Returns the lockdown value from the database. + * + * @throws ReadOnlyException + * @throws ConversionException + */ + public boolean dbLockdown() + throws IllegalAccessException { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + EntityManager em = emf.createEntityManager(); + Query globalRoleSettingsJPA = em.createNamedQuery("GlobalRoleSettings.findAll"); + + GlobalRoleSettings globalRoleSettings = (GlobalRoleSettings) globalRoleSettingsJPA.getSingleResult(); + + if (globalRoleSettings == null) { + // this should not happen + String msg = "NO GlobalSetttings for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString(); + if (LOGGER.isErrorEnabled()) + LOGGER.error(msg); + throw new IllegalAccessException(msg); + } + + if (!globalRoleSettings.getRole().equals(XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString())) { + String msg = "NOT FOUND db data for " + XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString(); + if (LOGGER.isErrorEnabled()) + LOGGER.error(msg); + throw new IllegalAccessException(msg); + } + + return globalRoleSettings.isLockdown(); + } + + + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java new file mode 100644 index 000000000..ab3b126ea --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java @@ -0,0 +1,67 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.util; + +public class JsonMessage { + + private String data; + private String data2; + private String data3; + public JsonMessage(String data) { + super(); + this.data = data; + } + public JsonMessage(String data,String data2) { + super(); + this.data = data; + this.data2 = data2; + } + + public JsonMessage(String data,String data2,String data3) { + super(); + this.data = data; + this.data2 = data2; + this.data3 = data3; + } + + public String getData() { + return data; + } + + public void setData(String data) { + this.data = data; + } + public String getData2() { + return data2; + } + public void setData2(String data2) { + this.data2 = data2; + } + public String getData3() { + return data3; + } + public void setData3(String data3) { + this.data3 = data3; + } + + +} + diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/PolicyContainer.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/PolicyContainer.java new file mode 100644 index 000000000..5d2453b5c --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/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.pap.xacml.rest.util; + +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/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/PolicyItemSetChangeNotifier.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/PolicyItemSetChangeNotifier.java new file mode 100644 index 000000000..5d7f7853c --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/PolicyItemSetChangeNotifier.java @@ -0,0 +1,96 @@ +/*- + * ============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.pap.xacml.rest.util; + + +import java.io.Serializable; +import java.util.Collection; +import java.util.EventObject; +import java.util.LinkedList; + +import org.onap.policy.pap.xacml.rest.util.PolicyContainer.ItemSetChangeEvent; +import org.onap.policy.pap.xacml.rest.util.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/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java new file mode 100644 index 000000000..d0bfa2f8d --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.restAuth; + +import java.util.Base64; +import java.util.StringTokenizer; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.rest.XACMLRestProperties; + +import com.att.research.xacml.util.XACMLProperties; + +public class AuthenticationService { + private String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + private String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + + public boolean authenticate(String authCredentials) { + + if (null == authCredentials) + return false; + // header value format will be "Basic encodedstring" for Basic authentication. + final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", ""); + String usernameAndPassword = null; + try { + byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword); + usernameAndPassword = new String(decodedBytes, "UTF-8"); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService", "Exception decoding username and password"); + return false; + } + try { + final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); + final String username = tokenizer.nextToken(); + final String password = tokenizer.nextToken(); + + boolean authenticationStatus = papID.equals(username) && papPass.equals(password); + return authenticationStatus; + } catch (Exception e){ + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService", "Exception authenticating user"); + return false; + } + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java new file mode 100644 index 000000000..02ec467ed --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java @@ -0,0 +1,181 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.restAuth; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +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.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.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.XACMLPapServlet; +import org.onap.policy.xacml.api.XACMLErrorConstants; + +public class CheckPDP { + + private static Path pdpPath = null; + private static Properties pdpProp = null; + private static Long oldModified = null; + private static Long newModified = null; + private static HashMap pdpMap = null; + private static final Logger logger = FlexLogger.getLogger(CheckPDP.class); + + public static boolean validateID(String id) { + // ReadFile + try { + readFile(); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception reading file"); + return false; + } + // Check ID + if (pdpMap.containsKey(id)) { + return true; + } + return false; + } + + private static void readFile() throws Exception { + String pdpFile = XACMLPapServlet.getPDPFile(); + if (pdpFile == null) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "PDP File name is undefined"); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"PDP File name not Valid : " + pdpFile); + } + if (pdpPath == null) { + pdpPath = Paths.get(pdpFile); + if (Files.notExists(pdpPath)) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path"); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"File doesn't exist in the specified Path : "+ pdpPath.toString()); + } + if (pdpPath.toString().endsWith(".properties")) { + readProps(); + } else { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "Not a .properties file"); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Not a .properties file"); + } + } + // Check if File is updated recently + else { + newModified = pdpPath.toFile().lastModified(); + if (newModified != oldModified) { + // File has been updated. + readProps(); + } + } + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private static void readProps() throws Exception { + InputStream in; + pdpProp = new Properties(); + try { + in = new FileInputStream(pdpPath.toFile()); + oldModified = pdpPath.toFile().lastModified(); + pdpProp.load(in); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Cannot load the Properties file"); + throw new Exception("Cannot Load the Properties file", e); + } + // 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) { + if (propKey.startsWith("PDP_URL")) { + String check_val = pdpProp.getProperty(propKey); + if (check_val == null) { + throw new Exception("Properties file doesn't have the PDP_URL parameter"); + } + if (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++; + } + } else { + readPDPParam(check_val); + } + } + } + if (pdpMap == null || pdpMap.isEmpty()) { + logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs"); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Proceed without PDP_URLs"); + } + } + + private static void readPDPParam(String pdpVal) throws Exception{ + 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{ + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request"); + throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request. " + pdpValues); + } + }else{ + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal); + throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS +"No enough Credentials to send Request."); + } + } + + public static String getEncoding(String pdpID){ + try { + readFile(); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exeption reading Properties file"); + } + String encoding = null; + if(pdpMap!=null && (!pdpMap.isEmpty())){ + try{ + encoding = pdpMap.get(pdpID); + } catch(Exception e){ + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception encoding"); + } + return encoding; + }else{ + return null; + } + } + +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java new file mode 100644 index 000000000..44cb7d14a --- /dev/null +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java @@ -0,0 +1,130 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.restAuth; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Servlet Filter implementation class PAPAuthenticationFilter + */ +@WebFilter("/*") +public class PAPAuthenticationFilter implements Filter { + + private static final Log logger = LogFactory.getLog(PAPAuthenticationFilter.class); + public static final String AUTHENTICATION_HEADER = "Authorization"; + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain filter) throws IOException, ServletException { + + + if (request instanceof HttpServletRequest) { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + + String authCredentials = null; + String url = httpServletRequest.getRequestURI(); + + logger.info("Request URI: " + url); + System.out.println("Request URI: " + url); + + //getting authentication credentials + if(url.contains("@Auth@")){ + int authIndex = url.lastIndexOf("@"); + int endAuthIndex = url.indexOf("/onap"); + authCredentials = "Basic " + url.substring(authIndex+1, endAuthIndex); + + //parse the url for /pap/onap/ + String url1 = url.substring(0, 4); + String url2 = url.substring(endAuthIndex, url.length()); + url = url1 + url2; + + } else { + authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER); + } + + // Check Authentication credentials + AuthenticationService authenticationService = new AuthenticationService(); + boolean authenticationStatus = authenticationService.authenticate(authCredentials); + + if (authenticationStatus) { + //indicates the request comes from Traditional Admin Console or PolicyEngineAPI + if (url.equals("/pap/")){ + logger.info("Request comes from Traditional Admin Console or PolicyEngineAPI"); + + //forward request to the XACMLPAPServlet if authenticated + request.getRequestDispatcher("/pap/pap/").forward(request, response); + + }else if (url.startsWith("/pap/onap/")){ + + //indicates the request comes from the ONAP Portal onap-sdk-app + if(response instanceof HttpServletResponse) { + HttpServletResponse alteredResponse = ((HttpServletResponse)response); + addCorsHeader(alteredResponse); + logger.info("Request comes from Onap Portal"); + //Spring dispatcher servlet is at the end of the filter chain at /pap/onap/ path + System.out.println("New Request URI: " + url); + filter.doFilter(request, response); + /*url = url.substring(url.indexOf("/pap/")+4); + request.getRequestDispatcher(url).forward(request, response);*/ + } + + } + + } else { + if (response instanceof HttpServletResponse) { + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + } + + } + } + + //method to add CorsHeaders for onap portal rest call + private void addCorsHeader(HttpServletResponse response) { + logger.info("Adding Cors Response Headers!!!"); + response.addHeader("Access-Control-Allow-Origin", "*"); + response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD"); + response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept"); + response.addHeader("Access-Control-Max-Age", "1728000"); + } + + @Override + public void destroy() { + } + + @Override + public void init(FilterConfig arg0) throws ServletException { + } +} diff --git a/ONAP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml b/ONAP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml new file mode 100644 index 000000000..19e567ddd --- /dev/null +++ b/ONAP-PAP-REST/src/main/resources/Decision_GuardBLPolicyTemplate.xml @@ -0,0 +1,111 @@ + + + ${description} + + + + + ${PolicyName} + + + + + + ${ONAPName} + + + + ${actor} + + + + ${recipe} + + + + ${clname} + + + + + + + + + + + DECIDE + + + + + + + + + + + + + ${guardActiveStart} + ${guardActiveEnd} + + + + + + + + + ${blackListElement} + + + + + + + + + + + + DECIDE + + + + + + + + + + + + + + ${guardActiveStart} + ${guardActiveEnd} + + + + + + + + + ${blackListElement} + + + + + + + + + + Denied! + + + + + \ No newline at end of file diff --git a/ONAP-PAP-REST/src/main/resources/Decision_GuardPolicyTemplate.xml b/ONAP-PAP-REST/src/main/resources/Decision_GuardPolicyTemplate.xml new file mode 100644 index 000000000..ed5b27b7d --- /dev/null +++ b/ONAP-PAP-REST/src/main/resources/Decision_GuardPolicyTemplate.xml @@ -0,0 +1,107 @@ + + + ${description} + + + + + ${PolicyName} + + + + + + ${ONAPName} + + + + ${actor} + + + + ${recipe} + + + + ${targets} + + + + ${clname} + + + + + + + + + + + DECIDE + + + + + + + + + + + + + ${guardActiveStart} + ${guardActiveEnd} + + + + + + ${limit} + + + + + + + + + + + DECIDE + + + + + + + + + + + + + + ${guardActiveStart} + ${guardActiveEnd} + + + + + + ${limit} + + + + + + + + + Denied! + + + + + \ No newline at end of file diff --git a/ECOMP-PAP-REST/src/main/resources/META-INF/drop.ddl b/ONAP-PAP-REST/src/main/resources/META-INF/drop.ddl similarity index 100% rename from ECOMP-PAP-REST/src/main/resources/META-INF/drop.ddl rename to ONAP-PAP-REST/src/main/resources/META-INF/drop.ddl diff --git a/ONAP-PAP-REST/src/main/resources/META-INF/generatedCreate.ddl b/ONAP-PAP-REST/src/main/resources/META-INF/generatedCreate.ddl new file mode 100644 index 000000000..c12949aed --- /dev/null +++ b/ONAP-PAP-REST/src/main/resources/META-INF/generatedCreate.ddl @@ -0,0 +1,119 @@ +CREATE TABLE PolicyEntity (policyId BIGINT NOT NULL, created_by VARCHAR(255) NOT NULL, created_date TIMESTAMP, deleted BOOLEAN NOT NULL, description VARCHAR(2048) NOT NULL, modified_by VARCHAR(255) NOT NULL, modified_date TIMESTAMP NOT NULL, policyData TEXT, policyName VARCHAR(255) NOT NULL, policyVersion INTEGER, scope VARCHAR(255) NOT NULL, version INTEGER, actionBodyId BIGINT, configurationDataId BIGINT, PRIMARY KEY (policyId)) +CREATE TABLE ConfigurationDataEntity (configurationDataId BIGINT NOT NULL, configBody TEXT, configType VARCHAR(255) NOT NULL, configurationName VARCHAR(255) NOT NULL, created_by VARCHAR(255) NOT NULL, created_date TIMESTAMP, deleted BOOLEAN NOT NULL, description VARCHAR(2048) NOT NULL, modified_by VARCHAR(255) NOT NULL, modified_date TIMESTAMP NOT NULL, version INTEGER, PRIMARY KEY (configurationDataId)) +CREATE TABLE PolicyDBDaoEntity (policyDBDaoUrl VARCHAR NOT NULL, created_date TIMESTAMP, description VARCHAR(2048) NOT NULL, modified_date TIMESTAMP NOT NULL, password VARCHAR, username VARCHAR, PRIMARY KEY (policyDBDaoUrl)) +CREATE TABLE GroupEntity (groupKey BIGINT NOT NULL, created_by VARCHAR(255) NOT NULL, created_date TIMESTAMP, defaultGroup BOOLEAN NOT NULL, deleted BOOLEAN NOT NULL, description VARCHAR(2048) NOT NULL, groupId VARCHAR NOT NULL, groupName VARCHAR(255) NOT NULL, modified_by VARCHAR(255) NOT NULL, modified_date TIMESTAMP NOT NULL, version INTEGER, PRIMARY KEY (groupKey)) +CREATE TABLE PdpEntity (pdpKey BIGINT NOT NULL, created_by VARCHAR(255) NOT NULL, created_date TIMESTAMP, deleted BOOLEAN NOT NULL, description VARCHAR(2048) NOT NULL, jmxPort INTEGER NOT NULL, modified_by VARCHAR(255) NOT NULL, modified_date TIMESTAMP NOT NULL, pdpId VARCHAR(255) NOT NULL, pdpName VARCHAR(255) NOT NULL, groupKey BIGINT, PRIMARY KEY (pdpKey)) +CREATE TABLE ActionBodyEntity (actionBodyId BIGINT NOT NULL, actionBody TEXT, actionBodyName VARCHAR(255) NOT NULL, created_by VARCHAR(255) NOT NULL, created_date TIMESTAMP, deleted BOOLEAN NOT NULL, modified_by VARCHAR(255) NOT NULL, modified_date TIMESTAMP NOT NULL, version INTEGER, PRIMARY KEY (actionBodyId)) +CREATE TABLE DatabaseLockEntity (lock_key INTEGER NOT NULL, PRIMARY KEY (lock_key)) +CREATE TABLE PolicyVersion (id INTEGER NOT NULL, ACTIVE_VERSION INTEGER, CREATED_BY VARCHAR(45) NOT NULL, created_date TIMESTAMP NOT NULL, HIGHEST_VERSION INTEGER, modified_by VARCHAR(45) NOT NULL, modified_date TIMESTAMP NOT NULL, POLICY_NAME VARCHAR(255) NOT NULL, PRIMARY KEY (id)) +CREATE TABLE POLICYSCORE (id INTEGER NOT NULL, POLICY_NAME VARCHAR NOT NULL, POLICY_SCORE VARCHAR, VERSIONEXTENSION VARCHAR NOT NULL, PRIMARY KEY (id)) +CREATE TABLE FunctionDefinition (id INTEGER NOT NULL, arg_lb INTEGER NOT NULL, arg_ub INTEGER NOT NULL, ho_arg_lb INTEGER, ho_arg_ub INTEGER, ho_primitive CHAR, is_bag_return INTEGER NOT NULL, is_higher_order INTEGER NOT NULL, short_name VARCHAR(64) NOT NULL, xacml_id VARCHAR(255) NOT NULL, return_datatype INTEGER, PRIMARY KEY (id)) +CREATE TABLE Attribute (id INTEGER NOT NULL, ATTRIBUTE_VALUE VARCHAR, created_date TIMESTAMP, description VARCHAR(2048), is_designator CHAR NOT NULL, modified_date TIMESTAMP NOT NULL, PRIORITY VARCHAR, selector_path VARCHAR(2048), xacml_id VARCHAR NOT NULL UNIQUE, category INTEGER, constraint_type INTEGER, datatype INTEGER, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) +CREATE TABLE Category (id INTEGER NOT NULL, grouping VARCHAR(64) NOT NULL, is_standard CHAR NOT NULL, short_name VARCHAR(64) NOT NULL, xacml_id VARCHAR(255) NOT NULL UNIQUE, PRIMARY KEY (id)) +CREATE TABLE ConstraintType (id INTEGER NOT NULL, constraint_type VARCHAR(64) NOT NULL, description VARCHAR(255) NOT NULL, PRIMARY KEY (id)) +CREATE TABLE ConstraintValues (id INTEGER NOT NULL, property VARCHAR, value VARCHAR, attribute_id INTEGER, PRIMARY KEY (id)) +CREATE TABLE Datatype (id INTEGER NOT NULL, is_standard CHAR NOT NULL, short_name VARCHAR(64) NOT NULL, xacml_id VARCHAR(255) NOT NULL UNIQUE, PRIMARY KEY (id)) +CREATE TABLE FunctionArguments (id INTEGER NOT NULL, arg_index INTEGER NOT NULL, is_bag INTEGER NOT NULL, datatype_id INTEGER, function_id INTEGER, PRIMARY KEY (id)) +CREATE TABLE UserInfo (loginid VARCHAR(45) NOT NULL, name VARCHAR NOT NULL UNIQUE, PRIMARY KEY (loginid)) +CREATE TABLE ActionPolicyDict (id INTEGER NOT NULL, ATTRIBUTE_NAME VARCHAR NOT NULL, Body VARCHAR, created_date TIMESTAMP, description VARCHAR(2048), Headers VARCHAR, Method VARCHAR NOT NULL, modified_date TIMESTAMP NOT NULL, Type VARCHAR NOT NULL, URL VARCHAR NOT NULL, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) +CREATE TABLE DecisionSettings (id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), modified_date TIMESTAMP NOT NULL, PRIORITY VARCHAR, xacml_id VARCHAR NOT NULL UNIQUE, datatype INTEGER, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) +CREATE TABLE MicroServiceModels (id INTEGER NOT NULL, annotation VARCHAR(2000) NOT NULL, attributes VARCHAR(255) NOT NULL, dependency VARCHAR(2048), description VARCHAR(2048), enumValues VARCHAR(2000) NOT NULL, modelName VARCHAR NOT NULL UNIQUE, ref_attributes VARCHAR(255) NOT NULL, sub_attributes VARCHAR(2000) NOT NULL, version VARCHAR(2000) NOT NULL, imported_by VARCHAR(45), PRIMARY KEY (id)) +CREATE TABLE actionlist (id INTEGER NOT NULL, actionname VARCHAR NOT NULL, description VARCHAR, PRIMARY KEY (id)) +CREATE TABLE AddressGroup (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, prefixlist VARCHAR, PRIMARY KEY (id)) +CREATE TABLE AttributeAssignment (id INTEGER NOT NULL, attribute_id INTEGER, expression VARCHAR NOT NULL, OBADVICE_id INTEGER, PRIMARY KEY (id)) +CREATE TABLE BRMSParamTemplate (id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), rule LONGVARCHAR NOT NULL, param_template_name VARCHAR NOT NULL UNIQUE, created_by VARCHAR(45), PRIMARY KEY (id)) +CREATE TABLE ClosedLoopD2Services (id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), modified_date TIMESTAMP NOT NULL, service_Name VARCHAR NOT NULL UNIQUE, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) +CREATE TABLE ClosedLoopSite (id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), modified_date TIMESTAMP NOT NULL, site_Name VARCHAR NOT NULL UNIQUE, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) +CREATE TABLE DCAEUsers (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) +CREATE TABLE DCAEuuid (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) +CREATE TABLE DescriptiveScope (Id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), scopename VARCHAR NOT NULL, modified_date TIMESTAMP NOT NULL, search VARCHAR, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (Id)) +CREATE TABLE OnapName (id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), modified_date TIMESTAMP NOT NULL, onap_Name VARCHAR NOT NULL UNIQUE, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) +CREATE TABLE EnforcingType (id INTEGER NOT NULL, connectionQuery VARCHAR(255) NOT NULL, enforcingType VARCHAR NOT NULL UNIQUE, script VARCHAR(255) NOT NULL, valueQuery VARCHAR(255) NOT NULL, PRIMARY KEY (id)) +CREATE TABLE GlobalRoleSettings (role VARCHAR(45) NOT NULL, lockdown BOOLEAN, PRIMARY KEY (role)) +CREATE TABLE GroupPolicyScopeList (id INTEGER NOT NULL, description VARCHAR, groupList VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) +CREATE TABLE GroupServiceList (id INTEGER NOT NULL, name VARCHAR NOT NULL, serviceList VARCHAR, PRIMARY KEY (id)) +CREATE TABLE MicroServiceConfigName (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) +CREATE TABLE MicroServiceLocation (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) +CREATE TABLE Obadvice (id INTEGER NOT NULL, created_by VARCHAR(255) NOT NULL, created_date TIMESTAMP NOT NULL, description VARCHAR(2048), fulfill_on VARCHAR(32), modified_by VARCHAR(255) NOT NULL, modified_date TIMESTAMP NOT NULL, type VARCHAR NOT NULL, xacml_id VARCHAR(255) NOT NULL, PRIMARY KEY (id)) +CREATE TABLE ObadviceExpressions (id INTEGER NOT NULL, type VARCHAR NOT NULL, obadvice_id INTEGER, attribute_id INTEGER, PRIMARY KEY (id)) +CREATE TABLE PEPOptions (Id INTEGER NOT NULL, Actions VARCHAR, created_date TIMESTAMP, description VARCHAR(2048), modified_date TIMESTAMP NOT NULL, PEP_NAME VARCHAR NOT NULL, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (Id)) +CREATE TABLE PIPConfigParams (id INTEGER NOT NULL, PARAM_DEFAULT VARCHAR(2048), PARAM_NAME VARCHAR(1024) NOT NULL, PARAM_VALUE VARCHAR(2048) NOT NULL, REQUIRED CHAR NOT NULL, PIP_ID INTEGER, PRIMARY KEY (id)) +CREATE TABLE PIPConfiguration (id INTEGER NOT NULL, CLASSNAME VARCHAR(2048) NOT NULL, CREATED_BY VARCHAR(255) NOT NULL, CREATED_DATE TIMESTAMP NOT NULL, DESCRIPTION VARCHAR(2048), ISSUER VARCHAR(1024), MODIFIED_BY VARCHAR(255) NOT NULL, MODIFIED_DATE TIMESTAMP NOT NULL, NAME VARCHAR(255) NOT NULL, READ_ONLY CHAR NOT NULL, REQUIRES_RESOLVER CHAR NOT NULL, TYPE INTEGER, PRIMARY KEY (id)) +CREATE TABLE PIPResolver (id INTEGER NOT NULL, CLASSNAME VARCHAR(2048) NOT NULL, CREATED_BY VARCHAR(255) NOT NULL, CREATED_DATE TIMESTAMP NOT NULL, DESCRIPTION VARCHAR(2048), ISSUER VARCHAR(1024), MODIFIED_BY VARCHAR(255) NOT NULL, MODIFIED_DATE TIMESTAMP NOT NULL, NAME VARCHAR(255) NOT NULL, READ_ONLY CHAR NOT NULL, PIP_ID INTEGER, PRIMARY KEY (id)) +CREATE TABLE PIPResolverParams (id INTEGER NOT NULL, PARAM_DEFAULT VARCHAR(2048), PARAM_NAME VARCHAR(1024) NOT NULL, PARAM_VALUE VARCHAR(2048) NOT NULL, REQUIRED CHAR NOT NULL, ID_RESOLVER INTEGER, PRIMARY KEY (id)) +CREATE TABLE PIPType (id INTEGER NOT NULL, type VARCHAR(45) NOT NULL, PRIMARY KEY (id)) +CREATE TABLE PolicyAlgorithms (id INTEGER NOT NULL, is_standard CHAR NOT NULL, short_name VARCHAR(64) NOT NULL, xacml_id VARCHAR(255) NOT NULL UNIQUE, PRIMARY KEY (id)) +CREATE TABLE policy_manangement (id INTEGER NOT NULL, CONFIG_NAME VARCHAR(45) NOT NULL, CREATE_DATE_TIME TIMESTAMP NOT NULL, CREATED_BY VARCHAR(45) NOT NULL, ONAP_NAME VARCHAR(45) NOT NULL, POLICY_NAME VARCHAR(45) NOT NULL, scope VARCHAR(45) NOT NULL, UPDATE_DATE_TIME TIMESTAMP NOT NULL, UPDATED_BY VARCHAR(45) NOT NULL, XML CLOB NOT NULL, PRIMARY KEY (id)) +CREATE TABLE PolicyScopeService (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) +CREATE TABLE PolicyScopeType (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) +CREATE TABLE PolicyScopeResource (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) +CREATE TABLE PolicyScopeClosedLoop (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) +CREATE TABLE portlist (id INTEGER NOT NULL, description VARCHAR, portname VARCHAR NOT NULL, PRIMARY KEY (id)) +CREATE TABLE protocollist (id INTEGER NOT NULL, description VARCHAR, protocolname VARCHAR NOT NULL, PRIMARY KEY (id)) +CREATE TABLE RemoteCatalogValues (id INTEGER NOT NULL, name VARCHAR NOT NULL, value VARCHAR, PRIMARY KEY (id)) +CREATE TABLE roles (id INTEGER NOT NULL, role VARCHAR(45) NOT NULL, scope VARCHAR(45), loginid VARCHAR(45), PRIMARY KEY (id)) +CREATE TABLE RuleAlgorithms (id INTEGER NOT NULL, is_standard CHAR NOT NULL, short_name VARCHAR(64) NOT NULL, xacml_id VARCHAR(255) NOT NULL UNIQUE, PRIMARY KEY (id)) +CREATE TABLE securityzone (id INTEGER NOT NULL, name VARCHAR NOT NULL, value VARCHAR, PRIMARY KEY (id)) +CREATE TABLE servicegroup (id INTEGER NOT NULL, appprotocol VARCHAR, description VARCHAR, name VARCHAR NOT NULL, ports VARCHAR, transportprotocol VARCHAR, type VARCHAR, PRIMARY KEY (id)) +CREATE TABLE SystemLogDB (id INTEGER NOT NULL, date TIMESTAMP NOT NULL, description VARCHAR(2048), logtype VARCHAR(255) NOT NULL, remote VARCHAR(255) NOT NULL, system VARCHAR(255) NOT NULL, type VARCHAR NOT NULL, PRIMARY KEY (id)) +CREATE TABLE TERM (id INTEGER NOT NULL, action VARCHAR, created_date TIMESTAMP, destIPList VARCHAR, destPortList VARCHAR, fromzone VARCHAR, modified_date TIMESTAMP NOT NULL, portList VARCHAR, protocolList VARCHAR, srcIPList VARCHAR, srcPortList VARCHAR, description VARCHAR, termName VARCHAR NOT NULL, tozone VARCHAR, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) +CREATE TABLE VarbindDictionary (Id INTEGER NOT NULL, created_date TIMESTAMP, modified_date TIMESTAMP NOT NULL, varbind_Description VARCHAR(2048), varbind_Name VARCHAR NOT NULL UNIQUE, varbind_oid VARCHAR NOT NULL, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (Id)) +CREATE TABLE VMType (id INTEGER NOT NULL, description VARCHAR, name VARCHAR NOT NULL, PRIMARY KEY (id)) +CREATE TABLE VNFType (id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), modified_date TIMESTAMP NOT NULL, vnf_type VARCHAR NOT NULL UNIQUE, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) +CREATE TABLE VSCLAction (id INTEGER NOT NULL, created_date TIMESTAMP, description VARCHAR(2048), modified_date TIMESTAMP NOT NULL, vscl_action VARCHAR NOT NULL UNIQUE, created_by VARCHAR(45), modified_by VARCHAR(45), PRIMARY KEY (id)) +CREATE TABLE zone (id INTEGER NOT NULL, zonename VARCHAR NOT NULL, zonevalue VARCHAR, PRIMARY KEY (id)) +CREATE TABLE BackUpMonitorEntity (id INTEGER NOT NULL, flag VARCHAR NOT NULL, notification_record LONGVARCHAR, resource_name VARCHAR NOT NULL UNIQUE, node_name VARCHAR NOT NULL, last_seen TIMESTAMP, PRIMARY KEY (id)) +CREATE TABLE StateManagementEntity (id BIGINT NOT NULL, adminState VARCHAR(20) NOT NULL, availStatus VARCHAR(20) NOT NULL, created_Date TIMESTAMP, modifiedDate TIMESTAMP NOT NULL, opState VARCHAR(20) NOT NULL, resourceName VARCHAR(100) NOT NULL UNIQUE, standbyStatus VARCHAR(20) NOT NULL, PRIMARY KEY (id)) +CREATE TABLE ForwardProgressEntity (forwardProgressId BIGINT NOT NULL, created_date TIMESTAMP, fpc_count BIGINT NOT NULL, last_updated TIMESTAMP, resourceName VARCHAR(100) NOT NULL UNIQUE, PRIMARY KEY (forwardProgressId)) +CREATE TABLE ResourceRegistrationEntity (ResourceRegistrationId BIGINT NOT NULL, created_date TIMESTAMP, last_updated TIMESTAMP, nodeType VARCHAR(50), resourceName VARCHAR(100) NOT NULL UNIQUE, resourceUrl VARCHAR(255) NOT NULL UNIQUE, site VARCHAR(50), PRIMARY KEY (ResourceRegistrationId)) +CREATE TABLE IntegrityAuditEntity (id BIGINT NOT NULL, createdDate TIMESTAMP, designated BOOLEAN, jdbcDriver VARCHAR NOT NULL, jdbcPassword VARCHAR NOT NULL, jdbcUrl VARCHAR NOT NULL, jdbcUser VARCHAR NOT NULL, lastUpdated TIMESTAMP, nodeType VARCHAR, persistenceUnit VARCHAR NOT NULL, resourceName VARCHAR NOT NULL UNIQUE, site VARCHAR, PRIMARY KEY (id)) +CREATE TABLE PolicyGroupEntity (groupKey BIGINT NOT NULL, policyId BIGINT NOT NULL, PRIMARY KEY (groupKey, policyId)) +ALTER TABLE PolicyEntity ADD CONSTRAINT FK_PolicyEntity_configurationDataId FOREIGN KEY (configurationDataId) REFERENCES ConfigurationDataEntity (configurationDataId) +ALTER TABLE PolicyEntity ADD CONSTRAINT FK_PolicyEntity_actionBodyId FOREIGN KEY (actionBodyId) REFERENCES ActionBodyEntity (actionBodyId) +ALTER TABLE PdpEntity ADD CONSTRAINT FK_PdpEntity_groupKey FOREIGN KEY (groupKey) REFERENCES GroupEntity (groupKey) +ALTER TABLE FunctionDefinition ADD CONSTRAINT FK_FunctionDefinition_return_datatype FOREIGN KEY (return_datatype) REFERENCES Datatype (id) +ALTER TABLE Attribute ADD CONSTRAINT FK_Attribute_category FOREIGN KEY (category) REFERENCES Category (id) +ALTER TABLE Attribute ADD CONSTRAINT FK_Attribute_constraint_type FOREIGN KEY (constraint_type) REFERENCES ConstraintType (id) +ALTER TABLE Attribute ADD CONSTRAINT FK_Attribute_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) +ALTER TABLE Attribute ADD CONSTRAINT FK_Attribute_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) +ALTER TABLE Attribute ADD CONSTRAINT FK_Attribute_datatype FOREIGN KEY (datatype) REFERENCES Datatype (id) +ALTER TABLE ConstraintValues ADD CONSTRAINT FK_ConstraintValues_attribute_id FOREIGN KEY (attribute_id) REFERENCES Attribute (id) +ALTER TABLE FunctionArguments ADD CONSTRAINT FK_FunctionArguments_function_id FOREIGN KEY (function_id) REFERENCES FunctionDefinition (id) +ALTER TABLE FunctionArguments ADD CONSTRAINT FK_FunctionArguments_datatype_id FOREIGN KEY (datatype_id) REFERENCES Datatype (id) +ALTER TABLE ActionPolicyDict ADD CONSTRAINT FK_ActionPolicyDict_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) +ALTER TABLE ActionPolicyDict ADD CONSTRAINT FK_ActionPolicyDict_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) +ALTER TABLE DecisionSettings ADD CONSTRAINT FK_DecisionSettings_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) +ALTER TABLE DecisionSettings ADD CONSTRAINT FK_DecisionSettings_datatype FOREIGN KEY (datatype) REFERENCES Datatype (id) +ALTER TABLE DecisionSettings ADD CONSTRAINT FK_DecisionSettings_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) +ALTER TABLE MicroServiceModels ADD CONSTRAINT FK_MicroServiceModels_imported_by FOREIGN KEY (imported_by) REFERENCES UserInfo (loginid) +ALTER TABLE AttributeAssignment ADD CONSTRAINT FK_AttributeAssignment_OBADVICE_id FOREIGN KEY (OBADVICE_id) REFERENCES Obadvice (id) +ALTER TABLE BRMSParamTemplate ADD CONSTRAINT FK_BRMSParamTemplate_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) +ALTER TABLE ClosedLoopD2Services ADD CONSTRAINT FK_ClosedLoopD2Services_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) +ALTER TABLE ClosedLoopD2Services ADD CONSTRAINT FK_ClosedLoopD2Services_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) +ALTER TABLE ClosedLoopSite ADD CONSTRAINT FK_ClosedLoopSite_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) +ALTER TABLE ClosedLoopSite ADD CONSTRAINT FK_ClosedLoopSite_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) +ALTER TABLE DescriptiveScope ADD CONSTRAINT FK_DescriptiveScope_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) +ALTER TABLE DescriptiveScope ADD CONSTRAINT FK_DescriptiveScope_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) +ALTER TABLE OnapName ADD CONSTRAINT FK_OnapName_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) +ALTER TABLE OnapName ADD CONSTRAINT FK_OnapName_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) +ALTER TABLE ObadviceExpressions ADD CONSTRAINT FK_ObadviceExpressions_obadvice_id FOREIGN KEY (obadvice_id) REFERENCES Obadvice (id) +ALTER TABLE ObadviceExpressions ADD CONSTRAINT FK_ObadviceExpressions_attribute_id FOREIGN KEY (attribute_id) REFERENCES Attribute (id) +ALTER TABLE PEPOptions ADD CONSTRAINT FK_PEPOptions_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) +ALTER TABLE PEPOptions ADD CONSTRAINT FK_PEPOptions_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) +ALTER TABLE PIPConfigParams ADD CONSTRAINT FK_PIPConfigParams_PIP_ID FOREIGN KEY (PIP_ID) REFERENCES PIPConfiguration (id) +ALTER TABLE PIPConfiguration ADD CONSTRAINT FK_PIPConfiguration_TYPE FOREIGN KEY (TYPE) REFERENCES PIPType (id) +ALTER TABLE PIPResolver ADD CONSTRAINT FK_PIPResolver_PIP_ID FOREIGN KEY (PIP_ID) REFERENCES PIPConfiguration (id) +ALTER TABLE PIPResolverParams ADD CONSTRAINT FK_PIPResolverParams_ID_RESOLVER FOREIGN KEY (ID_RESOLVER) REFERENCES PIPResolver (id) +ALTER TABLE roles ADD CONSTRAINT FK_roles_loginid FOREIGN KEY (loginid) REFERENCES UserInfo (loginid) +ALTER TABLE TERM ADD CONSTRAINT FK_TERM_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) +ALTER TABLE TERM ADD CONSTRAINT FK_TERM_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) +ALTER TABLE VarbindDictionary ADD CONSTRAINT FK_VarbindDictionary_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) +ALTER TABLE VarbindDictionary ADD CONSTRAINT FK_VarbindDictionary_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) +ALTER TABLE VNFType ADD CONSTRAINT FK_VNFType_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) +ALTER TABLE VNFType ADD CONSTRAINT FK_VNFType_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) +ALTER TABLE VSCLAction ADD CONSTRAINT FK_VSCLAction_modified_by FOREIGN KEY (modified_by) REFERENCES UserInfo (loginid) +ALTER TABLE VSCLAction ADD CONSTRAINT FK_VSCLAction_created_by FOREIGN KEY (created_by) REFERENCES UserInfo (loginid) +ALTER TABLE PolicyGroupEntity ADD CONSTRAINT FK_PolicyGroupEntity_policyId FOREIGN KEY (policyId) REFERENCES PolicyEntity (policyId) +ALTER TABLE PolicyGroupEntity ADD CONSTRAINT FK_PolicyGroupEntity_groupKey FOREIGN KEY (groupKey) REFERENCES GroupEntity (groupKey) +CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT NUMERIC(38), PRIMARY KEY (SEQ_NAME)) +INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0) diff --git a/ONAP-PAP-REST/src/main/resources/META-INF/generatedDrop.ddl b/ONAP-PAP-REST/src/main/resources/META-INF/generatedDrop.ddl new file mode 100644 index 000000000..ce1769a4d --- /dev/null +++ b/ONAP-PAP-REST/src/main/resources/META-INF/generatedDrop.ddl @@ -0,0 +1,118 @@ +ALTER TABLE PolicyEntity DROP CONSTRAINT FK_PolicyEntity_configurationDataId +ALTER TABLE PolicyEntity DROP CONSTRAINT FK_PolicyEntity_actionBodyId +ALTER TABLE PdpEntity DROP CONSTRAINT FK_PdpEntity_groupKey +ALTER TABLE FunctionDefinition DROP CONSTRAINT FK_FunctionDefinition_return_datatype +ALTER TABLE Attribute DROP CONSTRAINT FK_Attribute_category +ALTER TABLE Attribute DROP CONSTRAINT FK_Attribute_constraint_type +ALTER TABLE Attribute DROP CONSTRAINT FK_Attribute_created_by +ALTER TABLE Attribute DROP CONSTRAINT FK_Attribute_modified_by +ALTER TABLE Attribute DROP CONSTRAINT FK_Attribute_datatype +ALTER TABLE ConstraintValues DROP CONSTRAINT FK_ConstraintValues_attribute_id +ALTER TABLE FunctionArguments DROP CONSTRAINT FK_FunctionArguments_function_id +ALTER TABLE FunctionArguments DROP CONSTRAINT FK_FunctionArguments_datatype_id +ALTER TABLE ActionPolicyDict DROP CONSTRAINT FK_ActionPolicyDict_modified_by +ALTER TABLE ActionPolicyDict DROP CONSTRAINT FK_ActionPolicyDict_created_by +ALTER TABLE DecisionSettings DROP CONSTRAINT FK_DecisionSettings_created_by +ALTER TABLE DecisionSettings DROP CONSTRAINT FK_DecisionSettings_datatype +ALTER TABLE DecisionSettings DROP CONSTRAINT FK_DecisionSettings_modified_by +ALTER TABLE MicroServiceModels DROP CONSTRAINT FK_MicroServiceModels_imported_by +ALTER TABLE AttributeAssignment DROP CONSTRAINT FK_AttributeAssignment_OBADVICE_id +ALTER TABLE BRMSParamTemplate DROP CONSTRAINT FK_BRMSParamTemplate_created_by +ALTER TABLE ClosedLoopD2Services DROP CONSTRAINT FK_ClosedLoopD2Services_modified_by +ALTER TABLE ClosedLoopD2Services DROP CONSTRAINT FK_ClosedLoopD2Services_created_by +ALTER TABLE ClosedLoopSite DROP CONSTRAINT FK_ClosedLoopSite_modified_by +ALTER TABLE ClosedLoopSite DROP CONSTRAINT FK_ClosedLoopSite_created_by +ALTER TABLE DescriptiveScope DROP CONSTRAINT FK_DescriptiveScope_created_by +ALTER TABLE DescriptiveScope DROP CONSTRAINT FK_DescriptiveScope_modified_by +ALTER TABLE OnapName DROP CONSTRAINT FK_OnapName_modified_by +ALTER TABLE OnapName DROP CONSTRAINT FK_OnapName_created_by +ALTER TABLE ObadviceExpressions DROP CONSTRAINT FK_ObadviceExpressions_obadvice_id +ALTER TABLE ObadviceExpressions DROP CONSTRAINT FK_ObadviceExpressions_attribute_id +ALTER TABLE PEPOptions DROP CONSTRAINT FK_PEPOptions_modified_by +ALTER TABLE PEPOptions DROP CONSTRAINT FK_PEPOptions_created_by +ALTER TABLE PIPConfigParams DROP CONSTRAINT FK_PIPConfigParams_PIP_ID +ALTER TABLE PIPConfiguration DROP CONSTRAINT FK_PIPConfiguration_TYPE +ALTER TABLE PIPResolver DROP CONSTRAINT FK_PIPResolver_PIP_ID +ALTER TABLE PIPResolverParams DROP CONSTRAINT FK_PIPResolverParams_ID_RESOLVER +ALTER TABLE roles DROP CONSTRAINT FK_roles_loginid +ALTER TABLE TERM DROP CONSTRAINT FK_TERM_modified_by +ALTER TABLE TERM DROP CONSTRAINT FK_TERM_created_by +ALTER TABLE VarbindDictionary DROP CONSTRAINT FK_VarbindDictionary_modified_by +ALTER TABLE VarbindDictionary DROP CONSTRAINT FK_VarbindDictionary_created_by +ALTER TABLE VNFType DROP CONSTRAINT FK_VNFType_modified_by +ALTER TABLE VNFType DROP CONSTRAINT FK_VNFType_created_by +ALTER TABLE VSCLAction DROP CONSTRAINT FK_VSCLAction_modified_by +ALTER TABLE VSCLAction DROP CONSTRAINT FK_VSCLAction_created_by +ALTER TABLE PolicyGroupEntity DROP CONSTRAINT FK_PolicyGroupEntity_policyId +ALTER TABLE PolicyGroupEntity DROP CONSTRAINT FK_PolicyGroupEntity_groupKey +DROP TABLE PolicyEntity +DROP TABLE ConfigurationDataEntity +DROP TABLE PolicyDBDaoEntity +DROP TABLE GroupEntity +DROP TABLE PdpEntity +DROP TABLE ActionBodyEntity +DROP TABLE DatabaseLockEntity +DROP TABLE PolicyVersion +DROP TABLE POLICYSCORE +DROP TABLE FunctionDefinition +DROP TABLE Attribute +DROP TABLE Category +DROP TABLE ConstraintType +DROP TABLE ConstraintValues +DROP TABLE Datatype +DROP TABLE FunctionArguments +DROP TABLE UserInfo +DROP TABLE ActionPolicyDict +DROP TABLE DecisionSettings +DROP TABLE MicroServiceModels +DROP TABLE actionlist +DROP TABLE AddressGroup +DROP TABLE AttributeAssignment +DROP TABLE BRMSParamTemplate +DROP TABLE ClosedLoopD2Services +DROP TABLE ClosedLoopSite +DROP TABLE DCAEUsers +DROP TABLE DCAEuuid +DROP TABLE DescriptiveScope +DROP TABLE OnapName +DROP TABLE EnforcingType +DROP TABLE GlobalRoleSettings +DROP TABLE GroupPolicyScopeList +DROP TABLE GroupServiceList +DROP TABLE MicroServiceConfigName +DROP TABLE MicroServiceLocation +DROP TABLE Obadvice +DROP TABLE ObadviceExpressions +DROP TABLE PEPOptions +DROP TABLE PIPConfigParams +DROP TABLE PIPConfiguration +DROP TABLE PIPResolver +DROP TABLE PIPResolverParams +DROP TABLE PIPType +DROP TABLE PolicyAlgorithms +DROP TABLE policy_manangement +DROP TABLE PolicyScopeService +DROP TABLE PolicyScopeType +DROP TABLE PolicyScopeResource +DROP TABLE PolicyScopeClosedLoop +DROP TABLE portlist +DROP TABLE protocollist +DROP TABLE RemoteCatalogValues +DROP TABLE roles +DROP TABLE RuleAlgorithms +DROP TABLE securityzone +DROP TABLE servicegroup +DROP TABLE SystemLogDB +DROP TABLE TERM +DROP TABLE VarbindDictionary +DROP TABLE VMType +DROP TABLE VNFType +DROP TABLE VSCLAction +DROP TABLE zone +DROP TABLE BackUpMonitorEntity +DROP TABLE StateManagementEntity +DROP TABLE ForwardProgressEntity +DROP TABLE ResourceRegistrationEntity +DROP TABLE IntegrityAuditEntity +DROP TABLE PolicyGroupEntity +DELETE FROM SEQUENCE WHERE SEQ_NAME = 'SEQ_GEN' diff --git a/ONAP-PAP-REST/src/main/resources/META-INF/persistence.xml b/ONAP-PAP-REST/src/main/resources/META-INF/persistence.xml new file mode 100644 index 000000000..b0a76c40a --- /dev/null +++ b/ONAP-PAP-REST/src/main/resources/META-INF/persistence.xml @@ -0,0 +1,201 @@ + + + + + org.onap.policy.rest.jpa.PolicyEntity + org.onap.policy.rest.jpa.ConfigurationDataEntity + org.onap.policy.rest.jpa.PolicyDBDaoEntity + org.onap.policy.rest.jpa.GroupEntity + org.onap.policy.rest.jpa.PdpEntity + org.onap.policy.rest.jpa.ActionBodyEntity + org.onap.policy.rest.jpa.DatabaseLockEntity + org.onap.policy.rest.jpa.PolicyVersion + org.onap.policy.rest.jpa.PolicyScore + org.onap.policy.rest.jpa.FunctionDefinition + org.onap.policy.rest.jpa.Attribute + org.onap.policy.rest.jpa.Category + org.onap.policy.rest.jpa.ConstraintType + org.onap.policy.rest.jpa.ConstraintValue + org.onap.policy.rest.jpa.Datatype + org.onap.policy.rest.jpa.FunctionArgument + org.onap.policy.rest.jpa.UserInfo + org.onap.policy.rest.jpa.ActionPolicyDict + org.onap.policy.rest.jpa.DecisionSettings + org.onap.policy.rest.jpa.MicroServiceModels + org.onap.policy.rest.jpa.BRMSParamTemplate + org.onap.policy.rest.jpa.PolicyEditorScopes + + org.onap.policy.jpa.BackUpMonitorEntity + + org.onap.policy.common.im.jpa.StateManagementEntity + org.onap.policy.common.im.jpa.ForwardProgressEntity + org.onap.policy.common.im.jpa.ResourceRegistrationEntity + + org.onap.policy.common.ia.jpa.IntegrityAuditEntity + false + NONE + + + + + + + + + + + + + + + org.onap.policy.jpa.BackUpMonitorEntity + + org.onap.policy.common.im.jpa.StateManagementEntity + org.onap.policy.common.im.jpa.ForwardProgressEntity + org.onap.policy.common.im.jpa.ResourceRegistrationEntity + + org.onap.policy.common.ia.jpa.IntegrityAuditEntity + true + NONE + + + + + + org.eclipse.persistence.jpa.PersistenceProvider + org.onap.policy.rest.jpa.PolicyEntity + org.onap.policy.rest.jpa.ConfigurationDataEntity + org.onap.policy.rest.jpa.PolicyDBDaoEntity + org.onap.policy.rest.jpa.GroupEntity + org.onap.policy.rest.jpa.PdpEntity + org.onap.policy.rest.jpa.ActionBodyEntity + org.onap.policy.rest.jpa.DatabaseLockEntity + org.onap.policy.rest.jpa.PolicyVersion + org.onap.policy.rest.jpa.PolicyScore + org.onap.policy.rest.jpa.FunctionDefinition + org.onap.policy.rest.jpa.Attribute + org.onap.policy.rest.jpa.Category + org.onap.policy.rest.jpa.ConstraintType + org.onap.policy.rest.jpa.ConstraintValue + org.onap.policy.rest.jpa.Datatype + org.onap.policy.rest.jpa.FunctionArgument + org.onap.policy.rest.jpa.UserInfo + org.onap.policy.rest.jpa.ActionPolicyDict + org.onap.policy.rest.jpa.DecisionSettings + org.onap.policy.rest.jpa.MicroServiceModels + + org.onap.policy.rest.jpa.ActionList + org.onap.policy.rest.jpa.AddressGroup + org.onap.policy.rest.jpa.AttributeAssignment + org.onap.policy.rest.jpa.BRMSParamTemplate + org.onap.policy.rest.jpa.ClosedLoopD2Services + org.onap.policy.rest.jpa.ClosedLoopSite + org.onap.policy.rest.jpa.DCAEUsers + org.onap.policy.rest.jpa.DCAEuuid + org.onap.policy.rest.jpa.DescriptiveScope + org.onap.policy.rest.jpa.OnapName + org.onap.policy.rest.jpa.EnforcingType + org.onap.policy.rest.jpa.GlobalRoleSettings + org.onap.policy.rest.jpa.GroupPolicyScopeList + org.onap.policy.rest.jpa.GroupServiceList + org.onap.policy.rest.jpa.MicroServiceConfigName + org.onap.policy.rest.jpa.MicroServiceLocation + org.onap.policy.rest.jpa.Obadvice + org.onap.policy.rest.jpa.ObadviceExpression + org.onap.policy.rest.jpa.PEPOptions + org.onap.policy.rest.jpa.PIPConfigParam + org.onap.policy.rest.jpa.PIPConfiguration + org.onap.policy.rest.jpa.PIPResolver + org.onap.policy.rest.jpa.PIPResolverParam + org.onap.policy.rest.jpa.PIPType + org.onap.policy.rest.jpa.PolicyAlgorithms + org.onap.policy.rest.jpa.PolicyManagement + org.onap.policy.rest.jpa.PolicyScopeService + org.onap.policy.rest.jpa.PolicyScopeType + org.onap.policy.rest.jpa.PolicyScopeResource + org.onap.policy.rest.jpa.PolicyScopeClosedLoop + org.onap.policy.rest.jpa.PortList + org.onap.policy.rest.jpa.PREFIXLIST + org.onap.policy.rest.jpa.ProtocolList + org.onap.policy.rest.jpa.RemoteCatalogValues + org.onap.policy.rest.jpa.PolicyRoles + org.onap.policy.rest.jpa.RuleAlgorithms + org.onap.policy.rest.jpa.SecurityZone + org.onap.policy.rest.jpa.ServiceList + org.onap.policy.rest.jpa.SystemLogDB + org.onap.policy.rest.jpa.TermList + org.onap.policy.rest.jpa.VarbindDictionary + org.onap.policy.rest.jpa.VMType + org.onap.policy.rest.jpa.VNFType + org.onap.policy.rest.jpa.VSCLAction + org.onap.policy.rest.jpa.Zone + + org.onap.policy.jpa.BackUpMonitorEntity + + org.onap.policy.common.im.jpa.StateManagementEntity + org.onap.policy.common.im.jpa.ForwardProgressEntity + org.onap.policy.common.im.jpa.ResourceRegistrationEntity + + org.onap.policy.common.ia.jpa.IntegrityAuditEntity + + false + NONE + + + + + + + + + + + + + + + diff --git a/ONAP-PAP-REST/src/main/resources/log4j.properties b/ONAP-PAP-REST/src/main/resources/log4j.properties new file mode 100644 index 000000000..04f3233c1 --- /dev/null +++ b/ONAP-PAP-REST/src/main/resources/log4j.properties @@ -0,0 +1,71 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PAP-REST +# ================================================================================ +# 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========================================================= +### + +# +# Use this properties for deployments. +# +# +# Set root logger level to DEBUG and its only appender to FILE. +#log4j.rootLogger=DEBUG, FILE, CONSOLE +log4j.rootLogger=INFO, FILE + +# FILE appender +log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender +log4j.appender.FILE.File=${catalina.base}/logs/pap-rest.log +log4j.appender.FILE.ImmediateFlush=true +log4j.appender.FILE.Threshold=debug +log4j.appender.FILE.append=true +log4j.appender.FILE.DatePattern='.'yyyy-MM-dd +log4j.appender.FILE.layout=org.apache.log4j.PatternLayout +log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss}{GMT+0}+00:00|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%l||%m%n + +# for Developments and Debugging +#log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +#log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +#log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n + +# +# This is specifically for Xacml request/response logging +# +log4j.logger.xacml.request=INFO, REQUEST_LOG + +log4j.appender.REQUEST_LOG=org.apache.log4j.DailyRollingFileAppender +log4j.appender.REQUEST_LOG.File=${catalina.base}/logs/pap-rest-reqres.log +log4j.appender.REQUEST_LOG.ImmediateFlush=true +log4j.appender.REQUEST_LOG.Threshold=debug +log4j.appender.REQUEST_LOG.append=true +log4j.appender.REQUEST_LOG.DatePattern='.'yyyy-MM-dd + +log4j.appender.REQUEST_LOG.layout=org.apache.log4j.PatternLayout +log4j.appender.REQUEST_LOG.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} %m%n + +# +# audit (transaction) logging +# +log4j.logger.auditLogger=INFO,AUDIT_LOG +log4j.additivity.auditLogger=false + +log4j.appender.AUDIT_LOG=org.apache.log4j.DailyRollingFileAppender +log4j.appender.AUDIT_LOG.File=${catalina.base}/logs/audit.log +log4j.appender.AUDIT_LOG.Append=true +log4j.appender.AUDIT_LOG.DatePattern='.'yyyy-MM-dd +log4j.appender.AUDIT_LOG.threshold=INFO +log4j.appender.AUDIT_LOG.layout=org.apache.log4j.EnhancedPatternLayout +log4j.appender.AUDIT_LOG.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss}{GMT+0}+00:00|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%X{className}|%X{timer}|%m%n diff --git a/ONAP-PAP-REST/src/main/resources/logback.xml b/ONAP-PAP-REST/src/main/resources/logback.xml new file mode 100644 index 000000000..28dc956f3 --- /dev/null +++ b/ONAP-PAP-REST/src/main/resources/logback.xml @@ -0,0 +1,254 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + --> + + + + + + + + + + + + + + + + + + + + ${defaultPattern} + + + + + + + + + + + + + ${logDirectory}/${auditLogName}.log + + ${logDirectory}/${auditLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + ${defaultAuditPattern} + + + + + 256 + + + + + + + + ${logDirectory}/${metricsLogName}.log + + ${logDirectory}/${metricsLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + + ${defaultMetricPattern} + + + + + 256 + + + + + + + + ${logDirectory}/${errorLogName}.log + + ${logDirectory}/${errorLogName}.%i.log.zip + + 1 + 9 + + + ERROR + + + 5MB + + + ${defaultErrorPattern} + + + + + 256 + + + + + + + ${debugLogDirectory}/${debugLogName}.log + + ${debugLogDirectory}/${debugLogName}.%i.log.zip + + 1 + 9 + + + DEBUG + + + 5MB + + + ${debugLoggerPattern} + + + + + 256 + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ONAP-PAP-REST/src/main/resources/spring.xml b/ONAP-PAP-REST/src/main/resources/spring.xml new file mode 100644 index 000000000..ced7ac130 --- /dev/null +++ b/ONAP-PAP-REST/src/main/resources/spring.xml @@ -0,0 +1,46 @@ + + + + + + + + + + + classpath:hibernate.cfg.xml + + + + org.hibernate.dialect.MySQLDialect + thread + false + + + + diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java new file mode 100644 index 000000000..6c91411c3 --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java @@ -0,0 +1,450 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.ia; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Properties; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; + +import org.apache.commons.lang3.SerializationUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.ia.DbAudit; +import org.onap.policy.common.ia.DbDAO; +import org.onap.policy.common.ia.IntegrityAuditProperties; +import org.onap.policy.common.ia.jpa.IntegrityAuditEntity; +import org.onap.policy.common.im.jpa.ForwardProgressEntity; +import org.onap.policy.common.im.jpa.ResourceRegistrationEntity; +import org.onap.policy.common.im.jpa.StateManagementEntity; +import org.onap.policy.jpa.BackUpMonitorEntity; + +public class DbAuditCompareEntriesTest { + + private static Log logger = LogFactory.getLog(DbAuditCompareEntriesTest.class); + private DbDAO dbDAO; + private String persistenceUnit; + private Properties properties; + private String resourceName; + private String dbDriver; + private String dbUrl; + private String dbUser; + private String dbPwd; + private String siteName; + private String nodeType; + + @Before + public void setUp() throws Exception { + logger.info("setUp: Entering"); + + properties = new Properties(); + properties.put(IntegrityAuditProperties.DB_DRIVER, IntegrityAuditProperties.DEFAULT_DB_DRIVER); + properties.put(IntegrityAuditProperties.DB_URL, "jdbc:h2:file:./sql/xacmlTest"); + properties.put(IntegrityAuditProperties.DB_USER, IntegrityAuditProperties.DEFAULT_DB_USER); + properties.put(IntegrityAuditProperties.DB_PWD, IntegrityAuditProperties.DEFAULT_DB_PWD); + properties.put(IntegrityAuditProperties.SITE_NAME, "SiteA"); + properties.put(IntegrityAuditProperties.NODE_TYPE, "pap"); + + dbDriver = IntegrityAuditProperties.DEFAULT_DB_DRIVER; + dbUrl = "jdbc:h2:file:./sql/xacmlTest"; + dbUser = IntegrityAuditProperties.DEFAULT_DB_USER; + dbPwd = IntegrityAuditProperties.DEFAULT_DB_PWD; + siteName = "SiteA"; + nodeType = "pap"; + persistenceUnit = "testPapPU"; + resourceName = "siteA.pap1"; + + //Clean the iaTest DB table for IntegrityAuditEntity entries + cleanDb(persistenceUnit, properties); + + logger.info("setUp: Exiting"); + } + + @After + public void tearDown() throws Exception { + logger.info("tearDown: Entering"); + //nothing to do + logger.info("tearDown: Exiting"); + } + + public void cleanDb(String persistenceUnit, Properties properties){ + logger.debug("cleanDb: enter"); + + EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); + + EntityManager em = emf.createEntityManager(); + // Start a transaction + EntityTransaction et = em.getTransaction(); + + et.begin(); + + // Clean up the DB + em.createQuery("Delete from IntegrityAuditEntity").executeUpdate(); + + // commit transaction + et.commit(); + em.close(); + logger.debug("cleanDb: exit"); + } + + + /* + * Tests that a comparison between hashsets is successful if + * the entries match + */ + @Test + public void runAllTests() throws Exception { + logger.info("runAllTests: Entering"); + + + testIntegrityAuditEntity(); + testBackupMonitorEntity(); + testStateManagementEntity(); + testForwardProgressEntity(); + testResourceRegistrationEntity(); + + //clean up the IntegrityAuditEntity table + cleanDb(persistenceUnit, properties); + + logger.info("runAllTests: Exit"); + } + + + public void testIntegrityAuditEntity() throws Exception { + logger.info("testIntegrityAuditEntity: Entering"); + + dbDAO = new DbDAO(resourceName, persistenceUnit, properties); + DbAudit dbAudit = new DbAudit(dbDAO); + + String className = null; + //There is only one entry IntegrityAuditEntity, but we will check anyway + HashSet classNameSet = dbDAO.getPersistenceClassNames(); + for(String c : classNameSet){ + if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")){ + className = c; + } + } + String resourceName1 = resourceName; + String resourceName2 = resourceName; + + IntegrityAuditEntity entry1 = new IntegrityAuditEntity(); + IntegrityAuditEntity entry2 = new IntegrityAuditEntity(); + Date date = new Date(); + + /* + * Two entries with the same field values + */ + entry1.setDesignated(false); + entry1.setJdbcDriver(dbDriver); + entry1.setJdbcPassword(dbPwd); + entry1.setJdbcUrl(dbUrl); + entry1.setJdbcUser(dbUser); + entry1.setLastUpdated(date); + entry1.setNodeType(nodeType); + entry1.setPersistenceUnit(persistenceUnit); + entry1.setResourceName(resourceName1); + entry1.setSite(siteName); + + entry2 = SerializationUtils.clone(entry1); + + dbAudit.writeAuditDebugLog(className, resourceName1, resourceName2, entry1, entry2); + + HashMap myEntries = new HashMap<>(); + HashMap theirEntries = new HashMap<>(); + + myEntries.put("pdp1", entry1); + theirEntries.put("pdp1", entry2); + + HashSet result = dbAudit.compareEntries(myEntries, theirEntries); + + /* + * Assert that there are no mismatches returned + */ + assertTrue(result.isEmpty()); + + /* + * ************************************ + * Now test with a mis-matched entry + * ************************************ + */ + + /* + * Change the entry2 to different designated value + */ + entry2.setDesignated(true); + + myEntries = new HashMap<>(); + theirEntries = new HashMap<>(); + + myEntries.put("pdp1", entry1); + theirEntries.put("pdp1", entry2); + + result = dbAudit.compareEntries(myEntries, theirEntries); + + /* + * Assert that there was one mismatch + */ + assertEquals(1, result.size()); + logger.info("testIntegrityAuditEntity: Exit"); + } + + void testBackupMonitorEntity() throws Exception { + logger.info("testBackupMonitorEntity: Entering"); + + dbDAO = new DbDAO(resourceName, persistenceUnit, properties); + DbAudit dbAudit = new DbAudit(dbDAO); + + BackUpMonitorEntity entry1 = new BackUpMonitorEntity(); + BackUpMonitorEntity entry2 = new BackUpMonitorEntity(); + + // Two entries with the same field values + + + entry1.setFlag("flag1"); + entry1.setResoruceNodeName("node1"); + entry1.setResourceName("resourceName"); + entry1.setTimeStamp(new Date()); + + // Clone the first entry + entry2 = SerializationUtils.clone(entry1); + + HashMap myEntries = new HashMap<>(); + HashMap theirEntries = new HashMap<>(); + + myEntries.put("pdp1", entry1); + theirEntries.put("pdp1", entry2); + + HashSet result = dbAudit.compareEntries(myEntries, theirEntries); + + + // Assert that there are no mismatches returned + + assertTrue(result.isEmpty()); + + + /* ************************************ + * Now test with a mis-matched entry + * ************************************/ + + + + // Change a field on entry2 + + entry2.setFlag("flag2"); + + myEntries = new HashMap<>(); + theirEntries = new HashMap<>(); + + myEntries.put("pdp1", entry1); + theirEntries.put("pdp1", entry2); + + result = dbAudit.compareEntries(myEntries, theirEntries); + + + //Assert that there was one mismatch + + assertEquals(1, result.size()); + logger.info("testBackupMonitorEntity: Exit"); + } + + void testStateManagementEntity() throws Exception { + logger.info("testStateManagementEntity: Entering"); + + dbDAO = new DbDAO(resourceName, persistenceUnit, properties); + DbAudit dbAudit = new DbAudit(dbDAO); + + StateManagementEntity entry1 = new StateManagementEntity(); + StateManagementEntity entry2 = new StateManagementEntity(); + + // Two entries with the same field values + + entry1.setAdminState("locked"); + entry1.setAvailStatus("null"); + entry1.setModifiedDate(new Date()); + entry1.setOpState("enabled"); + entry1.setResourceName("myResource"); + entry1.setStandbyStatus("coldstandby"); + + // Clone the first entry + entry2 = SerializationUtils.clone(entry1); + + HashMap myEntries = new HashMap<>(); + HashMap theirEntries = new HashMap<>(); + + myEntries.put("pdp1", entry1); + theirEntries.put("pdp1", entry2); + + HashSet result = dbAudit.compareEntries(myEntries, theirEntries); + + + // Assert that there are no mismatches returned + + assertTrue(result.isEmpty()); + + + /* ************************************ + * Now test with a mis-matched entry + * ************************************/ + + + + // Change a field on entry2 + + entry2.setAdminState("unlocked"); + + myEntries = new HashMap<>(); + theirEntries = new HashMap<>(); + + myEntries.put("pdp1", entry1); + theirEntries.put("pdp1", entry2); + + result = dbAudit.compareEntries(myEntries, theirEntries); + + + //Assert that there was one mismatch + + assertEquals(1, result.size()); + logger.info("testStateManagementEntity: Exit"); + } + + void testForwardProgressEntity() throws Exception { + logger.info("testForwardProgressEntity: Entering"); + + dbDAO = new DbDAO(resourceName, persistenceUnit, properties); + DbAudit dbAudit = new DbAudit(dbDAO); + + ForwardProgressEntity entry1 = new ForwardProgressEntity(); + ForwardProgressEntity entry2 = new ForwardProgressEntity(); + + // Two entries with the same field values + + entry1.setFpcCount(123L); + entry1.setLastUpdated(new Date()); + entry1.setResourceName("myResource"); + + // Clone the first entry + entry2 = SerializationUtils.clone(entry1); + + HashMap myEntries = new HashMap(); + HashMap theirEntries = new HashMap(); + + myEntries.put("pdp1", entry1); + theirEntries.put("pdp1", entry2); + + HashSet result = dbAudit.compareEntries(myEntries, theirEntries); + + + // Assert that there are no mismatches returned + + assertTrue(result.isEmpty()); + + + /* ************************************ + * Now test with a mis-matched entry + * ************************************/ + + // Change a field on entry2 + + entry2.setFpcCount(321L); + + myEntries = new HashMap<>(); + theirEntries = new HashMap<>(); + + myEntries.put("pdp1", entry1); + theirEntries.put("pdp1", entry2); + + result = dbAudit.compareEntries(myEntries, theirEntries); + + + //Assert that there was one mismatch + + assertEquals(1, result.size()); + logger.info("testForwardProgressEntity: Exit"); + } + + void testResourceRegistrationEntity() throws Exception { + logger.info("testResourceRegistrationEntity: Entering"); + + dbDAO = new DbDAO(resourceName, persistenceUnit, properties); + DbAudit dbAudit = new DbAudit(dbDAO); + + ResourceRegistrationEntity entry1 = new ResourceRegistrationEntity(); + ResourceRegistrationEntity entry2 = new ResourceRegistrationEntity(); + + // Two entries with the same field values + + entry1.setNodeType("pap"); + entry1.setLastUpdated(new Date()); + entry1.setResourceName("myResource"); + entry1.setResourceUrl("http://nowhere.com"); + entry1.setSite("site_1"); + + // Clone the first entry + entry2 = SerializationUtils.clone(entry1); + + HashMap myEntries = new HashMap<>(); + HashMap theirEntries = new HashMap<>(); + + myEntries.put("pdp1", entry1); + theirEntries.put("pdp1", entry2); + + HashSet result = dbAudit.compareEntries(myEntries, theirEntries); + + + // Assert that there are no mismatches returned + + assertTrue(result.isEmpty()); + + + /* ************************************ + * Now test with a mis-matched entry + * ************************************/ + + // Change a field on entry2 + + entry2.setSite("site_1a"); + + myEntries = new HashMap<>(); + theirEntries = new HashMap<>(); + + myEntries.put("pdp1", entry1); + theirEntries.put("pdp1", entry2); + + result = dbAudit.compareEntries(myEntries, theirEntries); + + + //Assert that there was one mismatch + + assertEquals(1, result.size()); + logger.info("testResourceRegistrationEntity: Exit"); + } +} \ No newline at end of file diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java new file mode 100644 index 000000000..01e4a9b61 --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java @@ -0,0 +1,636 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.components; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Paths; +import java.util.Date; +import java.util.List; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.Persistence; +import javax.persistence.PersistenceException; +import javax.persistence.Query; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.junit.After; +import org.junit.Assert; +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.components.PolicyDBDao.PolicyDBDaoTestClass; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.GroupEntity; +import org.onap.policy.rest.jpa.PdpEntity; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDPGroup; +import org.onap.policy.xacml.util.XACMLPolicyWriter; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.util.XACMLProperties; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + +public class PolicyDBDaoTest { + + private static Logger logger = FlexLogger.getLogger(PolicyDBDaoTest.class); + + PolicyDBDaoTestClass d; + PolicyDBDao dbd; + PolicyDBDao dbd2; + EntityManagerFactory emf; + @Before + public void init(){ + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"xacml.pap.properties"); + emf = Persistence.createEntityManagerFactory("testPapPU"); + EntityManager em = emf.createEntityManager(); + em.getTransaction().begin(); + try{ + em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate(); + em.createQuery("DELETE FROM PolicyEntity").executeUpdate(); + em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate(); + em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate(); + em.createQuery("DELETE FROM PdpEntity").executeUpdate(); + em.createQuery("DELETE FROM GroupEntity").executeUpdate(); + + em.getTransaction().commit(); + } catch(Exception e){ + logger.error("Exception Occured"+e); + em.getTransaction().rollback(); + } + em.close(); + try { + dbd = PolicyDBDao.getPolicyDBDaoInstance(emf); + dbd2 = PolicyDBDao.getPolicyDBDaoInstance(emf); + } catch (Exception e) { + //logger.error("Exception Occured"+e); + Assert.fail(); + } + + d = PolicyDBDao.getPolicyDBDaoTestClass(); + } + + @After + public void cleanUp(){ + EntityManager em = emf.createEntityManager(); + em.getTransaction().begin(); + try{ + em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate(); + em.createQuery("DELETE FROM PolicyEntity").executeUpdate(); + em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate(); + em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate(); + em.createQuery("DELETE FROM PdpEntity").executeUpdate(); + em.createQuery("DELETE FROM GroupEntity").executeUpdate(); + + em.getTransaction().commit(); + } catch(Exception e){ + em.getTransaction().rollback(); + } + em.close(); + try { + FileUtils.forceDelete(new File("src/test/resources/junitTestCreatedDirectory")); + } catch (IOException e) { + //could not delete + } + + } + + @Test + public void computeScopeTest(){ + Assert.assertEquals("com",d.computeScope("C:\\Users\\testuser\\admin\\repo\\com\\", "C:\\Users\\testuser\\admin\\repo")); + Assert.assertEquals("org.onap.policy",d.computeScope("/Users/testuser/admin/repo/org.onap.policy", "/Users/testuser/admin/repo")); + } + @Test + public void getConfigFileTest(){ + PolicyRestAdapter pra = new PolicyRestAdapter(); + pra.setConfigType(ConfigPolicy.JSON_CONFIG); + String configFile = d.getConfigFile("Config_mypolicy.xml", "org.onap", pra); + Assert.assertEquals("org.onap.Config_mypolicy.json", configFile); + //yes, we can do action files too even though they don't have configs + configFile = d.getConfigFile("Action_mypolicy.xml", "org.onap", pra); + Assert.assertEquals("org.onap.Action_mypolicy.json", configFile); + } + + @Ignore + @Test + public void createFromPolicyObject(){ + String workspaceDir = "src/test/resources/"; + File parentPath = new File(workspaceDir+"/com"); + Policy policyObject = new ConfigPolicy(); + policyObject.policyAdapter = new PolicyRestAdapter(); + policyObject.policyAdapter.setConfigName("testpolicy1"); + policyObject.policyAdapter.setParentPath(parentPath.getAbsolutePath()); + policyObject.policyAdapter.setPolicyDescription("my description"); + policyObject.policyAdapter.setConfigBodyData("this is my test config file"); + policyObject.policyAdapter.setPolicyName("testpolicy1"); + policyObject.policyAdapter.setConfigType(ConfigPolicy.OTHER_CONFIG); + policyObject.policyAdapter.setPolicyType("Config"); + policyObject.policyAdapter.setDomainDir("org.onap"); + PolicyType policyTypeObject = new PolicyType(); + policyObject.policyAdapter.setPolicyData(policyTypeObject); + PolicyDBDaoTransaction transaction = dbd.getNewTransaction(); + try{ + transaction.createPolicy(policyObject, "testuser1"); + transaction.commitTransaction(); + } catch(Exception e){ + transaction.rollbackTransaction(); + Assert.fail(); + } + + EntityManager getData = emf.createEntityManager(); + Query getDataQuery = getData.createQuery("SELECT p FROM PolicyEntity p WHERE p.scope=:scope AND p.policyName=:name"); + getDataQuery.setParameter("scope", "org.onap"); + getDataQuery.setParameter("name","Config_testpolicy1.xml"); + PolicyEntity result = null; + try{ + result = (PolicyEntity)getDataQuery.getSingleResult(); + } catch(Exception e){ + logger.error("Exception Occured"+e); + Assert.fail(); + } + String expectedData; + try { + expectedData = IOUtils.toString(XACMLPolicyWriter.getXmlAsInputStream(policyTypeObject)); + } catch (IOException e1) { + expectedData = ""; + } + Assert.assertEquals(expectedData, result.getPolicyData()); + getData.close(); + result = null; + File policyFile = new File(workspaceDir+"/org/onap/Config_testpolicy1.xml"); + try{ + transaction = dbd.getNewTransaction(); + transaction.deletePolicy(policyFile.getAbsolutePath()); + } catch(Exception e){ + logger.error("Exception Occured"+e); + Assert.fail(); + } + Assert.assertTrue(transaction.isTransactionOpen()); + try{ + transaction.deletePolicy(policyFile.getAbsolutePath()); + Assert.fail(); + } catch(IllegalStateException e){ + //pass + } catch(Exception e){ + Assert.fail(); + } + transaction.commitTransaction(); + Assert.assertFalse(transaction.isTransactionOpen()); + try{ + transaction = dbd.getNewTransaction(); + transaction.deletePolicy(policyFile.getAbsolutePath()); + } catch(Exception e){ + logger.error("Exception Occured"+e); + Assert.fail(); + } + //Assert.assertFalse(transaction.isTransactionOpen()); + transaction.commitTransaction(); + } + + @Ignore + @Test + public void groupTransactions(){ + PolicyDBDaoTransaction group = dbd.getNewTransaction(); + String groupName = "test group 1"; + try{ + group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "this is a test group","testuser"); + group.commitTransaction(); + } catch(Exception e){ + group.rollbackTransaction(); + logger.error("Exception Occured"+e); + Assert.fail(); + } + EntityManager em = emf.createEntityManager(); + Query getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + getGroup.setParameter("groupId", PolicyDBDao.createNewPDPGroupId(groupName)); + getGroup.setParameter("deleted", false); + List groups = getGroup.getResultList(); + if(groups.size() != 1){ + Assert.fail(); + } + GroupEntity groupEntity = (GroupEntity)groups.get(0); + em.close(); + Assert.assertEquals(groupName, groupEntity.getgroupName()); + Assert.assertEquals("this is a test group", groupEntity.getDescription()); + group = dbd.getNewTransaction(); + try{ + OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId(groupName),Paths.get("/")); + group.deleteGroup(groupToDelete, null,"testuser"); + group.commitTransaction(); + } catch(Exception e){ + group.rollbackTransaction(); + logger.error("Exception Occured"+e); + Assert.fail(); + } + em = emf.createEntityManager(); + getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + getGroup.setParameter("groupId", PolicyDBDao.createNewPDPGroupId(groupName)); + getGroup.setParameter("deleted", false); + groups = getGroup.getResultList(); + if(groups.size() != 0){ + System.out.println("Group size: "+groups.size()); + Assert.fail(); + } + em.close(); + //add a pdp to a group + group = dbd.getNewTransaction(); + try{ + group.createGroup(PolicyDBDao.createNewPDPGroupId(groupName), groupName, "test group", "testuser"); + group.commitTransaction(); + } catch(Exception e){ + group.rollbackTransaction(); + logger.error("Exception Occured"+e); + Assert.fail(); + } + group = dbd.getNewTransaction(); + try{ + group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId(groupName), "primary", "the main pdp", 3232, "testuser"); + group.commitTransaction(); + } catch(Exception e){ + group.rollbackTransaction(); + logger.error("Exception Occured"+e); + Assert.fail(); + } + em = emf.createEntityManager(); + Query getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); + getPdp.setParameter("pdpId", "http://localhost:4344/pdp/"); + getPdp.setParameter("deleted", false); + List pdps = getPdp.getResultList(); + if(pdps.size() != 1){ + System.out.println("Group size: "+pdps.size()); + Assert.fail(); + } + PdpEntity pdp = (PdpEntity)pdps.get(0); + Assert.assertEquals(groupName, pdp.getGroup().getgroupName()); + Assert.assertEquals(pdp.getPdpName(), "primary"); + em.close(); + group = dbd.getNewTransaction(); + try{ + group.removePdpFromGroup("http://localhost:4344/pdp/","testuser"); + group.commitTransaction(); + } catch(Exception e){ + group.rollbackTransaction(); + logger.error("Exception Occured"+e); + Assert.fail(); + } + em = emf.createEntityManager(); + getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"); + getPdp.setParameter("pdpId", "http://localhost:4344/pdp/"); + getPdp.setParameter("deleted", false); + pdps = getPdp.getResultList(); + if(pdps.size() != 0){ + System.out.println("Group size: "+pdps.size()); + Assert.fail(); + } + em.close(); + + //add some pdps to groups + group = dbd.getNewTransaction(); + try{ + group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"), "testgroup1", "test group", "testuser"); + group.commitTransaction(); + } catch(Exception e){ + group.rollbackTransaction(); + logger.error("Exception Occured"+e); + Assert.fail(); + } + group = dbd.getNewTransaction(); + try{ + group.createGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"), "testgroup2", "test group", "testuser"); + group.commitTransaction(); + } catch(Exception e){ + group.rollbackTransaction(); + logger.error("Exception Occured"+e); + Assert.fail(); + } + + group = dbd.getNewTransaction(); + try{ + group.addPdpToGroup("http://localhost:4344/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), "primary", "the main pdp", 3232, "testuser"); + group.commitTransaction(); + } catch(Exception e){ + group.rollbackTransaction(); + logger.error("Exception Occured"+e); + Assert.fail(); + } + group = dbd.getNewTransaction(); + try{ + group.addPdpToGroup("http://localhost:4345/pdp/", PolicyDBDao.createNewPDPGroupId("testgroup1"), "secondary", "the second pdp", 3233, "testuser"); + group.commitTransaction(); + } catch(Exception e){ + group.rollbackTransaction(); + logger.error("Exception Occured"+e); + Assert.fail(); + } + em = emf.createEntityManager(); + getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.deleted=:deleted"); + getPdp.setParameter("deleted", false); + pdps = getPdp.getResultList(); + for(Object o : pdps){ + Assert.assertEquals("testgroup1",((PdpEntity)o).getGroup().getgroupName()); + } + em.close(); + + group = dbd.getNewTransaction(); + try{ + OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"),Paths.get("/")); + OnapPDPGroup groupToMoveTo = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"),Paths.get("/")); + group.deleteGroup(groupToDelete, groupToMoveTo,"testuser"); + group.commitTransaction(); + } catch(Exception e){ + group.rollbackTransaction(); + logger.error("Exception Occured"+e); + Assert.fail(); + } + em = emf.createEntityManager(); + getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + getGroup.setParameter("groupId", "testgroup1"); + getGroup.setParameter("deleted", false); + groups = getGroup.getResultList(); + if(groups.size() != 0){ + System.out.println("Group size: "+groups.size()); + Assert.fail(); + } + em.close(); + + em = emf.createEntityManager(); + getPdp = em.createQuery("SELECT p FROM PdpEntity p WHERE p.deleted=:deleted"); + getPdp.setParameter("deleted", false); + pdps = getPdp.getResultList(); + for(Object o : pdps){ + Assert.assertEquals("testgroup2",((PdpEntity)o).getGroup().getgroupName()); + } + em.close(); + + group = dbd.getNewTransaction(); + try{ + OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"),Paths.get("/")); + OnapPDPGroup groupToMoveTo = null; + group.deleteGroup(groupToDelete, groupToMoveTo,"testuser"); + group.commitTransaction(); + Assert.fail(); + } catch(PAPException pe){ + //good, can't delete group with pdps + group.rollbackTransaction(); + } catch(Exception e){ + group.rollbackTransaction(); + logger.error("Exception Occured"+e); + Assert.fail(); + } + + + //add policy to group + + //update group + OnapPDPGroup pdpGroup = new StdPDPGroup("testgroup2", false, "newtestgroup2", "this is my new description", Paths.get("/")); + group = dbd.getNewTransaction(); + try{ + group.updateGroup(pdpGroup, "testuser"); + group.commitTransaction(); + }catch (Exception e){ + logger.error("Exception Occured"+e); + group.rollbackTransaction(); + Assert.fail(); + } + em = emf.createEntityManager(); + getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + getGroup.setParameter("groupId", "newtestgroup2"); + getGroup.setParameter("deleted", false); + groups = getGroup.getResultList(); + if(groups.size() != 1){ + System.out.println("Group size: "+groups.size()); + Assert.fail(); + } + em.close(); + em = emf.createEntityManager(); + getGroup = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted"); + getGroup.setParameter("groupId", "testgroup2"); + getGroup.setParameter("deleted", false); + groups = getGroup.getResultList(); + if(groups.size() != 0){ + System.out.println("Group size: "+groups.size()); + Assert.fail(); + } + em.close(); + } + + @Test + public void encryptionTest(){ + try { + String encr = d.encryptPassword("testpassword"); + System.out.println("original password: "+"testpassword"); + System.out.println("Encrypted password: "+encr); + String decr = d.decryptPassword(encr); + System.out.println("Decrypted password: "+decr); + Assert.assertEquals("testpassword", decr); + } catch (Exception e) { + logger.error("Exception Occured"+e); + Assert.fail(); + } + + } + @Test + public void getDescriptionFromXacmlTest(){ + String myTestDesc = "hello this is a test"; + String desc = d.getDescriptionFromXacml(""+myTestDesc+""); + Assert.assertEquals(myTestDesc, desc); + } + @Ignore + @Test + public void threadingStabilityTest(){ + if(logger.isDebugEnabled()){ + logger.debug("\n\n****************************" + + "threadingStabilityTest() entry" + + "******************************\n\n"); + } + + PolicyDBDaoTransaction t = dbd.getNewTransaction(); + Assert.assertTrue(t.isTransactionOpen()); + try { + //Add 1000 ms to the timeout just to be sure it actually times out + int sleepTime = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)) + 1000; + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + + "\n sleepTime = " + sleepTime + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + Thread.sleep(sleepTime); + } catch (InterruptedException e) { + logger.error("Exception Occured"+e); + } + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + + "\n Assert.assertFalse(t.isTransactionOpen() = " + t.isTransactionOpen() + ")" + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + Assert.assertFalse(t.isTransactionOpen()); + + + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + + "\n a = dbd.getNewTransaction() " + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + PolicyDBDaoTransaction a = dbd.getNewTransaction(); + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + + "\n Assert.assertTrue(a.isTransactionOpen() = " + a.isTransactionOpen() + ")" + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + Assert.assertTrue(a.isTransactionOpen()); + + try { + //Add 1000 ms to the timeout just to be sure it actually times out + int sleepTime = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)) + 1000; + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + + "\n sleepTime = " + sleepTime + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + Thread.sleep(sleepTime); + } catch (InterruptedException e) { + logger.error("Exception Occured"+e); + } + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + + "\n b = dbd.getNewTransaction() " + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + PolicyDBDaoTransaction b = dbd.getNewTransaction(); + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + + "\n Assert.assertFalse(a.isTransactionOpen() = " + a.isTransactionOpen() + ")" + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + Assert.assertFalse(a.isTransactionOpen()); + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + + "\n Assert.assertTrue(b.isTransactionOpen() = " + b.isTransactionOpen() + ")" + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + Assert.assertTrue(b.isTransactionOpen()); + b.close(); + + + + //Now let's test the transaction wait time timeout. Shorten the wait time to 1000 ms + System.setProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT,"1000"); + //And let's lengthen the transaction timeout to 5000 ms + System.setProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT,"5000"); + //get a transacton + PolicyDBDaoTransaction t1 = dbd.getNewTransaction(); + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + + "\n Assert.assertTrue(t1.isTransactionOpen() = " + t1.isTransactionOpen() + ")" + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + Assert.assertTrue(t1.isTransactionOpen()); + //while it is open, get another from a different DB Dao so it will not collide on the synchronized code segment + //but will collide at the DB. Remember that the wait time is only 1000 ms + try { + //Now the 2nd transaction has a wait timeout in 1000 ms + PolicyDBDaoTransaction t2 = dbd2.getNewTransaction(); + /* + * Give it plenty of time to time out the second transaction + * It will actually hang right here until it either gets the lock from the DB or the + * request for the DB lock times out. The timers are very sloppy so, I have given + * this plenty of leeway. + */ + + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + + "\n Thread.sleep(3000)" + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + Thread.sleep(3000); + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + + "\n Assert.assertTrue(t1.isTransactionOpen() = " + t1.isTransactionOpen() + ")" + + "\n Assert.assertFalse(t2.isTransactionOpen() = " + t2.isTransactionOpen() + ")" + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + //Assert.assertTrue(t1.isTransactionOpen()); + //Assert.assertFalse(t2.isTransactionOpen()); + + Assert.fail("\n\nTransaction timeout of 1000 ms exceeded without a PersistenceException\n\n"); + } catch (PersistenceException e) { + //success + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + + "\n SUCCESS! Transaction Wait Timeout worked!" + + "\n Caught PersistenceException = " + e + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + } catch (Exception e) { + // failure due to some other reason + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() FAILURE" + + "\n Caught Exception = " + e + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + logger.error("Exception Occured"+e); + Assert.fail(); + } + + if(logger.isDebugEnabled()){ + Date date= new java.util.Date(); + logger.debug("\n\nthreadingStabilityTest() exit" + + "\n TimeStamp = " + date.getTime() + + "\n\n"); + } + } + +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java new file mode 100644 index 000000000..708794d60 --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java @@ -0,0 +1,319 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.controller; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.BufferedReader; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.servlet.http.HttpServletRequest; + +import org.json.JSONObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +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.Attribute; +import org.onap.policy.rest.jpa.MicroServiceModels; +import org.onap.policy.rest.jpa.PolicyEditorScopes; +import org.springframework.mock.web.MockHttpServletResponse; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.fge.jackson.JsonLoader; + +/** + * The class DictionaryControllerTest contains tests + * for the class {@link DictionaryController}* + * + * All JUnits are designed to run in the local development environment + * where they have write privileges and can execute time-sensitive + * tasks. + */ +public class DictionaryControllerTest { + + private static Logger logger = FlexLogger.getLogger(DictionaryControllerTest.class); + private static CommonClassDao commonClassDao; + private String jsonString = null; + private String configBodyString = null; + private HttpServletRequest request = null; + private DictionaryController controller = null; + private BufferedReader br = null; + + @Before + public void setUp() throws Exception { + logger.info("setUp: Entering"); + commonClassDao = Mockito.mock(CommonClassDao.class); + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + List microServiceModelsData = new ArrayList(); + MicroServiceModels testData = new MicroServiceModels(); + testData.setVersion("1707.4.1.2-Junit"); + + //--- mock the getDataByColumn() call + List microList = new ArrayList(); + microList.add("123"); + List listId = new ArrayList(); + when(commonClassDao.getDataByColumn(Attribute.class, "xacmlId")).thenReturn(microList); + PolicyEditorScopes editorScope = new PolicyEditorScopes(); + doNothing().when(commonClassDao).save(editorScope); + doNothing().when(commonClassDao).update(editorScope); + + when(commonClassDao.getData(Attribute.class)).thenReturn(listId); + + jsonString = "{\"attributeDictionaryDatas\": {\"error\": \"\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " + + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," + + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," + + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " + + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," + + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " + + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; + + configBodyString = "{\"service\":\"SniroPolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\",\"templateVersion\":\"1607\",\"version\":\"HD\"," + + "\"priority\":\"2\",\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\",\"retiredDate\":\"test\",\"scope\":\"SNIRO_PLACEMENT_VDHV\"," + + "\"name\":\"test\",\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\",\"target\":\"SNIRO\"}}"; + + request = mock(HttpServletRequest.class); + BufferedReader br = new BufferedReader(new StringReader(jsonString)); + //--- mock the getReader() call + when(request.getReader()).thenReturn(br); + + controller = new DictionaryController(commonClassDao); + + logger.info("setUp: exit"); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetAttributeDictionaryEntityDatabyAttributeName() { + logger.info("testGetAttributeDictionaryEntityDatabyAttributeName: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + + controller.getAttributeDictionaryEntityDatabyAttributeName(request, response); + + try { + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + } catch (UnsupportedEncodingException e) { + fail("Exception: " + e); + } + + logger.info("testGetAttributeDictionaryEntityDatabyAttributeName: exit"); + } + + @Test + public void testGetAttributeDictionaryEntityData() { + logger.info("testGetAttributeDictionaryEntityData: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + + controller.getAttributeDictionaryEntityData(request, response); + + try { + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + } catch (UnsupportedEncodingException e) { + fail("Exception: " + e); + } + + logger.info("testGetAttributeDictionaryEntityData: exit"); + } + + @Test + public void testSaveAttributeDictionary() { + logger.info("testSaveAttributeDictionary: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + jsonString = "{\"attributeDictionaryData\": {\"userDataTypeValues\": [{\"attributeValues\": \"Values1\"}, {\"attributeValues\": \"Values2\"}], \"datatypeBean\": {\"type\": \"C\"},\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"userDataTypeValues\": [\"user-type\"],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " + + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," + + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," + + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " + + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," + + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " + + " \"policyJSON\": {\"some\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"}, \"userid\":\"smetest\", \"userDataTypeValues\":[\"type-one\"]}"; + + BufferedReader br = new BufferedReader(new StringReader(jsonString)); + when(request.getReader()).thenReturn(br); + controller.saveAttributeDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testSaveAttributeDictionary: exit"); + } + + @Test + public void testRemoveAttributeDictionary() { + logger.info("testRemoveAttributeDictionary: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " + + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," + + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," + + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " + + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," + + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " + + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; + BufferedReader br = new BufferedReader(new StringReader(jsonString)); + when(request.getReader()).thenReturn(br); + controller.removeAttributeDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testRemoveAttributeDictionary: exit"); + } + + @Test + public void testGetOnapNameDictionaryByNameEntityData() { + logger.info("testGetOnapNameDictionaryByNameEntityData: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + + controller.getOnapNameDictionaryByNameEntityData(request, response); + + try { + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas")); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + } catch (UnsupportedEncodingException e) { + fail("Exception: " + e); + } + + logger.info("testGetOnapNameDictionaryByNameEntityData: exit"); + } + + @Test + public void testGetOnapNameDictionaryEntityData() { + logger.info("testGetOnapNameDictionaryEntityData: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + + controller.getOnapNameDictionaryEntityData(request, response); + + try { + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas")); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + } catch (UnsupportedEncodingException e) { + fail("Exception: " + e); + } + + logger.info("testGetOnapNameDictionaryEntityData: exit"); + } + + @Test + public void testSaveOnapDictionary() { + + logger.info("testSaveOnapDictionary: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + jsonString = "{\"onapNameDictionaryData\": {\"userDataTypeValues\": [{\"attributeValues\": \"Values1\"}, {\"attributeValues\": \"Values2\"}], \"datatypeBean\": {\"type\": \"C\"},\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"userDataTypeValues\": [\"user-type\"],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " + + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," + + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," + + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " + + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," + + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " + + " \"policyJSON\": {\"some\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"}, \"userid\":\"smetest\", \"userDataTypeValues\":[\"type-one\"]}"; + + BufferedReader br = new BufferedReader(new StringReader(jsonString)); + when(request.getReader()).thenReturn(br); + controller.saveOnapDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testSaveOnapDictionary: exit"); + } + + @Test + public void testRemoveOnapDictionary() { + logger.info("testRemoveOnapDictionary: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " + + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," + + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," + + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " + + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," + + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " + + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; + BufferedReader br = new BufferedReader(new StringReader(jsonString)); + when(request.getReader()).thenReturn(br); + controller.removeOnapDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testRemoveOnapDictionary: exit"); + } + +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java new file mode 100644 index 000000000..c66ace11e --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java @@ -0,0 +1,693 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.controller; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.BufferedReader; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +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.DCAEuuid; +import org.onap.policy.rest.jpa.MicroServiceLocation; +import org.onap.policy.rest.jpa.MicroServiceModels; +import org.onap.policy.rest.jpa.UserInfo; +import org.springframework.mock.web.MockHttpServletResponse; + +/** + * The class MicroServiceDictionaryControllerTest contains tests + * for the class {@link MicroServiceDictionaryController}* + * + * All JUnits are designed to run in the local development environment + * where they have write privileges and can execute time-sensitive + * tasks. + */ + +public class MicroServiceDictionaryControllerTest { + + private static Logger logger = FlexLogger.getLogger(MicroServiceDictionaryControllerTest.class); + private static CommonClassDao commonClassDao; + private String jsonString = null; + private String configBodyString = null; + private HttpServletRequest request = null; + private MicroServiceDictionaryController controller = null; + BufferedReader br = null; + + @Before + public void setUp() throws Exception { + logger.info("setUp: Entering"); + commonClassDao = Mockito.mock(CommonClassDao.class); + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId("testUserId"); + userInfo.setUserName("John"); + when(commonClassDao.getEntityItem(UserInfo.class, "userLoginId", "testing")).thenReturn(userInfo); + + List listIds = new ArrayList(); + listIds.add("Jack"); + when(commonClassDao.getDataByColumn(DCAEuuid.class, "name")).thenReturn(listIds); + + List microList = new ArrayList(); + microList.add("MC-Model"); + when(commonClassDao.getDataByColumn(MicroServiceLocation.class, "name")).thenReturn(microList); + + List listId = new ArrayList(); + listId.add("smith"); + when(commonClassDao.getData(DCAEuuid.class)).thenReturn(listId); + MicroServiceModels microServiceModels = new MicroServiceModels(); + + doNothing().when(commonClassDao).delete(microServiceModels); + + MicroServiceDictionaryController.setCommonClassDao(commonClassDao); + + controller = new MicroServiceDictionaryController(); + + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + jsonString = "{\"microServiceModelsDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " + + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," + + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," + + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " + + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," + + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " + + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; + + configBodyString = "{\"service\":\"SniroPolicyEntityTest\",\"policyName\":\"someone\",\"description\":\"test\",\"templateVersion\":\"1607\",\"version\":\"HD\"," + + "\"priority\":\"2\",\"content\":{\"lastPolled\":\"1\",\"boolen-test\":\"true\",\"created\":\"test\",\"retiredDate\":\"test\",\"scope\":\"SNIRO_PLACEMENT_VDHV\"," + + "\"name\":\"test\",\"lastModified\":\"test\",\"state\":\"CREATED\",\"type\":\"CONFIG\",\"intent\":\"test\",\"target\":\"SNIRO\"}}"; + + br = new BufferedReader(new StringReader(jsonString)); + //--- mock the getReader() call + when(request.getReader()).thenReturn(br); + + logger.info("setUp: exit"); + } + + @After + public void tearDown() throws Exception { + } + + + @Test + public void testGetUserInfo() { + + logger.info("testGetUserInfo: Entering"); + + UserInfo userInfo = controller.getUserInfo("testing"); + logger.info("userInfo.getUserName() : " + userInfo.getUserName()); + + assertEquals("John", userInfo.getUserName()); + + logger.info("testGetUserInfo: exit"); + } + + @Test + public void testGetDCAEUUIDDictionaryByNameEntityData() { + + logger.info("testGetDCAEUUIDDictionaryByNameEntityData: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + + controller.getDCAEUUIDDictionaryByNameEntityData(request, response); + + try { + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeUUIDDictionaryDatas")); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + } catch (UnsupportedEncodingException e) { + fail("Exception: " + e); + } + + logger.info("testGetDCAEUUIDDictionaryByNameEntityData: exit"); + } + + @Test + public void testGetDCAEUUIDDictionaryEntityData() { + + logger.info("testGetDCAEUUIDDictionaryEntityData: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + + controller.getDCAEUUIDDictionaryEntityData(request, response); + + try { + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeUUIDDictionaryDatas")); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + } catch (UnsupportedEncodingException e) { + fail("Exception: " + e); + } + + logger.info("testGetDCAEUUIDDictionaryEntityData: exit"); + } + + @Test + public void testSaveDCAEUUIDDictionary() { + logger.info("testSaveDCAEUUIDDictionary: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + jsonString = "{\"dcaeUUIDDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " + + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," + + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," + + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " + + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," + + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " + + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; + BufferedReader br = new BufferedReader(new StringReader(jsonString)); + when(request.getReader()).thenReturn(br); + controller.saveDCAEUUIDDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("dcaeUUIDDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testSaveDCAEUUIDDictionary: exit"); + } + + @Test + public void testRemoveDCAEUUIDDictionary() { + logger.info("testRemoveDCAEUUIDDictionary: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " + + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," + + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," + + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " + + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," + + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " + + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; + BufferedReader br = new BufferedReader(new StringReader(jsonString)); + when(request.getReader()).thenReturn(br); + controller.removeMicroServiceConfigNameDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceCongigNameDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testRemoveDCAEUUIDDictionary: exit"); + } + + @Test + public void testGetMicroServiceConfigNameByNameDictionaryEntityData() { + logger.info("testGetMicroServiceConfigNameByNameDictionaryEntityData: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + + controller.getMicroServiceConfigNameByNameDictionaryEntityData(request, response); + + try { + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceCongigNameDictionaryDatas")); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + } catch (UnsupportedEncodingException e) { + fail("Exception: " + e); + } + + logger.info("testGetMicroServiceConfigNameByNameDictionaryEntityData: exit"); + } + + @Test + public void testGetMicroServiceConfigNameDictionaryEntityData() { + logger.info("testGetMicroServiceConfigNameByNameDictionaryEntityData: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + + controller.getMicroServiceConfigNameDictionaryEntityData(request, response); + + try { + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceCongigNameDictionaryDatas")); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + } catch (UnsupportedEncodingException e) { + fail("Exception: " + e); + } + + logger.info("testGetMicroServiceConfigNameDictionaryEntityData: exit"); + } + + @Test + public void testSaveMicroServiceConfigNameDictionary() { + logger.info("testSaveMicroServiceConfigNameDictionary: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + jsonString = "{\"microServiceCongigNameDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " + + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," + + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," + + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " + + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," + + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " + + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; + BufferedReader br = new BufferedReader(new StringReader(jsonString)); + when(request.getReader()).thenReturn(br); + controller.saveMicroServiceConfigNameDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceCongigNameDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testSaveMicroServiceConfigNameDictionary: exit"); + } + + @Test + public void testRemoveMicroServiceConfigNameDictionary() { + logger.info("testRemoveMicroServiceConfigNameDictionary: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " + + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," + + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," + + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " + + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," + + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " + + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; + BufferedReader br = new BufferedReader(new StringReader(jsonString)); + when(request.getReader()).thenReturn(br); + controller.removeMicroServiceConfigNameDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceCongigNameDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testRemoveMicroServiceConfigNameDictionary: exit"); + } + + @Test + public void testGetMicroServiceLocationByNameDictionaryEntityData() { + + logger.info("testGetMicroServiceLocationByNameDictionaryEntityData: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + + controller.getMicroServiceLocationByNameDictionaryEntityData(request, response); + + try { + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas")); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + } catch (UnsupportedEncodingException e) { + fail("Exception: " + e); + } + + logger.info("testGetMicroServiceLocationByNameDictionaryEntityData: exit"); + } + + @Test + public void testGetMicroServiceLocationDictionaryEntityData() { + logger.info("testGetMicroServiceLocationDictionaryEntityData: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + + controller.getMicroServiceLocationDictionaryEntityData(request, response); + + try { + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas")); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + } catch (UnsupportedEncodingException e) { + fail("Exception: " + e); + } + + logger.info("testGetMicroServiceLocationDictionaryEntityData: exit"); + } + + @Test + public void testSaveMicroServiceLocationDictionary() { + logger.info("testSaveMicroServiceLocationDictionary: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + jsonString = "{\"microServiceLocationDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " + + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," + + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," + + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " + + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," + + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " + + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; + BufferedReader br = new BufferedReader(new StringReader(jsonString)); + when(request.getReader()).thenReturn(br); + controller.saveMicroServiceLocationDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testSaveMicroServiceLocationDictionary: exit"); + } + + @Test + public void testRemoveMicroServiceLocationDictionary() { + logger.info("testRemoveMicroServiceLocationDictionary: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " + + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," + + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," + + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " + + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," + + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " + + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; + BufferedReader br = new BufferedReader(new StringReader(jsonString)); + + when(request.getReader()).thenReturn(br); + controller.removeMicroServiceLocationDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceLocationDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testRemoveMicroServiceLocationDictionary: exit"); + } + + @Test + public void testGetMicroServiceAttributeByNameDictionaryEntityData() { + logger.info("testGetMicroServiceAttributeByNameDictionaryEntityData: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + + controller.getMicroServiceAttributeByNameDictionaryEntityData(request, response); + + try { + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas")); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + } catch (UnsupportedEncodingException e) { + fail("Exception: " + e); + } + + logger.info("testGetMicroServiceAttributeByNameDictionaryEntityData: exit"); + } + + @Test + public void testGetMicroServiceAttributeDictionaryEntityData() { + logger.info("testGetMicroServiceAttributeDictionaryEntityData: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + + controller.getMicroServiceAttributeDictionaryEntityData(request, response); + + try { + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas")); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + } catch (UnsupportedEncodingException e) { + fail("Exception: " + e); + } + + logger.info("testGetMicroServiceAttributeDictionaryEntityData: exit"); + } + + @Test + public void testSaveMicroServiceAttributeDictionary() { + logger.info("testSaveMicroServiceAttributeDictionary: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + jsonString = "{\"modelAttributeDictionaryData\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " + + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," + + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," + + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " + + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," + + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " + + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; + BufferedReader br = new BufferedReader(new StringReader(jsonString)); + when(request.getReader()).thenReturn(br); + controller.saveMicroServiceAttributeDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testSaveMicroServiceAttributeDictionary: exit"); + } + + @Test + public void testRemoveMicroServiceAttributeDictionary() { + logger.info("testRemoveMicroServiceAttributeDictionary: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " + + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," + + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," + + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " + + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," + + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " + + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; + BufferedReader br = new BufferedReader(new StringReader(jsonString)); + when(request.getReader()).thenReturn(br); + controller.removeMicroServiceAttributeDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceAttributeDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testRemoveMicroServiceAttributeDictionary: exit"); + } + + @Test + public void testGetMicroServiceModelsDictionaryByNameEntityData() { + logger.info("testGetMicroServiceModelsDictionaryByNameEntityData: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + + controller.getMicroServiceModelsDictionaryByNameEntityData(request, response); + + try { + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas")); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + } catch (UnsupportedEncodingException e) { + fail("Exception: " + e); + } + + logger.info("testGetMicroServiceModelsDictionaryByNameEntityData: exit"); + } + + @Test + public void testGetMicroServiceModelsDictionaryByVersionEntityData() { + logger.info("testGetMicroServiceModelsDictionaryByVersionEntityData: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}"; + + BufferedReader br = new BufferedReader(new StringReader(msModelJson)); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + when(request.getReader()).thenReturn(br); + controller.getMicroServiceModelsDictionaryByVersionEntityData(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("No model name given")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testGetMicroServiceModelsDictionaryByVersionEntityData: exit"); + } + + @Test + public void testGetMicroServiceModelsDictionaryEntityData() { + logger.info("testGetMicroServiceModelsDictionaryEntityData: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}"; + + BufferedReader br = new BufferedReader(new StringReader(msModelJson)); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + when(request.getReader()).thenReturn(br); + controller.getMicroServiceModelsDictionaryEntityData(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testGetMicroServiceModelsDictionaryEntityData: exit"); + } + + @Test + public void testGetMicroServiceModelsDictionaryEntityDataServiceVersion() { + logger.info("testGetMicroServiceModelsDictionaryEntityDataServiceVersion: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}"; + + BufferedReader br = new BufferedReader(new StringReader(msModelJson)); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + when(request.getReader()).thenReturn(br); + controller.getMicroServiceModelsDictionaryEntityDataServiceVersion(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testGetMicroServiceModelsDictionaryEntityDataServiceVersion: exit"); + } + + @Test + public void testGetMicroServiceModelsDictionaryClassEntityData() { + logger.info("testGetMicroServiceModelsDictionaryClassEntityData: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + String msModelJson = "{\"microServiceModelsDictionaryData\":[\"modelName\"]}"; + + BufferedReader br = new BufferedReader(new StringReader(msModelJson)); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + when(request.getReader()).thenReturn(br); + controller.getMicroServiceModelsDictionaryClassEntityData(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryClassDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testGetMicroServiceModelsDictionaryClassEntityData: exit"); + } + + @Test + public void testSaveMicroServiceModelsDictionary() { + logger.info("testSaveMicroServiceModelsDictionary: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + when(request.getReader()).thenReturn(br); + controller.saveMicroServiceModelsDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testSaveMicroServiceModelsDictionary: exit"); + } + + @Test + public void testRemoveMicroServiceModelsDictionary() { + logger.info("testRemoveMicroServiceModelsDictionary: Entering"); + + MockHttpServletResponse response = new MockHttpServletResponse(); + request = mock(HttpServletRequest.class); + + try { + // mock the getReader() call + jsonString = "{\"data\": {\"modelName\": \"test\", \"inprocess\": false,\"model\": {\"name\": \"testingdata\", " + + " \"subScopename\": \"\",\"path\": [],\"type\": \"dir\",\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", " + + " \"version\": \"\",\"createdBy\": \"someone\", \"modifiedBy\": \"someone\", \"content\": \"\",\"recursive\": false}," + + " \"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\" }," + + " \"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\",\"policyName\": \"may1501\", " + + " \"policyDescription\": \"testing input\", \"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\",\"riskLevel\": \"2\"," + + " \"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\",\"version\": \"1707.41.02\",\"ruleGridData\": [ [\"fileId\"]],\"ttlDate\": null}}, " + + " \"policyJSON\": {\"pmTableName\": \"test\", \"dmdTopic\": \"1\",\"fileId\": \"56\"} }"; + + BufferedReader br = new BufferedReader(new StringReader(jsonString)); + when(request.getReader()).thenReturn(br); + controller.removeMicroServiceModelsDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("microServiceModelsDictionaryDatas")); + + } catch (Exception e) { + fail("Exception: " + e); + } + + logger.info("testRemoveMicroServiceModelsDictionary: exit"); + } + +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java new file mode 100644 index 000000000..8b4c73abd --- /dev/null +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java @@ -0,0 +1,803 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.pap.xacml.rest.jpa; + +import static org.junit.Assert.*; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.junit.*; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.jpa.ActionBodyEntity; +import org.onap.policy.rest.jpa.ConfigurationDataEntity; +import org.onap.policy.rest.jpa.PolicyDBDaoEntity; +import org.onap.policy.rest.jpa.PolicyEntity; + +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; +import javax.persistence.Query; + +import java.util.Date; +import java.util.List; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +import java.util.Properties; + +public class PolicyEntityTest { + + private static Logger logger = FlexLogger.getLogger(PolicyEntityTest.class); + + @Test + public void testAllOps(){ + Properties properties = new Properties(); + properties.put(XACMLRestProperties.PROP_PAP_DB_DRIVER,"org.h2.Driver"); + properties.put(XACMLRestProperties.PROP_PAP_DB_URL, "jdbc:h2:file:./sql/xacmlTest"); + properties.put(XACMLRestProperties.PROP_PAP_DB_USER, "sa"); + properties.put(XACMLRestProperties.PROP_PAP_DB_PASSWORD, ""); + EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPapPU", properties); + EntityManager em = emf.createEntityManager(); + // Start a transaction + EntityTransaction et = em.getTransaction(); + + et.begin(); + //Make sure the DB is clean + em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate(); + em.createQuery("DELETE FROM PolicyEntity").executeUpdate(); + em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate(); + em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate(); + + //Create a policy object + PolicyEntity p1 = new PolicyEntity(); + + //persist the policy + em.persist(p1); + + long policyId1 = p1.getPolicyId(); + + String policyName1 = p1.getPolicyName(); + + int version1 = p1.getVersion(); + + String policyData1 = p1.getPolicyData(); + + ConfigurationDataEntity configData1 = p1.getConfigurationData(); + String configDataStr1 = (configData1!=null ? "configurationDataId = " + configData1.getConfigurationDataId() : "configurationData is null"); + + ActionBodyEntity actionBody1 = p1.getActionBodyEntity(); + String actionBodyStr1 = (actionBody1!=null ? "actionBodyId = " + actionBody1.getActionBodyId() : "actionBody is null"); + + String createdBy1 = p1.getCreatedBy(); + + Date createdDate1 = p1.getCreatedDate(); + String createdDateStr1 = (createdDate1 != null ? createdDate1.toString() : "createdDate is null"); + + String description = p1.getDescription(); + + String modifiedBy1 = p1.getModifiedBy(); + + Date modifiedDate1 = p1.getModifiedDate(); + String modifiedDateStr1 = (modifiedDate1 != null ? modifiedDate1.toString() : "modifiedDate is null"); + + + logger.debug("\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects before persist*********" + + "\npolicyId1 = " + policyId1 + + "\npolicyName1 = " + policyName1 + + "\nversion1 = " + version1 + + "\npolicyData1 = " + policyData1 + + "\nconfigDataStr1 = " + configDataStr1 + + "\nactionBodyStr1 = " + actionBodyStr1 + + "\nscope = " + p1.getScope() + + "\ncreatedBy1 = " + createdBy1 + + "\ncreatedDateStr1 = " + createdDateStr1 + + "\ndescription = " + description + + "\nmodifiedBy1 = " + modifiedBy1 + + "\nmodifiedDateStr1 = " + modifiedDateStr1 + + "\ndeleted = " + p1.isDeleted()); + + //Set policyID + p1.setPolicyName("testPID2"); + + //Set policyData + p1.setPolicyData("PolicyData"); + + //We will NOT set the ConfigurationDataEntity or ActionBodyEntity object just to test that it is optional + + //set createdBy + p1.setCreatedBy("kevin"); + + //createdDate will be set when it is persisted + + //set scope + p1.setScope("mckiou.kevin"); + + //set description + p1.setDescription("PolicyEntity Description"); + + //set modifiedBy + p1.setModifiedBy("kevin"); + + //modifiedDate will be set when it is persisted + + //Flush to the DB + em.flush(); + + //Now lets get some attribute values + + policyId1 = p1.getPolicyId(); + + policyName1 = p1.getPolicyName(); + + version1 = p1.getVersion(); + + policyData1 = p1.getPolicyData(); + + configData1 = p1.getConfigurationData(); + configDataStr1 = (configData1!=null ? "configurationDataId = " + configData1.getConfigurationDataId() : "configurationData is null"); + + actionBody1 = p1.getActionBodyEntity(); + actionBodyStr1 = (actionBody1!=null ? "actionBodyId = " + actionBody1.getActionBodyId() : "actionBody is null"); + + createdBy1 = p1.getCreatedBy(); + + createdDate1 = p1.getCreatedDate(); + createdDateStr1 = (createdDate1 != null ? createdDate1.toString() : "createdDate is null"); + + description = p1.getDescription(); + + modifiedBy1 = p1.getModifiedBy(); + + modifiedDate1 = p1.getModifiedDate(); + modifiedDateStr1 = (modifiedDate1 != null ? modifiedDate1.toString() : "modifiedDate is null"); + + logger.debug("\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects after persist*********" + + "\npolicyId1 = " + policyId1 + + "\npolicyName1 = " + policyName1 + + "\nversion1 = " + version1 + + "\npolicyData1 = " + policyData1 + + "\nconfigDataStr1 = " + configDataStr1 + + "\nactionBodyStr1 = " + actionBodyStr1 + + "\nscopeId = " + p1.getScope() + + "\ncreatedBy1 = " + createdBy1 + + "\ncreatedDateStr1 = " + createdDateStr1 + + "\ndescription = " + description + + "\nmodifiedBy1 = " + modifiedBy1 + + "\nmodifiedDateStr1 = " + modifiedDateStr1 + + "\ndeleted = " + p1.isDeleted()); + + //Now lets fully configure the configurationData and actionBody + + //Create a ConfigurationDataEntity object and set ID + ConfigurationDataEntity c1 = new ConfigurationDataEntity(); + + ActionBodyEntity a1 = new ActionBodyEntity(); + + //persist the configuration Data + em.persist(c1); + + c1.setConfigType("OTHER"); + + c1.setConfigBody("ABC"); + + c1.setDescription("ConfigurationDataEntity Description"); + + c1.setCreatedBy("kevin"); + + //c1.setModifiedBy("kevin"); + + c1.setDeleted(true); + + //persist the action Body + + em.persist(a1); + + a1.setActionBody("myActionBody"); + + a1.setActionBodyName("myActionBodyName"); + + a1.setCreatedBy("kevin"); + + a1.setModifiedBy("kevin"); + + a1.setDeleted(false); + + + long configurationDataId = c1.getConfigurationDataId(); + + int cdVersion = c1.getVersion(); + + String cdConfigType = c1.getConfigType(); + + String cdConfigBody = c1.getConfigBody(); + + String cdCreatedBy = c1.getCreatedBy(); + + Date cdCreatedDate = c1.getCreatedDate(); + + String cdDescription = c1.getDescription(); + + String cdModifiedBy = c1.getModifiedBy(); + + Date cdModifiedDate = c1.getModifiedDate(); + + logger.debug("\n\n********PolicyEntityTest: Local Configuration object after setting values *********" + + "\nconfigurationDataId = " + configurationDataId + + "\ncdVersion = " + cdVersion + + "\ncdConfigType = " + cdConfigType + + "\ncdConfigBody = " + cdConfigBody + + "\ncdCreatedBy = " + cdCreatedBy + + "\ncdCreatedDate = " + cdCreatedDate + + "\ncdDescription = " + cdDescription + + "\ncdModifiedBy = " + cdModifiedBy + + "\ncdModifiedDate = " + cdModifiedDate + + "\ndeleted = " + c1.isDeleted()); + + + + logger.debug("\n\n********PolicyEntityTest: Local Action Body object after setting values *********" + + "\nactionBodyId = " + a1.getActionBodyId() + + "\nactionBodyVersion = " + a1.getVersion() + + "\nactionBody = " + a1.getActionBody() + + "\nactionBodyCeatedBy = " + a1.getCreatedBy() + + "\nactionBodyCreatedDate = " + a1.getCreatedDate() + + "\nactionBodyModifiedBy = " + a1.getModifiedBy() + + "\nactionBodyModifiedDate = " + a1.getModifiedDate() + + "\nactionBodyDeleted = " + a1.isDeleted()); + + p1.setScope("mckiou.kevin.kim"); + + //flush to the db + em.flush(); + + //Perform policy selects + + Query query = em.createQuery("Select p from PolicyEntity p where p.policyId=:pid"); + Query queryscope = em.createQuery("Select p from PolicyEntity p where p.scope=:s"); + + query.setParameter("pid", p1.getPolicyId()); + queryscope.setParameter("s", "mckiou.kevin.kim"); + + //Just test that we are retrieving the right object + @SuppressWarnings("rawtypes") + List psList = queryscope.getResultList(); + PolicyEntity px = null; + if(!psList.isEmpty()){ + //ignores multiple results + px = (PolicyEntity) psList.get(0); + }else{ + fail("\nPolicyEntityTest: No PolicyEntity using scope DB entry found"); + } + + //The scope object on the retrieved policy object should be same as the one we used to find it + assertSame(p1,px); + + + //Because getSingleResult() throws an unchecked exception which is an indication of a + //programming error, we are not going to use it. + @SuppressWarnings("rawtypes") + List resultList = query.getResultList(); + PolicyEntity p2 = null; + if(!resultList.isEmpty()){ + // ignores multiple results + p2 = (PolicyEntity) resultList.get(0); + }else{ + fail("\nPolicyEntityTest: No PolicyEntity DB entry found"); + } + + logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB BEFORE assigning configurationData*********" + + "\npolicyId2 = " + p2.getPolicyId() + + "\npolicyName2 = " + p2.getPolicyName() + + "\nversion2 = " + p2.getVersion() + + "\npolicyData2 = " + p2.getPolicyData() + + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null") + + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null") + + "\nscope2 = " + p2.getScope() + + "\ncreatedBy2 = " + p2.getCreatedBy() + + "\ncreatedDate2 = " + p2.getCreatedDate() + + "\ndescription2 = " + p2.getDescription() + + "\nmodifiedBy2 = " + p2.getModifiedBy() + + "\nmodifiedDate2 = " + p2.getModifiedDate() + + "\ndeleted2 = " + p2.isDeleted()); + + //Confirm that the retrieved policy object is the same as the persisted object + assertSame(p1,p2); + + //Perform configurationData selects + Query query2 = em.createQuery("Select c from ConfigurationDataEntity c where c.configurationDataId=:cid"); + + query2.setParameter("cid", c1.getConfigurationDataId()); + + //Get the database version of the Configuration Data + resultList = query2.getResultList(); + ConfigurationDataEntity c2 = null; + if(!resultList.isEmpty()){ + // ignores multiple results + c2 = (ConfigurationDataEntity) resultList.get(0); + }else{ + fail("\nPolicyEntityTest: No ConfigurationDataEntity DB entry found"); + } + + logger.debug("\n\n********PolicyEntityTest: Configuration object after retrieving from DB BEFORE assigning to policy*********" + + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() + + "\nversion2 = " + c2.getVersion() + + "\nconfigType2 = " + c2.getConfigType() + + "\nconfigBody2 = " + c2.getConfigBody() + + "\ncreatedBy2 = " + c2.getCreatedBy() + + "\ncreatedDate2 = " + c2.getCreatedDate() + + "\ndescription2 = " + c2.getDescription() + + "\nmodifiedBy2 = " + c2.getModifiedBy() + + "\nmodifiedDate2 = " + c2.getModifiedDate() + + "\ndeleted2 = " + c2.isDeleted()); + + //Confirm the retrieved ConfigurationDataEntity object is the same as the persisted + assertSame(c1,c2); + + //Now assign the configurationData to the policy + p1.setConfigurationData(c1); + + //Perform actionBody selects + Query querya2 = em.createQuery("Select a from ActionBodyEntity a where a.actionBodyId=:aid"); + + querya2.setParameter("aid", a1.getActionBodyId()); + + //Get the database version of the Action Body + resultList = querya2.getResultList(); + ActionBodyEntity a2 = null; + if(!resultList.isEmpty()){ + // ignores multiple results + a2 = (ActionBodyEntity) resultList.get(0); + }else{ + fail("\nPolicyEntityTest: No ActionBodyEntity DB entry found"); + } + + + logger.debug("\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB BEFORE assigning to policy *********" + + "\nactionBodyId2 = " + a2.getActionBodyId() + + "\nactionBodyVersion2 = " + a2.getVersion() + + "\nactionBody2 = " + a2.getActionBody() + + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() + + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() + + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy() + + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() + + "\nactionBodyDeleted2 = " + a2.isDeleted()); + + + //Confirm the retrieved ActionBodyEntity object is the same as the persisted + assertSame(a1,a2); + + //Now assign the ActionBodyEntity to the policy + p1.setActionBodyEntity(a1); + + em.flush(); + + //Let's retrieve the policy, configurationData and actionBody from the DB and look at them + //Here is the policy object + resultList = query.getResultList(); + p2 = null; + if(!resultList.isEmpty()){ + // ignores multiple results + p2 = (PolicyEntity) resultList.get(0); + }else{ + fail("PolicyEntityTest: No PolicyEntity DB entry found"); + } + + logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB AFTER assigning configurationData*********" + + "\npolicyId2 = " + p2.getPolicyId() + + "\npolicyName2 = " + p2.getPolicyName() + + "\nversion2 = " + p2.getVersion() + + "\npolicyData2 = " + p2.getPolicyData() + + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null") + + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null") + + "\nscope2 = " + p2.getScope() + + "\ncreatedBy2 = " + p2.getCreatedBy() + + "\ncreatedDate2 = " + p2.getCreatedDate() + + "\ndescription2 = " + p2.getDescription() + + "\nmodifiedBy2 = " + p2.getModifiedBy() + + "\nmodifiedDate2 = " + p2.getModifiedDate() + + "\ndeleted2 = " + p2.isDeleted()); + + //And now the ConfigurationDataEntity object + resultList = query2.getResultList(); + c2 = null; + if(!resultList.isEmpty()){ + // ignores multiple results + c2 = (ConfigurationDataEntity) resultList.get(0); + }else{ + fail("\nPolicyEntityTest: No ConfigurationDataEntity DB entry found"); + } + + logger.debug("\n\n********PolicyEntityTest: Configuration object after retrieving from DB AFTER assigning to policy*********" + + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() + + "\nversion2 = " + c2.getVersion() + + "\nconfigType2 = " + c2.getConfigType() + + "\nconfigBody2 = " + c2.getConfigBody() + + "\ncreatedBy2 = " + c2.getCreatedBy() + + "\ncreatedDate2 = " + c2.getCreatedDate() + + "\ndescription2 = " + c2.getDescription() + + "\nmodifiedBy = " + c2.getModifiedBy() + + "\nmodifiedDate = " + c2.getModifiedDate() + + "\ndeleted2 = " + c2.isDeleted()); + + + //Get the database version of the Action Body + resultList = querya2.getResultList(); + a2 = null; + if(!resultList.isEmpty()){ + // ignores multiple results + a2 = (ActionBodyEntity) resultList.get(0); + }else{ + fail("\nPolicyEntityTest: No ActionBodyEntity DB entry found"); + } + + + logger.debug("\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB AFTER assigning to policy *********" + + "\nactionBodyId2 = " + a2.getActionBodyId() + + "\nactionBodyVersion2 = " + a2.getVersion() + + "\nactionBody2 = " + a2.getActionBody() + + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() + + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() + + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy() + + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() + + "\nactionBodyDeleted2 = " + a2.isDeleted()); + + + //****Now lets see if the orphanRemoval=true does anything useful*** + //Remove the configurationData from the policy relationship + + p1.setConfigurationData(null); + + p1.setActionBodyEntity(null); + + //flush the update to the DB + em.flush(); + + //Attempt to retrieve the configuration data object from the db. It should not be there + //Reusing the previous query + resultList = query2.getResultList(); + c2 = null; + if(resultList.isEmpty()){ + logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******" + + "\n Success!! No ConfigurationDataEntity DB entry found"); + + }else{ + c2 = (ConfigurationDataEntity) resultList.get(0); + fail("\nPolicyEntityTest: ConfigurationDataEntity DB entry found - and none should exist" + + "\nconfigurationDataId = " + c2.getConfigurationDataId()); + } + + //Attempt to retrieve the actionBody data object from the db. It should not be there + //Reusing the previous query + resultList = querya2.getResultList(); + a2 = null; + if(resultList.isEmpty()){ + logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******" + + "\n Success!! No ActionBodyEntity DB entry found"); + + }else{ + a2 = (ActionBodyEntity) resultList.get(0); + fail("\nPolicyEntityTest: ActionBodyEntity DB entry found - and none should exist" + + "\nactionBodyId = " + a2.getActionBodyId()); + } + + //Now lets put the configurationData and actionBody back into the policy object and see what appears + //in the DB after a flush + + //put c1 back into the persistence context since the orphanRemoval removed it. + em.persist(c1); + p1.setConfigurationData(c1); + + em.persist(a1); + p1.setActionBodyEntity(a1); + + em.flush(); + + //retrieve the policy object + resultList = query.getResultList(); + p2 = null; + if(!resultList.isEmpty()){ + // ignores multiple results + p2 = (PolicyEntity) resultList.get(0); + }else{ + fail("\nPolicyEntityTest: No PolicyEntity DB entry found"); + } + + //output what we policy object found + logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after again adding ConfigurationDataEntity and retrieving from DB*********" + + "\npolicyId2 = " + p2.getPolicyId() + + "\npolicyName2 = " + p2.getPolicyName() + + "\nversion2 = " + p2.getVersion() + + "\npolicyData2 = " + p2.getPolicyData() + + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null") + + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null") + + "\nscope2 = " + p2.getScope() + + "\ncreatedBy2 = " + p2.getCreatedBy() + + "\ncreatedDate2 = " + p2.getCreatedDate() + + "\ndescription2 = " + p2.getDescription() + + "\nmodifiedBy2 = " + p2.getModifiedBy() + + "\nmodifiedDate2 = " + p2.getModifiedDate() + + "\ndeleted2 = " + p2.isDeleted()); + + + //now lets see if it put the configurationData c1 back into the table + resultList = query2.getResultList(); + c2 = null; + if(!resultList.isEmpty()){ + // ignores multiple results + c2 = (ConfigurationDataEntity) resultList.get(0); + }else{ + fail("\nPolicyEntityTest - Check re-entry of configurationData into DB" + + "No ConfigurationDataEntity DB entry found"); + } + + //output what configurationData object we found + logger.debug("\n\n********PolicyEntityTest: Configuration object after re-enter into policy object and retrieving from DB *********" + + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() + + "\nversion2 = " + c2.getVersion() + + "\nconfigType2 = " + c2.getConfigType() + + "\nconfigBody2 = " + c2.getConfigBody() + + "\ncreatedBy2 = " + c2.getCreatedBy() + + "\ncreatedDate2 = " + c2.getCreatedDate() + + "\ndescription2 = " + c2.getDescription() + + "\nmodifiedBy = " + c2.getModifiedBy() + + "\nmodifiedDate = " + c2.getModifiedDate() + + "\ndeleted2 = " + c2.isDeleted()); + + //now lets see if it put the actionBody a1 back into the table + //Get the database version of the Action Body + resultList = querya2.getResultList(); + a2 = null; + if(!resultList.isEmpty()){ + // ignores multiple results + a2 = (ActionBodyEntity) resultList.get(0); + }else{ + fail("\nPolicyEntityTest - Check re-entry of actionBody into DB" + + "No ActionBodyEntity DB entry found"); + } + + logger.debug("\n\n********PolicyEntityTest: Local Action Body object after re-enter into policy object and retrieving from DB *********" + + "\nactionBodyId2 = " + a2.getActionBodyId() + + "\nactionBodyVersion2 = " + a2.getVersion() + + "\nactionBody2 = " + a2.getActionBody() + + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() + + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() + + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy() + + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() + + "\nactionBodyDeleted2 = " + a2.isDeleted()); + + //I want to save all the above in the DB + try{ + et.commit(); + logger.debug("\n\n***********PolicyEntityTest: et.commit Succeeded********"); + }catch(Exception e){ + logger.debug("\n\n***********PolicyEntityTest: et.commit Failed********" + + "\nTRANSACTION ROLLBACK " + + "\n with exception: " + e); + } + + // Start a new transaction + EntityTransaction et2 = em.getTransaction(); + + et2.begin(); + + //Let's test if the PolicyEntity uniqueConstraint for policyName and scopeId hold + PolicyEntity p3 = new PolicyEntity(); + em.persist(p3); + + + //first let's assure that you can save with the same name but a different scope + p3.setPolicyName(p1.getPolicyName()); + p3.setScope("mckiou.kevin.kory"); + em.flush(); + logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********" + + "\nSuccess! PolicyEntity uniqueness constraint allowed " + + "\n policyId1 " + p1.getPolicyId() + + "\n policyName1 " + p1.getPolicyName() + + "\n scope1 = " + p1.getScope() + + "\n policyId3 " + p3.getPolicyId() + + "\n policyName3 " + p3.getPolicyName() + + "\n scope3 = " + p3.getScope()); + + //Assert that the policyIds are NOT the same to show that the automatic sequencing is working + assert(p1.getPolicyId() != p3.getPolicyId()); + + try{ + //Now set the scope the same to verify the uniqueness constraint will be enforced + p3.setScope(p1.getScope()); + + em.flush(); + logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********" + + "\nFailed! PolicyEntity Uniqueness constraint FAILED and DID allow " + + "\n policyId1 " + p1.getPolicyId() + + "\n policyName1 " + p1.getPolicyName() + + "\n scope1 = " + p1.getScope() + + "\n policyId3 " + p3.getPolicyId() + + "\n policyName3 " + p3.getPolicyName() + + "\n scope3 = " + p3.getScope());; + } + catch(Exception e){ + //Success + logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********" + + "\nSuccess! PolicyEntity Uniqueness constraint SUCCEEDED and did NOT allow " + + "\n policyId1 " + p1.getPolicyId() + + "\n policyName1 " + p1.getPolicyName() + + "\n scope1 = " + p1.getScope() + + "\n policyId3 " + p3.getPolicyId() + + "\n policyName3 " + p3.getPolicyName() + + "\n scope3 = " + p3.getScope() + + "\n with excpetion: " + e); + } + + + try{ + et2.commit(); + logger.debug("\n\n***********PolicyEntityTest: et2.commit Succeeded********"); + }catch(Exception e){ + logger.debug("\n\n***********PolicyEntityTest: et2.commit Failed********" + + "\nTRANSACTION ROLLBACK " + + "\n with exception: " + e); + } + + //****************Test the PolicyDBDaoEntity************************ + + //Create a transaction + EntityTransaction et3 = em.getTransaction(); + + et3.begin(); + + //create one + PolicyDBDaoEntity pe1 = new PolicyDBDaoEntity(); + em.persist(pe1); + + pe1.setDescription("This is pe1"); + + pe1.setPolicyDBDaoUrl("http://123.45.2.456:2345"); + + //push it to the DB + em.flush(); + + //create another + PolicyDBDaoEntity pe2 = new PolicyDBDaoEntity(); + em.persist(pe2); + + pe2.setDescription("This is pe2"); + + pe2.setPolicyDBDaoUrl("http://789.01.2.345:2345"); + + //Print them to the log before flushing + logger.debug("\n\n***********PolicyEntityTest: PolicyDBDaoEntity objects before flush********" + + "\n policyDBDaoUrl-1 = " + pe1.getPolicyDBDaoUrl() + + "\n description-1 = " + pe1.getDescription() + + "\n createdDate-1 = " + pe1.getCreatedDate() + + "\n modifiedDate-1 " + pe1.getModifiedDate() + + "\n*****************************************" + + "\n policyDBDaoUrl-2 = " + pe2.getPolicyDBDaoUrl() + + "\n description-2 = " + pe2.getDescription() + + "\n createdDate-2 = " + pe2.getCreatedDate() + + "\n modifiedDate-2 " + pe2.getModifiedDate() + ); + + //push it to the DB + em.flush(); + + //Now let's retrieve them from the DB using the named query + + resultList = em.createNamedQuery("PolicyDBDaoEntity.findAll").getResultList(); + + PolicyDBDaoEntity pex = null; + PolicyDBDaoEntity pey = null; + + if(!resultList.isEmpty()){ + if (resultList.size() != 2){ + fail("\nPolicyEntityTest: Number of PolicyDBDaoEntity entries = " + resultList.size() + " instead of 2"); + } + for(Object policyDBDaoEntity: resultList){ + PolicyDBDaoEntity pdbdao = (PolicyDBDaoEntity)policyDBDaoEntity; + if(pdbdao.getPolicyDBDaoUrl().equals("http://123.45.2.456:2345")){ + pex = pdbdao; + }else if(pdbdao.getPolicyDBDaoUrl().equals("http://789.01.2.345:2345")){ + pey = pdbdao; + } + } + + //Print them to the log before flushing + logger.debug("\n\n***********PolicyEntityTest: PolicyDBDaoEntity objects retrieved from DB********" + + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl() + + "\n description-x = " + pex.getDescription() + + "\n createdDate-x = " + pex.getCreatedDate() + + "\n modifiedDate-x " + pex.getModifiedDate() + + "\n*****************************************" + + "\n policyDBDaoUrl-y = " + pey.getPolicyDBDaoUrl() + + "\n description-y = " + pey.getDescription() + + "\n createdDate-y = " + pey.getCreatedDate() + + "\n modifiedDate-y " + pey.getModifiedDate() + ); + //Verify the retrieved objects are the same as the ones we stored in the DB + if(pex.getPolicyDBDaoUrl().equals("http://123.45.2.456:2345")){ + assertSame(pe1,pex); + assertSame(pe2,pey); + }else{ + assertSame(pe2,pex); + assertSame(pe1,pey); + } + + }else{ + fail("\nPolicyEntityTest: No PolicyDBDaoEntity DB entry found"); + } + + //Now let's see if we can do an update on the PolicyDBDaoEntity which we retrieved. + //em.persist(pex); + pex.setDescription("This is pex"); + em.flush(); + + //retrieve it + Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyDBDaoEntity p WHERE p.description=:desc"); + resultList = createPolicyQuery.setParameter("desc", "This is pex").getResultList(); + + PolicyDBDaoEntity pez = null; + + if(!resultList.isEmpty()){ + if (resultList.size() != 1){ + fail("\nPolicyEntityTest: Update Test - Number of PolicyDBDaoEntity entries = " + resultList.size() + " instead of 1"); + } + pez = (PolicyDBDaoEntity) resultList.get(0); + + //Print them to the log before flushing + logger.debug("\n\n***********PolicyEntityTest: Update Test - PolicyDBDaoEntity objects retrieved from DB********" + + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl() + + "\n description-x = " + pex.getDescription() + + "\n createdDate-x = " + pex.getCreatedDate() + + "\n modifiedDate-x " + pex.getModifiedDate() + + "\n*****************************************" + + "\n policyDBDaoUrl-z = " + pez.getPolicyDBDaoUrl() + + "\n description-z = " + pez.getDescription() + + "\n createdDate-z = " + pez.getCreatedDate() + + "\n modifiedDate-z " + pez.getModifiedDate() + ); + //Verify the retrieved objects are the same as the ones we stored in the DB + assertSame(pex,pez); + }else{ + fail("\nPolicyEntityTest: Update Test - No PolicyDBDaoEntity DB updated entry found"); + } + + //Clean up the DB + em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate(); + em.createQuery("DELETE FROM PolicyEntity").executeUpdate(); + em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate(); + em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate(); + + //Wrap up the transaction + try{ + et3.commit(); + logger.debug("\n\n***********PolicyEntityTest: et3.commit Succeeded********"); + }catch(Exception e){ + logger.debug("\n\n***********PolicyEntityTest: et3.commit Failed********" + + "\nTRANSACTION ROLLBACK " + + "\n with exception: " + e); + } + + + //Tidy up + em.close(); + } + +} diff --git a/ONAP-PAP-REST/test.properties b/ONAP-PAP-REST/test.properties new file mode 100644 index 000000000..65a9363ee --- /dev/null +++ b/ONAP-PAP-REST/test.properties @@ -0,0 +1,22 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PAP-REST +# ================================================================================ +# 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========================================================= +### + +PDP_URL=http://localhost:8082/pdp/, testpdp, alpha456 +#PAP_URL=http://localhost:8070/pap/, testpap, alpha123 diff --git a/ONAP-PAP-REST/xacml.pap.properties b/ONAP-PAP-REST/xacml.pap.properties new file mode 100644 index 000000000..b0fa954a8 --- /dev/null +++ b/ONAP-PAP-REST/xacml.pap.properties @@ -0,0 +1,165 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PAP-REST +# ================================================================================ +# 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========================================================= +### +#=====================================================================================# +#================The Below Properties are default, shouldn't change them==============# +#=====================================================================================# +# +# This is our factory that will create our engine +# +xacml.PAP.papEngineFactory=org.onap.policy.xacml.std.pap.StdEngineFactory +# Dictionary and Policy Implementation Classes Properties +dictionary.impl.className=org.onap.policy.pap.xacml.rest.handler.DictionaryHandlerImpl +savePolicy.impl.className=org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler +pushPolicy.impl.className=org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler +deletePolicy.impl.className=org.onap.policy.pap.xacml.rest.handler.DeleteHandler +#AutoPush Policy +xacml.rest.pap.autopush.file=autopush.properties +#=====================================================================================# +#===============The Below Properties will be changed based on Environment=============# +#=====================================================================================# +# +# Where we store our PAP PDP Group/Node information +# +xacml.pap.pdps=pdps +# +# Need the PAP's url (how PDPs will reach it) configured here +# because we need it to generate the URLs of the Policy Files +# sent to the PDPs in the configuration when the PAP is first brought up. +# (In other cases, such as the PDP calling the PAP, we could generate this URL, +# but for startup there is no other way to get it.) +# +# +xacml.rest.pap.url=http://localhost:8070/pap/ + +# +# Upon startup, have the PAP servlet send latest configuration information to all +# the PDP nodes it knows about. +# +xacml.rest.pap.initiate.pdp=true +# +# Heartbeat from PAP to PDPs +# +# How much time (in milliseconds) between heartbeats +# (i.e. the time between completing the heartbeat with all PDPs and starting the next cycle) +# +xacml.rest.pap.heartbeat.interval=100000 +# +# Heartbeat connection timeout (in milliseconds) +# +xacml.rest.pap.heartbeat.timeout=100000 + +# new Property Please mention your PAP-REST webapps Location here. +xacml.rest.config.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ + +#Turn the audit on to synchronize the DB/file system +#xacml.rest.pap.run.audit.flag=true +#Turn the audit off to not synchronize the DB/file system +#xacml.rest.pap.run.audit.flag=false +xacml.rest.pap.run.audit.flag=true + +#Audit will synchronize the file system to match the contents of the DB +#xacml.rest.pap.filesystem.audit=true +#Audit will synchronize the DB to match the contents of the file system +#xacml.rest.pap.filesystem.audit=false +xacml.rest.pap.filesystem.audit=false +xacm.xcor.required.pattern=1,1 +# id +xacml.rest.pap.userid=testpap +# pass +xacml.rest.pap.password=alpha123 +# pdps file +xacml.rest.pdp.idfile=test.properties + +#Properties for db access +#properties for MySql xacml database: PLEASE DO NOT REMOVE... NEEDED FOR APIs +javax.persistence.jdbc.driver=com.mysql.jdbc.Driver +javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/onap_sdk?failOverReadOnly=false&autoReconnect=true +javax.persistence.jdbc.user=policy_user +javax.persistence.jdbc.password=policy_user + +#Time in ms which a Policy DB transaction will wait to get the transaction lock object +xacml.rest.pap.transaction.waitms=500000 + +#Policy DB transaction timeout in ms after it has obtained the transaction lock object +xacml.rest.pap.transaction.timeoutms=500000 + +#Policy Audit timeout in ms after it has obtained the transaction lock object +xacml.rest.pap.audit.timeoutms=500000 + +#controls how long the pap will wait before giving up when sending notifications to other paps +xacml.rest.pap.notify.timeoutms=10000 + +#the number of times an incoming policy update notification will be tried to be processed (or until it succeeds) +xacml.rest.pap.incomingnotification.tries=4 + +#AutoPush Policy Flag +xacml.rest.pap.autopush.flag=false + +#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java*** + +#The name of the PAP. Must be unique across the system +xacml.rest.pap.resource.name=site_1.pap_1 + +#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** + +#Interval between forward progress counter updates in seconds +fp_monitor_interval=30 + +#Number of forward progress counter failures before failover +failed_counter_threshold=3 + +#Interval in seconds between test transactions if there is no other traffic +test_trans_interval=10 + +#Interval in seconds between updates of the forward progress counter in the DB +write_fpc_interval=5 + +#Name of the site +site_name=site_1 + +#Node type. Can take values of: pdp-xacml, pdp-drools, pap, pap-admin, logparser, brms-gateway, +#astra-gateway, elk-server +node_type=pap + +#Dependency groups are groups of resources upon which a node operational state is dependent upon (dependency_groups). +#Each group is a comma-separated list of resource names and groups are separated by a semicolon. A group may contain +#one or more members. +dependency_groups=site_1.logparser_1;site_1.adminconsole_1;site_1.elk_1 + +# The (optional) period of time in seconds between executions of the integrity audit. +# Value < 0 : Audit does not run (default value if property is not present = -1) +# Value = 0 : Audit runs continuously +# Value > 0 : The period of time in seconds between execution of the audit on a particular node +integrity_audit_period_seconds=-1 + +ENVIRONMENT=DEVL + +# +#PolicySafetyChecker properties +# +#Turn safetyChecker on/off +xacml.rest.pap.safetychecker=on +PDP_URL1 = http://localhost:8082/pdp/, testpdp, alpha456 +CLIENT_ID= +CLIENT_KEY= + +#Micro Service Model Properties +xacml.policy.msOnapName=http://org.onap +xacml.policy.msPolicyName=http://org.onap.policy \ No newline at end of file diff --git a/ONAP-PAP-REST/xacml.pap.test.properties b/ONAP-PAP-REST/xacml.pap.test.properties new file mode 100644 index 000000000..fe9559591 --- /dev/null +++ b/ONAP-PAP-REST/xacml.pap.test.properties @@ -0,0 +1,145 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PAP-REST +# ================================================================================ +# 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========================================================= +### +#=====================================================================================# +#================The Below Properties are default, shouldn't change them==============# +#=====================================================================================# +# +# This is our factory that will create our engine +# +xacml.PAP.papEngineFactory=org.onap.policy.xacml.std.pap.StdEngineFactory +# Dictionary and Policy Implementation Classes Properties +dictionary.impl.className=org.onap.policy.pap.xacml.rest.handler.DictionaryHandlerImpl +savePolicy.impl.className=org.onap.policy.pap.xacml.rest.handler.SavePolicyHandler +pushPolicy.impl.className=org.onap.policy.pap.xacml.rest.handler.PushPolicyHandler +deletePolicy.impl.className=org.onap.policy.pap.xacml.rest.handler.DeleteHandler +#AutoPush Policy +xacml.rest.pap.autopush.file=autopush.properties +#=====================================================================================# +#===============The Below Properties will be changed based on Environment=============# +#=====================================================================================# +# +# Where we store our PAP PDP Group/Node information +# +xacml.pap.pdps=pdps +# +# Need the PAP's url (how PDPs will reach it) configured here +# because we need it to generate the URLs of the Policy Files +# sent to the PDPs in the configuration when the PAP is first brought up. +# (In other cases, such as the PDP calling the PAP, we could generate this URL, +# but for startup there is no other way to get it.) +# +# +xacml.rest.pap.url=http://localhost:8070/pap/ +# +# Upon startup, have the PAP servlet send latest configuration information to all +# the PDP nodes it knows about. +# +xacml.rest.pap.initiate.pdp=true +# +# Heartbeat from PAP to PDPs +# +# How much time (in milliseconds) between heartbeats +# (i.e. the time between completing the heartbeat with all PDPs and starting the next cycle) +# +xacml.rest.pap.heartbeat.interval=10000 +# +# Heartbeat connection timeout (in milliseconds) +# +xacml.rest.pap.heartbeat.timeout=10000 + +# new Property Please mention your PAP-REST webapps Location here. +xacml.rest.config.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ + +#Turn the audit on to synchronize the DB/file system +#xacml.rest.pap.run.audit.flag=true +#Turn the audit off to not synchronize the DB/file system +#xacml.rest.pap.run.audit.flag=false +xacml.rest.pap.run.audit.flag=false + +#Audit will synchronize the file system to match the contents of the DB +#xacml.rest.pap.filesystem.audit=true +#Audit will synchronize the DB to match the contents of the file system +#xacml.rest.pap.filesystem.audit=false +xacml.rest.pap.filesystem.audit=false + +# id +xacml.rest.pap.userid=testpap +# pass +xacml.rest.pap.password=alpha123 +# pdps file +xacml.rest.pdp.idfile=test.properties + +#Properties for db access +javax.persistence.jdbc.driver=org.h2.Driver +javax.persistence.jdbc.url=jdbc:h2:file:./sql/xacmlTest +javax.persistence.jdbc.user=sa +javax.persistence.jdbc.password= + +#Time in ms which a Policy DB transaction will wait to get the transaction lock object +xacml.rest.pap.transaction.waitms=1000 + +#Policy DB transaction timeout in ms after it has obtained the transaction lock object +xacml.rest.pap.transaction.timeoutms=500 + +#Policy Audit timeout in ms after it has obtained the transaction lock object +xacml.rest.pap.audit.timeoutms=5000 + +#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** + +#JMX URL for the PAP-REST. Need to update to real IP and port +xacml.rest.pap.jmx.url=service:jmx:rmi:///jndi/rmi://localhost:9990/jmxrmi + +#The name of the PAP. Must be unique across the system +xacml.rest.pap.resource.name=site_1.pap_1 + +#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** + +#Interval between forward progress counter updates in seconds +fp_monitor_interval=30 + +#Number of forward progress counter failures before failover +failed_counter_threshold=3 + +#Interval in seconds between test transactions if there is no other traffic +test_trans_interval=10 + +#Interval in seconds between updates of the forward progress counter in the DB +write_fpc_interval=5 + +#Name of the site +site_name=site_1 + +#Node type. Can take values of: pdp-xacml, pdp-drools, pap, pap-admin, logparser, brms-gateway, +#astra-gateway, elk-server +node_type=pap + +#Dependency groups are groups of resources upon which a node operational state is dependent upon (dependency_groups). +#Each group is a comma-separated list of resource names and groups are separated by a semicolon. A group may contain +#one or more members. +dependency_groups=site_1.logparser_1;site_1.adminconsole_1;site_1.elk_1 + +# The (optional) period of time in seconds between executions of the integrity audit. +# Value < 0 : Audit does not run (default value if property is not present = -1) +# Value = 0 : Audit runs continuously +# Value > 0 : The period of time in seconds between execution of the audit on a particular node +#integrity_audit_period_seconds=-1 +integrity_audit_period_seconds=0 + +ENVIRONMENT=DEVL diff --git a/ECOMP-PDP-REST/.gitignore b/ONAP-PDP-REST/.gitignore similarity index 100% rename from ECOMP-PDP-REST/.gitignore rename to ONAP-PDP-REST/.gitignore diff --git a/ECOMP-PDP-REST/WebContent/META-INF/MANIFEST.MF b/ONAP-PDP-REST/WebContent/META-INF/MANIFEST.MF similarity index 100% rename from ECOMP-PDP-REST/WebContent/META-INF/MANIFEST.MF rename to ONAP-PDP-REST/WebContent/META-INF/MANIFEST.MF diff --git a/ECOMP-PDP-REST/WebContent/WEB-INF/.gitignore b/ONAP-PDP-REST/WebContent/WEB-INF/.gitignore similarity index 100% rename from ECOMP-PDP-REST/WebContent/WEB-INF/.gitignore rename to ONAP-PDP-REST/WebContent/WEB-INF/.gitignore diff --git a/ECOMP-PDP-REST/client.properties b/ONAP-PDP-REST/client.properties similarity index 100% rename from ECOMP-PDP-REST/client.properties rename to ONAP-PDP-REST/client.properties diff --git a/ONAP-PDP-REST/config/policyLogger.properties b/ONAP-PDP-REST/config/policyLogger.properties new file mode 100644 index 000000000..a04f4eef8 --- /dev/null +++ b/ONAP-PDP-REST/config/policyLogger.properties @@ -0,0 +1,44 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP-REST +# ================================================================================ +# 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========================================================= +### + +################################### Set concurrentHashMap and timer info ####################### +#Timer initial delay and the delay between in milliseconds before task is to be execute. +timer.delay.time=1000 +#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. +check.interval= 30000 +#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. +event.expired.time=86400 +#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed +#to remove all expired records from this concurrentHashMap. +concurrentHashMap.limit=5000 +#Size of the concurrentHashMap - when its size drops to this point, stop the Timer +stop.check.point=2500 +################################### Set logging format ############################################# +# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println +logger.type=EELF +#################################### Set level for EELF or SYSTEMOUT logging ################################## +# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all +debugLogger.level=INFO +# Set level for metrics file. Set OFF to disable; set ON to enable +metricsLogger.level=ON +# Set level for error file. Set OFF to disable; set ON to enable +error.level=ON +# Set level for audit file. Set OFF to disable; set ON to enable +audit.level=ON diff --git a/ECOMP-PDP-REST/config/xacml.pip.properties b/ONAP-PDP-REST/config/xacml.pip.properties similarity index 100% rename from ECOMP-PDP-REST/config/xacml.pip.properties rename to ONAP-PDP-REST/config/xacml.pip.properties diff --git a/ECOMP-PDP-REST/config/xacml.policy.properties b/ONAP-PDP-REST/config/xacml.policy.properties similarity index 100% rename from ECOMP-PDP-REST/config/xacml.policy.properties rename to ONAP-PDP-REST/config/xacml.policy.properties diff --git a/ONAP-PDP-REST/policyLogger.properties b/ONAP-PDP-REST/policyLogger.properties new file mode 100644 index 000000000..a04f4eef8 --- /dev/null +++ b/ONAP-PDP-REST/policyLogger.properties @@ -0,0 +1,44 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP-REST +# ================================================================================ +# 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========================================================= +### + +################################### Set concurrentHashMap and timer info ####################### +#Timer initial delay and the delay between in milliseconds before task is to be execute. +timer.delay.time=1000 +#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. +check.interval= 30000 +#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. +event.expired.time=86400 +#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed +#to remove all expired records from this concurrentHashMap. +concurrentHashMap.limit=5000 +#Size of the concurrentHashMap - when its size drops to this point, stop the Timer +stop.check.point=2500 +################################### Set logging format ############################################# +# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println +logger.type=EELF +#################################### Set level for EELF or SYSTEMOUT logging ################################## +# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all +debugLogger.level=INFO +# Set level for metrics file. Set OFF to disable; set ON to enable +metricsLogger.level=ON +# Set level for error file. Set OFF to disable; set ON to enable +error.level=ON +# Set level for audit file. Set OFF to disable; set ON to enable +audit.level=ON diff --git a/ONAP-PDP-REST/pom.xml b/ONAP-PDP-REST/pom.xml new file mode 100644 index 000000000..64c036a65 --- /dev/null +++ b/ONAP-PDP-REST/pom.xml @@ -0,0 +1,223 @@ + + + + + 4.0.0 + + + org.onap.policy.engine + PolicyEngineSuite + 1.1.0-SNAPSHOT + + + ONAP-PDP-REST + + ONAP PDP REST + + 4.3.3.RELEASE + + war + + + + maven-war-plugin + 2.1 + + true + + + + + + + org.onap.policy.engine + ONAP-PDP + ${project.version} + + + commons-logging + commons-logging + 1.1.3 + + + javax.servlet + servlet-api + + + + + log4j + apache-log4j-extras + 1.2.17 + + + commons-io + commons-io + 2.4 + + + com.google.guava + guava + 19.0 + + + mysql + mysql-connector-java + 5.1.30 + + + org.mariadb.jdbc + mariadb-java-client + 1.2.3 + + + postgresql + postgresql + 9.1-901.jdbc4 + + + org.springframework + spring-test + ${springframework.version} + test + + + org.awaitility + awaitility + 3.0.0 + test + + + org.hsqldb + hsqldb + 2.3.2 + + + com.sun.jersey + jersey-client + 1.18 + + + com.sun.jersey + jersey-core + 1.18 + + + junit + junit + 4.12 + test + + + javax.websocket + javax.websocket-api + 1.1 + provided + + + com.att.nsa + cambriaClient + 0.0.1 + + + slf4j-log4j12 + org.slf4j + + + + + org.mockito + mockito-core + 1.9.5 + + + org.springframework + spring-mock + 2.0.8 + + + com.mockrunner + mockrunner + 0.3.1 + + + org.powermock + powermock-api-mockito + 1.5.6 + + + org.powermock + powermock-module-junit4 + 1.5.6 + + + org.springframework + spring-core + ${springframework.version} + + + org.springframework + spring-web + ${springframework.version} + + + org.springframework + spring-webmvc + ${springframework.version} + + + io.springfox + springfox-swagger2 + 2.5.0 + + + com.fasterxml.jackson.core + jackson-annotations + + + + + io.springfox + springfox-swagger-ui + 2.5.0 + + + org.onap.policy.engine + PolicyEngineAPI + ${project.version} + + + org.glassfish.tyrus + tyrus-client + + + org.glassfish.tyrus + tyrus-container-grizzly-client + + + javax.persistence + persistence-api + + + + + \ No newline at end of file diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java new file mode 100644 index 000000000..cee07fd9f --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java @@ -0,0 +1,377 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest; + +import java.net.URI; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.NoSuchElementException; +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 com.att.research.xacml.util.XACMLProperties; + +public class PapUrlResolver { + private static final Logger LOGGER = FlexLogger.getLogger(PapUrlResolver.class); + //how long to keep a pap failed before making it un-failed, in milli-seconds + private static final long FAIL_TIMEOUT = 18000000; + + //thread locks + public static final Object propertyLock = new Object(); + + //keeping this here for backward compatibility + public static String extractIdFromUrl(String url){ + return extractQuery(url); + } + public static String extractQuery(String url){ + try{ + return URI.create(url).getQuery(); + } catch(Exception e){ + LOGGER.error("Exception occured while extracting query. So, empty string is returned"+e); + return ""; + } + } + public static String modifyUrl(String idUrl, String serverUrl){ + URI one = URI.create(idUrl); + String host = one.getPath()+one.getQuery(); + URI two = URI.create(serverUrl); + two.resolve(host); + return two.toString(); + } + + //get an instance of a new PapUrlResolver, using XACMLProperties to get the url lists + public static PapUrlResolver getInstance(){ + return new PapUrlResolver(null,null,null,true); + } + + //get an instance of a new PapUrlResolver, using the provides strings for the url lists + public static PapUrlResolver getInstance(String urlList, String failedList, String succeededList){ + return new PapUrlResolver(urlList, failedList, succeededList,false); + } + + //keeps track of our current location in the list of urls, allows for iterating + private int pointer; + + //should the XACML property lists be updated after anything changes or should we wait for the update + //method to be called. + private boolean autoUpdateProperties; + + //this list keeps the sorted, priority of PAP URLs + private PapUrlNode[] sortedUrlNodes; + //this list keeps the original list of nodes so that they can be entered into the property list correctly + private PapUrlNode[] originalUrlNodes; + + //private constructor to make an instance of a PapUrlResolver, called by static method getInstance. + //If the list property strings are not defined, we get the values from XACMLProperties. + //The instance acts as an iterator, with hasNext and next methods, but does not implement Iterable, + //because it is used for a difference purpose. + private PapUrlResolver(String urlList, String failedList, String succeededList, boolean autoUpdateProperties){ + this.autoUpdateProperties = autoUpdateProperties; + String papUrlLists = urlList; + String papUrlFailedList = failedList; + String papUrlSuccessList = succeededList; + if(papUrlLists == null){ + papUrlLists = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS); + if(papUrlLists == null){ + papUrlLists = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + } + papUrlFailedList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); + papUrlSuccessList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); + } + + String[] urls = papUrlLists.split(","); + if(urls.length == 0){ + //log error + } + String[] failed = emptyOrSplit(papUrlFailedList,urls.length); + String[] succeeded = emptyOrSplit(papUrlSuccessList,urls.length); + + sortedUrlNodes = new PapUrlNode[urls.length]; + for(int i=0;i { + private String papUrl; + private Date failedTime; + private Date succeededTime; + private String userId; + private String pass; + + public PapUrlNode(String url,String userId,String pass){ + this.papUrl = url; + failedTime = null; + this.succeededTime = null; + this.userId = userId; + this.pass = pass; + + } + public String getUserId(){ + return this.userId; + } + public String getPass(){ + return this.pass; + } + + public void setFailedTime(Object time){ + Date failedTimeAsDate = setHandler(time); + if(failedTimeAsDate == null){ + this.failedTime = null; + } else { + long timeDifference = new Date().getTime() - failedTimeAsDate.getTime(); + if(timeDifference < FAIL_TIMEOUT){ + this.failedTime = failedTimeAsDate; + } else { + this.failedTime = null; + } + } + } + + //set the time that this url succeeded at + public void setSucceededTime(Object time){ + this.succeededTime = setHandler(time); + } + + //parses string into a date or a null date, if the url never failed/succeeded (since -1 will be in the property) + private Date setHandler(Object time){ + if(time instanceof String){ + if("-1".equals((String)time)){ + return null; + } + try { + DateFormat df = new SimpleDateFormat(); + return df.parse((String)time); + } catch (ParseException e) { + return null; + } + } + if(time instanceof Date){ + return (Date)time; + } + return null; + } + + + public String getFailedTime(){ + return formatTime(this.failedTime); + } + + public String getSucceededTime(){ + return formatTime(this.succeededTime); + } + + //formats a Date into a string or a -1 if there is not date (-1 is used in properties for no date) + private String formatTime(Date d){ + if(d == null){ + return "-1"; + } + DateFormat df = new SimpleDateFormat(); + return df.format(d); + } + + public String getUrl(){ + return papUrl; + } + + @Override + public int compareTo(PapUrlNode other){ + if(this.failedTime == null && other.failedTime != null){ + return -1; + } + if(this.failedTime != null && other.failedTime == null){ + return 1; + } + if(this.failedTime != null){ + return this.failedTime.compareTo(other.failedTime); + } + return 0; + } + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpLoader.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpLoader.java new file mode 100644 index 000000000..7526af692 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpLoader.java @@ -0,0 +1,645 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest; + +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Base64; +import java.util.ConcurrentModificationException; +import java.util.HashMap; +import java.util.Properties; +import java.util.Set; + +import org.apache.commons.io.IOUtils; +import org.onap.policy.pdp.rest.notifications.NotificationController; +import org.onap.policy.rest.XACMLRest; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +import org.onap.policy.xacml.api.XACMLErrorConstants; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPStatus; +import com.att.research.xacml.api.pap.PDPStatus.Status; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.api.pdp.PDPEngineFactory; +import com.att.research.xacml.api.pip.PIPEngine; +import com.att.research.xacml.api.pip.PIPException; +import com.att.research.xacml.api.pip.PIPFinder; +import com.att.research.xacml.api.pip.PIPFinderFactory; +import org.onap.policy.xacml.std.pap.StdPDPPIPConfig; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; +import org.onap.policy.xacml.std.pap.StdPDPStatus; +import com.att.research.xacml.util.FactoryException; +import com.att.research.xacml.util.XACMLProperties; +import com.att.research.xacmlatt.pdp.policy.PolicyDef; +import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef; +import com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory; +import com.google.common.base.Splitter; + +/** + * Does the work for loading policy and PIP configurations sent from the PAP + * servlet. + * + * + * + */ +public class XACMLPdpLoader { + private static final Logger LOGGER = FlexLogger.getLogger(XACMLPdpLoader.class); + private static NotificationController notificationController = new NotificationController(); + private static final Long notifyDelay = (long) XACMLPdpServlet.getNotificationDelay(); + + + public static synchronized PDPEngine loadEngine(StdPDPStatus status, + Properties policyProperties, Properties pipProperties) { + LOGGER.info("loadEngine: " + policyProperties + " " + pipProperties); + // + // First load our policies + // + try { + // + // Were we given some properties? + // + if (policyProperties == null) { + // + // On init we have no incoming configuration, so just + // Load our current saved configuration + // + policyProperties = new Properties(); + try (InputStream is = Files.newInputStream(getPDPPolicyCache())) { + policyProperties.load(is); + } + } + + // + // Get our policy cache up-to-date + // + // Side effects of this include: + // - downloading of policies from remote locations, and + // - creating new ".file" properties for files existing + // local + // + XACMLPdpLoader.cachePolicies(policyProperties); + // + // Validate the policies + // + XACMLPdpLoader.validatePolicies(policyProperties, status); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Status: " + status); + } + } catch (ConcurrentModificationException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e.getMessage() + e); + } catch (Exception e) { + String error = "Failed to load Policy Cache properties file: " + + e.getMessage(); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + error, e); + status.addLoadError(error); + status.setStatus(PDPStatus.Status.LOAD_ERRORS); + } + // + // Load our PIP configuration + // + try { + // + // Were we given some properties to use? + // + if (pipProperties == null) { + // + // Load our current saved configuration + // + pipProperties = new Properties(); + try (InputStream is = Files.newInputStream(getPIPConfig())) { + pipProperties.load(is); + } + } + // + // Validate our PIP configurations + // + XACMLPdpLoader.validatePipConfiguration(pipProperties, status); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Status: " + status); + } + } catch (Exception e) { + String error = "Failed to load/validate Pip Config properties file: " + + e.getMessage(); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + error, e); + status.addLoadError(XACMLErrorConstants.ERROR_PROCESS_FLOW + error); + status.setStatus(PDPStatus.Status.LOAD_ERRORS); + } + // + // Were they validated? + // + if (status.getStatus() == Status.LOAD_ERRORS) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW +"there were load errors"); + return null; + } + // + // Reset our official properties the PDP factory + // uses to configure the PDP engine. + // + XACMLRest.loadXacmlProperties(policyProperties, pipProperties); + // + // Dump ALL our properties that we are trying to load + // + try { + LOGGER.info(XACMLProperties.getProperties().toString()); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to get XACML Properties", e); + } + // + // Now load the PDP engine + // + PDPEngineFactory factory = null; + PDPEngine engine = null; + try { + factory = PDPEngineFactory.newInstance(); + engine = factory.newEngine(); + LOGGER.info("Loaded new PDP engine."); + status.setStatus(Status.UP_TO_DATE); + } catch (FactoryException e) { + String error = "Failed to create new PDP Engine"; + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +error, e); + status.addLoadError(error); + } + // Notification will be Sent Here. + sendNotification(); + return engine; + } + + private static HashMap policyContainer = null; + + private static void sendNotification(){ + Thread notify = new Thread(){ + public void run(){ + try{ + Thread.sleep(notifyDelay); + NotificationController.sendNotification(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_UNKNOWN + e); + } + } + }; + notify.start(); + } + + public static synchronized void validatePolicies(Properties properties, + StdPDPStatus status) throws PAPException { + Set rootPolicies = XACMLProperties.getRootPolicyIDs(properties); + Set refPolicies = XACMLProperties + .getReferencedPolicyIDs(properties); + policyContainer = new HashMap(); + + for (String id : rootPolicies) { + loadPolicy(properties, status, id, true); + } + // remember which policies were root policies + status.addAllLoadedRootPolicies(status.getLoadedPolicies()); + + for (String id : refPolicies) { + loadPolicy(properties, status, id, false); + } + LOGGER.info("Loaded " + status.getLoadedPolicies().size() + + " policies, failed to load " + + status.getFailedPolicies().size() + " policies, " + + status.getLoadedRootPolicies().size() + " root policies"); + notificationController.check(status, policyContainer); + if (status.getLoadedRootPolicies().size() == 0) { + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW +"NO ROOT POLICIES LOADED!!! Cannot serve PEP Requests."); + status.addLoadWarning("NO ROOT POLICIES LOADED!!! Cannot serve PEP Requests."); + } + policyContainer.clear(); + } + + + public static synchronized void loadPolicy(Properties properties, + StdPDPStatus status, String id, boolean isRoot) throws PAPException { + PolicyDef policy = null; + String location = null; + URI locationURI = null; + boolean isFile = false; + boolean rougeFile = false; + try { + location = properties.getProperty(id + ".file"); + if(location != null){ + isFile = true; + locationURI = Paths.get(location).toUri(); + try (InputStream is = Files.newInputStream(Paths.get(location))) { + policy = DOMPolicyDef.load(is); + } catch (Exception e){ + // This Happens if a any issue with the error policyFile. Lets remove it. + try { + LOGGER.error("Corrupted policy file, deleting: " + location + e); + Files.delete(Paths.get(location)); + properties.remove(id + ".file"); + rougeFile = true; + } catch (IOException e1) { + LOGGER.error(e1); + } + } + } + if(location==null || rougeFile){ + if(rougeFile){ + rougeFile = false; + } + location = properties.getProperty(id + ".url"); + if (location != null) { + // + // Construct the URL + // + int errorCount=0; + boolean error= false; + do{ + error=false; + PapUrlResolver papUrls = PapUrlResolver.getInstance(); + while(papUrls.hasMoreUrls()){ + String papID = papUrls.getUserId(); + String papPass = papUrls.getPass(); + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); + locationURI = URI.create(papUrls.getUrl(PapUrlResolver.extractIdFromUrl(location))); + URL url = locationURI.toURL(); + URLConnection urlConnection = null; + try{ + urlConnection = url.openConnection(); + } catch (IOException e){ + LOGGER.error("Exception Occured while opening connection" +e); + papUrls.failed(); + papUrls.getNext(); + break; + } + urlConnection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID, + XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID)); + urlConnection.setRequestProperty("Authorization", "Basic " + encoding); + // + // Now construct the output file name + // + Path outFile = Paths.get(getPDPConfig().toAbsolutePath() + .toString(), id); + // + // Copy it to disk + // + try (FileOutputStream fos = new FileOutputStream( + outFile.toFile())) { + IOUtils.copy(urlConnection.getInputStream(), fos); + } catch(IOException e){ + LOGGER.error("Exception Occured while Copying input stream" +e); + papUrls.failed(); + papUrls.getNext(); + break; + } + // + // Now try to load + // + isFile = true; + try (InputStream fis = Files.newInputStream(outFile)) { + policy = DOMPolicyDef.load(fis); + }catch(Exception e){ + try { + LOGGER.error("Corrupted policy file, deleting: " + location +e); + Files.delete(outFile); + error = true; + errorCount++; + break; + } catch (IOException e1) { + LOGGER.error(e1); + } + } + // + // Save it + // + properties.setProperty(id + ".file", outFile + .toAbsolutePath().toString()); + error = false; + break; + } + }while(error && errorCount>2); + } + } + if (policy != null) { + status.addLoadedPolicy(new StdPDPPolicy(id, isRoot, + locationURI, properties)); + LOGGER.info("Loaded policy: " + policy.getIdentifier() + + " version: " + policy.getVersion().stringValue()); + // Sending the policy objects to the Notification Controller. + policyContainer.put(id, policy); + } else { + String error = "Failed to load policy " + location; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + error); + status.setStatus(PDPStatus.Status.LOAD_ERRORS); + status.addLoadError(error); + status.addFailedPolicy(new StdPDPPolicy(id, isRoot)); + } + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW +"Failed to load policy '" + id + "' from location '" + + location + "'", e); + status.setStatus(PDPStatus.Status.LOAD_ERRORS); + status.addFailedPolicy(new StdPDPPolicy(id, isRoot)); + // + // Is it a file? + // + if (isFile) { + // + // Let's remove it + // + try { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Corrupted policy file, deleting: " + location); + Files.delete(Paths.get(location)); + + } catch (IOException e1) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e1); + } + } + } + } + + public static synchronized void validatePipConfiguration( + Properties properties, StdPDPStatus status) throws PAPException { + try { + PIPFinderFactory factory = PIPFinderFactory.newInstance(properties); + if (factory == null) { + throw new FactoryException( + "Could not create PIP Finder Factory: " + + properties + .getProperty(XACMLProperties.PROP_PIPFINDERFACTORY)); + } + PIPFinder finder = factory.getFinder(properties); + // + // Check for this, although it should always return something + // + if (finder == null) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "pip finder factory returned a null engine."); + throw new PIPException("Could not create PIP Finder"); + } else { + LOGGER.info("Loaded PIP finder"); + } + for (PIPEngine engine : finder.getPIPEngines()) { + LOGGER.info("Configured PIP Engine: " + engine.getName()); + StdPDPPIPConfig config = new StdPDPPIPConfig(); + config.setName(engine.getName()); + status.addLoadedPipConfig(config); + } + } catch (FactoryException | PIPException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "validate PIP configuration failed: " + + e.getLocalizedMessage()); + status.addLoadError(e.getLocalizedMessage()); + status.setStatus(Status.LOAD_ERRORS); + throw new PAPException(e); + } + } + + /** + * Iterates the policies defined in the props object to ensure they are + * loaded locally. Policies are searched for in the following order: - see + * if the current properties has a "<PolicyID>.file" entry and that + * file exists in the local directory - if not, see if the file exists in + * the local directory; if so create a ".file" property for it. - if not, + * get the "<PolicyID>.url" property and try to GET the policy from + * that location (and set the ".file" property) + * + * If the ".file" property is created, then true is returned to tell the + * caller that the props object changed. + * + * @param props + * @return true/false if anything was changed in the props object + * @throws PAPException + */ + public static synchronized boolean cachePolicies(Properties props) + throws PAPException { + boolean changed = false; + String[] lists = new String[2]; + lists[0] = props.getProperty(XACMLProperties.PROP_ROOTPOLICIES); + lists[1] = props.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); + for (String list : lists) { + // + // Check for a null or empty parameter + // + if (list == null || list.length() == 0) { + continue; + } + Iterable policies = Splitter.on(',').trimResults() + .omitEmptyStrings().split(list); + for (String policy : policies) { + boolean policyExists = false; + + // First look for ".file" property and verify the file exists + String propLocation = props.getProperty(policy + + StdPolicyFinderFactory.PROP_FILE); + if (propLocation != null) { + // + // Does it exist? + // + policyExists = Files.exists(Paths.get(propLocation)); + if (policyExists == false) { + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy file " + policy + " expected at " + + propLocation + " does NOT exist."); + } + } + + // If ".file" property does not exist, try looking for the local + // file anyway + // (it might exist without having a ".file" property set for it) + if (policyExists == false) { + // + // Now construct the output file name + // + Path outFile = Paths.get(getPDPConfig().toAbsolutePath() + .toString(), policy); + // + // Double check to see if we pulled it at some point + // + policyExists = Files.exists(outFile); + if (policyExists) { + // + // Set the property so the PDP engine doesn't have + // to pull it from the URL but rather the FILE. + // + LOGGER.info("Policy does exist: " + + outFile.toAbsolutePath().toString()); + props.setProperty(policy + + StdPolicyFinderFactory.PROP_FILE, outFile + .toAbsolutePath().toString()); + // + // Indicate that there were changes made to the + // properties + // + changed = true; + } else { + + // File does not exist locally, so we need to get it + // from the location given in the ".url" property (which + // MUST exist) + + // + // There better be a URL to retrieve it + // + propLocation = props.getProperty(policy + + StdPolicyFinderFactory.PROP_URL); + if (propLocation != null) { + // + // Get it + // + PapUrlResolver papUrls = PapUrlResolver.getInstance(); + while(papUrls.hasMoreUrls()){ + String papID = papUrls.getUserId(); + String papPass = papUrls.getPass(); + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); + URL url = null; + try { + // + // Create the URL + // + url = new URL(papUrls.getUrl(PapUrlResolver.extractIdFromUrl(propLocation))); + LOGGER.info("Pulling " + url.toString()); + // + // Open the connection + // + URLConnection urlConnection = url.openConnection(); + urlConnection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID, + XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID)); + urlConnection.setRequestProperty("Authorization", "Basic " + encoding); + // + // Copy it to disk + // + try (InputStream is = urlConnection + .getInputStream(); + OutputStream os = new FileOutputStream( + outFile.toFile())) { + IOUtils.copy(is, os); + } + // + // Now save it in the properties as a .file + // + LOGGER.info("Pulled policy: " + + outFile.toAbsolutePath().toString()); + props.setProperty(policy + + StdPolicyFinderFactory.PROP_FILE, + outFile.toAbsolutePath().toString()); + papUrls.succeeded(); + // + // Indicate that there were changes made to the + // properties + // + changed = true; + } catch (Exception e) { + papUrls.failed(); + if (e instanceof MalformedURLException) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy '" + + policy + + "' had bad URL in new configuration, URL='" + + propLocation + "'"); + + } else { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while retrieving policy " + + policy + + " from URL " + + url + ", e=" + e); + } + } + papUrls.getNext(); + } + } else { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Policy " + policy + + " does NOT exist and does NOT have a URL"); + } + } + } + } + } + return changed; + } + + public static synchronized Path getPDPPolicyCache() throws PAPException { + Path config = getPDPConfig(); + Path policyProperties = Paths.get(config.toAbsolutePath().toString(), + "xacml.policy.properties"); + if (Files.notExists(policyProperties)) { + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + policyProperties.toAbsolutePath().toString() + + " does NOT exist."); + // + // Try to create the file + // + try { + Files.createFile(policyProperties); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create policy properties file: " + + policyProperties.toAbsolutePath().toString() +e); + throw new PAPException( + "Failed to create policy properties file: " + + policyProperties.toAbsolutePath().toString()); + } + } + return policyProperties; + } + + public static synchronized Path getPIPConfig() throws PAPException { + Path config = getPDPConfig(); + Path pipConfigProperties = Paths.get( + config.toAbsolutePath().toString(), "xacml.pip.properties"); + if (Files.notExists(pipConfigProperties)) { + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + pipConfigProperties.toAbsolutePath().toString() + + " does NOT exist."); + // + // Try to create the file + // + try { + Files.createFile(pipConfigProperties); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create pip properties file: " + + pipConfigProperties.toAbsolutePath().toString() +e); + throw new PAPException("Failed to create pip properties file: " + + pipConfigProperties.toAbsolutePath().toString()); + } + } + return pipConfigProperties; + } + + public static synchronized Path getPDPConfig() throws PAPException { + Path config = Paths.get(XACMLProperties + .getProperty(XACMLRestProperties.PROP_PDP_CONFIG)); + if (Files.notExists(config)) { + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + config.toAbsolutePath().toString() + " does NOT exist."); + // + // Try to create the directory + // + try { + Files.createDirectories(config); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: " + + config.toAbsolutePath().toString(), e); + throw new PAPException("Failed to create config directory: " + + config.toAbsolutePath().toString()); + } + } + return config; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java new file mode 100644 index 000000000..14b312f6d --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpRegisterThread.java @@ -0,0 +1,285 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Base64; +import java.util.Properties; +import java.util.UUID; + +import org.apache.commons.io.IOUtils; +import org.onap.policy.pdp.rest.XACMLPdpServlet.PutRequest; +import org.onap.policy.rest.XACMLRestProperties; + +import org.onap.policy.xacml.api.XACMLErrorConstants; +import com.att.research.xacml.util.XACMLProperties; + +import org.onap.policy.common.logging.ONAPLoggingContext; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.*; + +public class XACMLPdpRegisterThread implements Runnable { + private static final Logger LOGGER = FlexLogger.getLogger(XACMLPdpRegisterThread.class); + private static final Logger auditLogger = FlexLogger.getLogger("auditLogger"); + private ONAPLoggingContext baseLoggingContext = null; + + + + public volatile boolean isRunning = false; + + public XACMLPdpRegisterThread(ONAPLoggingContext baseLoggingContext) { + this.baseLoggingContext = baseLoggingContext; + } + + public synchronized boolean isRunning() { + return this.isRunning; + } + + public synchronized void terminate() { + this.isRunning = false; + } + + /** + * + * This is our thread that runs on startup to tell the PAP server we are up-and-running. + * + */ + @Override + public void run() { + synchronized(this) { + this.isRunning = true; + } + // get a new logging context for the thread + ONAPLoggingContext loggingContext = new ONAPLoggingContext(baseLoggingContext); + loggingContext.setServiceName("PDP:PAP.register"); + //are we registered with at least one + boolean registered = false; + boolean interrupted = false; + /* + int seconds; + try { + seconds = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_SLEEP)); + } catch (NumberFormatException e) { + LOGGER.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR +"REGISTER_SLEEP: ", e); + seconds = 5; + } + if (seconds < 5) { + seconds = 5; + } + int retries; + try { + retries = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER_RETRIES)); + } catch (NumberFormatException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +" REGISTER_SLEEP: ", e); + retries = -1; + } + */ + PapUrlResolver papUrls = PapUrlResolver.getInstance(); + //while (! registered && ! interrupted && this.isRunning()) { + String tempRootPoliciesProperty = XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES); + String tempReferencedPoliciesProperty = XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); + Properties tempPipConfigProperties = new Properties(); + try(InputStream pipFile = Files.newInputStream(XACMLPdpLoader.getPIPConfig())){ + tempPipConfigProperties.load(pipFile); + } catch(Exception e){ + LOGGER.error("Failed to open PIP property file", e); + } + while(papUrls.hasMoreUrls()){ + String papID = papUrls.getUserId(); + String papPass = papUrls.getPass(); + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); + HttpURLConnection connection = null; + try { + // get a new transaction (request) ID and update the logging context. + // each time through the outer loop is considered a new transaction. + // each time through the inner loop (which handles redirects) is a + // continuation of the same transaction. + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + //PolicyLogger.info("Request Id generated in XACMLPdpRegisterThread under XACML-PDP-REST"); + loggingContext.transactionStarted(); + // + // Get the list of PAP Servlet URLs from the property file + // + //String papUrlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + //String[] papUrls = papUrlList.split(","); + //PapUrlResolver.setPapUrls(papUrls); + URL url = new URL(papUrls.getUrl()); + LOGGER.info("Registering with " + url.toString()); + //PolicyLogger.info("new transaction (request) ID and update to logging context in XACMLPdpRegisterThread"); + boolean finished = false; + while (! finished) { + // + // Open up the connection + // + connection = (HttpURLConnection)url.openConnection(); + // + // Setup our method and headers + // + connection.setRequestMethod("POST"); + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setRequestProperty("Accept", "text/x-java-properties"); + connection.setRequestProperty("Content-Type", "text/x-java-properties"); + connection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_ID, XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID)); + connection.setRequestProperty(XACMLRestProperties.PROP_PDP_HTTP_HEADER_JMX_PORT, XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_JMX_PORT)); + connection.setRequestProperty("X-ECOMP-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 { + // + // Send our current policy configuration + // + String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + tempRootPoliciesProperty; + lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + tempReferencedPoliciesProperty + "\n"; + try (InputStream listsInputStream = new ByteArrayInputStream(lists.getBytes()); + OutputStream os = connection.getOutputStream()) { + IOUtils.copy(listsInputStream, os); + + // + // Send our current PIP configuration + // + //IOUtils.copy(pipInputStream, os); + tempPipConfigProperties.store(os, ""); + } + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Failed to send property file", e); + } + // + // Do the connect + // + connection.connect(); + if (connection.getResponseCode() == 204) { + LOGGER.info("Success. We are configured correctly."); + loggingContext.transactionEnded(); + PolicyLogger.audit("Success. We are configured correctly."); + papUrls.registered(); + finished = true; + registered = true; + } else if (connection.getResponseCode() == 200) { + LOGGER.info("Success. We have a new configuration."); + loggingContext.transactionEnded(); + PolicyLogger.audit("Success. We have a new configuration."); + papUrls.registered(); + Properties properties = new Properties(); + properties.load(connection.getInputStream()); + LOGGER.info("New properties: " + properties.toString()); + // + // Queue it + // + // The incoming properties does NOT include urls + Properties returnedPolicyProperties = XACMLProperties.getPolicyProperties(properties, false); + tempRootPoliciesProperty = new String(returnedPolicyProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES)); + tempReferencedPoliciesProperty = new String(returnedPolicyProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)); + Properties returnedPipProperties = XACMLProperties.getPipProperties(properties); + Properties threadSafeReturnedPipProperties = new Properties(); + ByteArrayOutputStream threadSafeReturnedPipPropertiesOs = new ByteArrayOutputStream(); + returnedPipProperties.store(threadSafeReturnedPipPropertiesOs, ""); + InputStream threadSafeReturnedPipPropertiesIs = new ByteArrayInputStream(threadSafeReturnedPipPropertiesOs.toByteArray()); + threadSafeReturnedPipProperties.load(threadSafeReturnedPipPropertiesIs); + tempPipConfigProperties = threadSafeReturnedPipProperties; + + PutRequest req = new PutRequest(returnedPolicyProperties,returnedPipProperties); + XACMLPdpServlet.queue.offer(req); + // + // We are now registered + // + finished = true; + registered=true; + } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { + // + // Re-direction + // + String newLocation = connection.getHeaderField("Location"); + if (newLocation == null || newLocation.isEmpty()) { + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Did not receive a valid re-direction location"); + loggingContext.transactionEnded(); + auditLogger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Did not receive a valid re-direction location"); + PolicyLogger.audit("Transaction Failed - See Error.log"); + finished = true; + } else { + LOGGER.info("New Location: " + newLocation); + url = new URL(newLocation); + } + } else { + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + loggingContext.transactionEnded(); + auditLogger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + PolicyLogger.audit("Transaction Failed - See Error.log"); + finished = true; + papUrls.failed(); + } + } + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + PolicyLogger.audit("Transaction Failed - See Error.log"); + loggingContext.transactionEnded(); + papUrls.failed(); + } 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(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to get Input Stream: " + e1); + } + if (is != null) { + is.close(); + } + + } catch (IOException ex) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to close connection: " + ex, ex); + } + connection.disconnect(); + } + } + + papUrls.getNext(); + } + synchronized(this) { + this.isRunning = false; + } + LOGGER.info("Thread exiting...(registered=" + registered + ", interrupted=" + interrupted + ", isRunning=" + this.isRunning() + ", retries=" + "0" + ")"); + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java new file mode 100644 index 000000000..1e1b94d9b --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java @@ -0,0 +1,1266 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.lang.reflect.Constructor; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.nio.file.Files; +import java.util.Properties; +import java.util.UUID; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; + +import javax.servlet.Servlet; +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.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.entity.ContentType; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.im.AdministrativeStateException; +import org.onap.policy.common.im.ForwardProgressException; +import org.onap.policy.common.im.IntegrityMonitor; +import org.onap.policy.common.im.IntegrityMonitorProperties; +import org.onap.policy.common.im.StandbyStatusException; +import org.onap.policy.common.logging.ONAPLoggingContext; +import org.onap.policy.common.logging.ONAPLoggingUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.pdp.rest.jmx.PdpRestMonitor; +import org.onap.policy.rest.XACMLRest; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.pdp.std.functions.PolicyList; +import org.onap.policy.xacml.std.pap.StdPDPStatus; + +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.Response; +import com.att.research.xacml.api.pap.PDPStatus.Status; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.api.pdp.PDPException; +import com.att.research.xacml.std.dom.DOMRequest; +import com.att.research.xacml.std.dom.DOMResponse; +import com.att.research.xacml.std.json.JSONRequest; +import com.att.research.xacml.std.json.JSONResponse; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Servlet implementation class XacmlPdpServlet + * + * This is an implementation of the XACML 3.0 RESTful Interface with added features to support + * simple PAP RESTful API for policy publishing and PIP configuration changes. + * + * If you are running this the first time, then we recommend you look at the xacml.pdp.properties file. + * This properties file has all the default parameter settings. If you are running the servlet as is, + * then we recommend setting up you're container to run it on port 8080 with context "/pdp". Wherever + * the default working directory is set to, a "config" directory will be created that holds the policy + * and pip cache. This setting is located in the xacml.pdp.properties file. + * + * When you are ready to customize, you can create a separate xacml.pdp.properties on you're local file + * system and setup the parameters as you wish. Just set the Java VM System variable to point to that file: + * + * -Dxacml.properties=/opt/app/xacml/etc/xacml.pdp.properties + * + * Or if you only want to change one or two properties, simply set the Java VM System variable for that property. + * + * -Dxacml.rest.pdp.register=false + * + * + */ +@WebServlet( + description = "Implements the XACML PDP RESTful API and client PAP API.", + urlPatterns = { "/" }, + loadOnStartup=1, + initParams = { + @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pdp.properties", description = "The location of the PDP xacml.pdp.properties file holding configuration information.") + }) +public class XACMLPdpServlet extends HttpServlet implements Runnable { + private static final long serialVersionUID = 1L; + private static final String DEFAULT_MAX_CONTENT_LENGTH = "999999999"; //32767 + private static final String CREATE_UPDATE_POLICY_SERVICE = "org.onap.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl"; + // + // Our application debug log + // + private static final Log logger = LogFactory.getLog(XACMLPdpServlet.class); + // + // This logger is specifically only for Xacml requests and their corresponding response. + // It's output ideally should be sent to a separate file from the application logger. + // + private static final Log requestLogger = LogFactory.getLog("xacml.request"); + // + // audit logger + private static final Log auditLogger = LogFactory.getLog("auditLogger"); + + private static final PdpRestMonitor monitor = PdpRestMonitor.getSingleton(); + + // + // This thread may getting invoked on startup, to let the PAP know + // that we are up and running. + // + private Thread registerThread = null; + private XACMLPdpRegisterThread registerRunnable = null; + // + // This is our PDP engine pointer. There is a synchronized lock used + // for access to the pointer. In case we are servicing PEP requests while + // an update is occurring from the PAP. + // + private static PDPEngine pdpEngine = null; + private static final Object pdpEngineLock = new Object(); + // + // This is our PDP's status. What policies are loaded (or not) and + // what PIP configurations are loaded (or not). + // There is a synchronized lock used for access to the object. + // + private static volatile StdPDPStatus status = new StdPDPStatus(); + private static final Object pdpStatusLock = new Object(); + private static Constructor createUpdatePolicyConstructor; + + private static final String ENVIORNMENT_HEADER = "Environment"; + private static String environment = null; + // + // Queue of PUT requests + // + public static class PutRequest { + private Properties policyProperties = null; + private Properties pipConfigProperties = null; + + PutRequest(Properties policies, Properties pips) { + this.policyProperties = policies; + this.pipConfigProperties = pips; + } + } + protected static volatile BlockingQueue queue = null; + // For notification Delay. + private static int notificationDelay = 0; + public static int getNotificationDelay(){ + return XACMLPdpServlet.notificationDelay; + } + + private static String pdpResourceName; + private static String[] dependencyNodes = null; + + // + // This is our configuration thread that attempts to load + // a new configuration request. + // + private Thread configThread = null; + private volatile boolean configThreadTerminate = false; + private ONAPLoggingContext baseLoggingContext = null; + private IntegrityMonitor im; + /** + * Default constructor. + */ + public XACMLPdpServlet() { + //Default constructor. + } + + /** + * @see Servlet#init(ServletConfig) + */ + @Override + public void init(ServletConfig config) throws ServletException { + String createUpdateResourceName = null; + String dependencyGroups = null; + // + // Initialize + // + XACMLRest.xacmlInit(config); + // Load the Notification Delay. + try{ + XACMLPdpServlet.notificationDelay = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY)); + }catch(Exception e){ + logger.info("Notification Delay Not set. Keeping it 0 as default."+e); + } + // Load Queue size. + int queueSize = 5; // Set default Queue Size here. + queueSize = Integer.parseInt(XACMLProperties.getProperty("REQUEST_BUFFER_SIZE",String.valueOf(queueSize))); + queue = new LinkedBlockingQueue(queueSize); + // Load our engine - this will use the latest configuration + // that was saved to disk and set our initial status object. + // + PDPEngine engine = XACMLPdpLoader.loadEngine(XACMLPdpServlet.status, null, null); + if (engine != null) { + synchronized(pdpEngineLock) { + pdpEngine = engine; + } + } + // + // Logging stuff.... + // + baseLoggingContext = new ONAPLoggingContext(); + // fixed data that will be the same in all logging output goes here + try { + String ipaddress = InetAddress.getLocalHost().getHostAddress(); + baseLoggingContext.setServer(ipaddress); + } catch (UnknownHostException e) { + logger.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging"+e); + } + + Properties properties; + try { + properties = XACMLProperties.getProperties(); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, + "Error loading properties with: XACMLProperties.getProperties()"); + throw new ServletException(e.getMessage(), e.getCause()); + } + if(properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME)==null){ + XACMLProperties.reloadProperties(); + try { + properties = XACMLProperties.getProperties(); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, + "Error loading properties with: XACMLProperties.getProperties()"); + throw new ServletException(e.getMessage(), e.getCause()); + } + PolicyLogger.info("\n Properties Given : \n" + properties.toString()); + } + pdpResourceName = properties.getProperty(XACMLRestProperties.PDP_RESOURCE_NAME); + if(pdpResourceName == null){ + PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, XACMLRestProperties.PDP_RESOURCE_NAME, "xacml.pdp"); + throw new ServletException("pdpResourceName is null"); + } + + dependencyGroups = properties.getProperty(IntegrityMonitorProperties.DEPENDENCY_GROUPS); + if(dependencyGroups == null){ + PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, IntegrityMonitorProperties.DEPENDENCY_GROUPS, "xacml.pdp"); + throw new ServletException("dependency_groups is null"); + } + // dependency_groups is a semicolon-delimited list of groups, and + // each group is a comma-separated list of nodes. For our purposes + // we just need a list of dependencies without regard to grouping, + // so split the list into nodes separated by either comma or semicolon. + dependencyNodes = dependencyGroups.split("[;,]"); + for (int i = 0 ; i < dependencyNodes.length ; i++){ + dependencyNodes[i] = dependencyNodes[i].trim(); + } + + // CreateUpdatePolicy ResourceName + createUpdateResourceName = properties.getProperty("createUpdatePolicy.impl.className", CREATE_UPDATE_POLICY_SERVICE); + setCreateUpdatePolicyConstructor(createUpdateResourceName); + + // Create an IntegrityMonitor + try { + logger.info("Creating IntegrityMonitor"); + im = IntegrityMonitor.getInstance(pdpResourceName, properties); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to create IntegrityMonitor" +e); + throw new ServletException(e); + } + + environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); + // + // Kick off our thread to register with the PAP servlet. + // + if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_REGISTER))) { + this.registerRunnable = new XACMLPdpRegisterThread(baseLoggingContext); + this.registerThread = new Thread(this.registerRunnable); + this.registerThread.start(); + } + // + // This is our thread that manages incoming configuration + // changes. + // + this.configThread = new Thread(this); + this.configThread.start(); + } + + /** + * @see Servlet#destroy() + */ + @Override + public void destroy() { + super.destroy(); + logger.info("Destroying...."); + // + // Make sure the register thread is not running + // + if (this.registerRunnable != null) { + try { + this.registerRunnable.terminate(); + if (this.registerThread != null) { + this.registerThread.interrupt(); + this.registerThread.join(); + } + } catch (InterruptedException e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); + } + } + // + // Make sure the configure thread is not running + // + this.configThreadTerminate = true; + try { + this.configThread.interrupt(); + this.configThread.join(); + } catch (InterruptedException e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); + } + logger.info("Destroyed."); + } + + /** + * PUT - The PAP engine sends configuration information using HTTP PUT request. + * + * One parameter is expected: + * + * config=[policy|pip|all] + * + * policy - Expect a properties file that contains updated lists of the root and referenced policies that the PDP should + * be using for PEP requests. + * + * Specifically should AT LEAST contain the following properties: + * xacml.rootPolicies + * xacml.referencedPolicies + * + * In addition, any relevant information needed by the PDP to load or retrieve the policies to store in its cache. + * + * EXAMPLE: + * xacml.rootPolicies=PolicyA.1, PolicyB.1 + * + * PolicyA.1.url=http://localhost:9090/PAP?id=b2d7b86d-d8f1-4adf-ba9d-b68b2a90bee1&version=1 + * PolicyB.1.url=http://localhost:9090/PAP/id=be962404-27f6-41d8-9521-5acb7f0238be&version=1 + * + * xacml.referencedPolicies=RefPolicyC.1, RefPolicyD.1 + * + * RefPolicyC.1.url=http://localhost:9090/PAP?id=foobar&version=1 + * RefPolicyD.1.url=http://localhost:9090/PAP/id=example&version=1 + * + * pip - Expect a properties file that contain PIP engine configuration properties. + * + * Specifically should AT LEAST the following property: + * xacml.pip.engines + * + * In addition, any relevant information needed by the PDP to load and configure the PIPs. + * + * EXAMPLE: + * xacml.pip.engines=foo,bar + * + * foo.classname=com.foo + * foo.sample=abc + * foo.example=xyz + * ...... + * + * bar.classname=com.bar + * ...... + * + * all - Expect ALL new configuration properties for the PDP + * + * @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response) + */ + @Override + protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + loggingContext.transactionStarted(); + if ((loggingContext.getRequestID() == null) || "".equals(loggingContext.getRequestID())){ + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPut) so we generated one"); + } else { + PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPut)"); + } + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 1 of 2"); + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 2 of 2"); + // + // Dump our request out + // + if (logger.isDebugEnabled()) { + XACMLRest.dumpRequest(request); + } + + try { + im.startTransaction(); + } + catch (AdministrativeStateException | StandbyStatusException e) { + String message = e.toString(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + e); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + return; + } + // + // What is being PUT? + // + String cache = request.getParameter("cache"); + // + // Should be a list of policy and pip configurations in Java properties format + // + if (cache != null && request.getContentType().equals("text/x-java-properties")) { + loggingContext.setServiceName("PDP.putConfig"); + try{ + if (request.getContentLength() > Integer.parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", DEFAULT_MAX_CONTENT_LENGTH))) { + String message = "Content-Length larger than server will accept."; + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + loggingContext.transactionEnded(); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); + im.endTransaction(); + return; + } + this.doPutConfig(cache, request, response, loggingContext); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction ended"); + + im.endTransaction(); + }catch(Exception e){ + logger.error("Exception Occured while getting Max Content lenght"+e); + } + } else { + String message = "Invalid cache: '" + cache + "' or content-type: '" + request.getContentType() + "'"; + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + im.endTransaction(); + return; + } + } + + protected void doPutConfig(String config, HttpServletRequest request, HttpServletResponse response, ONAPLoggingContext loggingContext) throws ServletException, IOException { + try { + // prevent multiple configuration changes from stacking up + if (XACMLPdpServlet.queue.remainingCapacity() <= 0) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Queue capacity reached"); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Queue capacity reached"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_CONFLICT, "Multiple configuration changes waiting processing."); + return; + } + // + // Read the properties data into an object. + // + Properties newProperties = new Properties(); + newProperties.load(request.getInputStream()); + // should have something in the request + if (newProperties.size() == 0) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No properties in PUT"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No properties in PUT"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT must contain at least one property"); + return; + } + // + // Which set of properties are they sending us? Whatever they send gets + // put on the queue (if there is room). + // For audit logging purposes, we consider the transaction done once the + // the request gets put on the queue. + // + if (config.equals("policies")) { + newProperties = XACMLProperties.getPolicyProperties(newProperties, true); + if (newProperties.size() == 0) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policy properties in PUT"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No policy properties in PUT"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=policies must contain at least one policy property"); + return; + } + XACMLPdpServlet.queue.offer(new PutRequest(newProperties, null)); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Success"); + } else if (config.equals("pips")) { + newProperties = XACMLProperties.getPipProperties(newProperties); + if (newProperties.size() == 0) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No pips properties in PUT"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No pips properties in PUT"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=pips must contain at least one pip property"); + return; + } + XACMLPdpServlet.queue.offer(new PutRequest(null, newProperties)); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Success"); + } else if (config.equals("all")) { + Properties newPolicyProperties = XACMLProperties.getPolicyProperties(newProperties, true); + if (newPolicyProperties.size() == 0) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policy properties in PUT"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No policy properties in PUT"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one policy property"); + return; + } + Properties newPipProperties = XACMLProperties.getPipProperties(newProperties); + if (newPipProperties.size() == 0) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No pips properties in PUT"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No pips properties in PUT"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one pip property"); + return; + } + XACMLPdpServlet.queue.offer(new PutRequest(newPolicyProperties, newPipProperties)); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Success"); + } else { + // + // Invalid value + // + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid config value: " + config); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Invalid config value: " + config); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Config must be one of 'policies', 'pips', 'all'"); + return; + } + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to process new configuration.", e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to process new configuration"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + return; + } + + } + + /** + * Parameters: type=hb|config|Status + * + * 1. HeartBeat Status + * HeartBeat + * OK - All Policies are Loaded, All PIPs are Loaded + * LOADING_IN_PROGRESS - Currently loading a new policy set/pip configuration + * LAST_UPDATE_FAILED - Need to track the items that failed during last update + * LOAD_FAILURE - ??? Need to determine what information is sent and how + * 2. Configuration + * 3. Status + * return the StdPDPStatus object in the Response content + * + * + * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + loggingContext.transactionStarted(); + if ((loggingContext.getRequestID() == null) || (loggingContext.getRequestID() == "")){ + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doGet) so we generated one"); + } else { + PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doGet)"); + } + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 1 of 2"); + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 2 of 2"); + + XACMLRest.dumpRequest(request); + + String pathInfo = request.getRequestURI(); + if (pathInfo != null){ + // health check from Global Site Selector (iDNS). + // DO NOT do a im.startTransaction for the test request + if (pathInfo.equals("/pdp/test")) { + loggingContext.setServiceName("iDNS:PDP.test"); + try { + im.evaluateSanity(); + //If we make it this far, all is well + String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is OK"; + PolicyLogger.debug(message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Success"); + response.setStatus(HttpServletResponse.SC_OK); + return; + } catch (ForwardProgressException fpe){ + //No forward progress is being made + String message = "GET:/pdp/test called and PDP " + pdpResourceName + " is not making forward progress." + + " Exception Message: " + fpe.getMessage(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + fpe); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + return; + }catch (AdministrativeStateException ase){ + //Administrative State is locked + String message = "GET:/pdp/test called and PDP " + pdpResourceName + " Administrative State is LOCKED " + + " Exception Message: " + ase.getMessage(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + ase); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + return; + }catch (StandbyStatusException sse){ + //Administrative State is locked + String message = "GET:/pdp/test called and PDP " + pdpResourceName + " Standby Status is NOT PROVIDING SERVICE " + + " Exception Message: " + sse.getMessage(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + sse); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + return; + } catch (Exception e) { + //A subsystem is not making progress or is not responding + String eMsg = e.getMessage(); + if(eMsg == null){ + eMsg = "No Exception Message"; + } + String message = "GET:/pdp/test called and PDP " + pdpResourceName + " has had a subsystem failure." + + " Exception Message: " + eMsg; + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message ); + //Get the specific list of subsystems that failed + String failedNodeList = null; + for(String node : dependencyNodes){ + if(eMsg.contains(node)){ + if(failedNodeList == null){ + failedNodeList = node; + }else{ + failedNodeList = failedNodeList.concat(","+node); + } + } + } + if(failedNodeList == null){ + failedNodeList = "UnknownSubSystem"; + } + response.addHeader("X-ONAP-SubsystemFailure", failedNodeList); + try{ + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log" + e); + return; + } + } + } + + try { + im.startTransaction(); + } + catch (AdministrativeStateException | StandbyStatusException e) { + String message = e.toString(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log" +e); + try{ + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + return; + } + // + // What are they requesting? + // + boolean returnHB = false; + response.setHeader("Cache-Control", "no-cache"); + String type = request.getParameter("type"); + // type might be null, so use equals on string constants + if ("config".equals(type)) { + loggingContext.setServiceName("PDP.getConfig"); + response.setContentType("text/x-java-properties"); + try { + String lists = XACMLProperties.PROP_ROOTPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_ROOTPOLICIES, ""); + lists = lists + "\n" + XACMLProperties.PROP_REFERENCEDPOLICIES + "=" + XACMLProperties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, "") + "\n"; + try (InputStream listInputStream = new ByteArrayInputStream(lists.getBytes()); + InputStream pipInputStream = Files.newInputStream(XACMLPdpLoader.getPIPConfig()); + OutputStream os = response.getOutputStream()) { + IOUtils.copy(listInputStream, os); + IOUtils.copy(pipInputStream, os); + } + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Success"); + response.setStatus(HttpServletResponse.SC_OK); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to copy property file", e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to copy property file"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(400, "Failed to copy Property file"); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + } + + } else if ("hb".equals(type)) { + returnHB = true; + response.setStatus(HttpServletResponse.SC_NO_CONTENT); + + } else if ("Status".equals(type)) { + loggingContext.setServiceName("PDP.getStatus"); + // convert response object to JSON and include in the response + synchronized(pdpStatusLock) { + ObjectMapper mapper = new ObjectMapper(); + try{ + mapper.writeValue(response.getOutputStream(), status); + }catch(Exception e1){ + logger.error("Exception occured while writing output stream" +e1); + } + } + response.setStatus(HttpServletResponse.SC_OK); + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Success"); + + } else { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid type value: " + type); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Invalid type value: " + type); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "type not 'config' or 'hb'"); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + } + if (returnHB) { + synchronized(pdpStatusLock) { + response.addHeader(XACMLRestProperties.PROP_PDP_HTTP_HEADER_HB, status.getStatus().toString()); + } + } + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Ended"); + im.endTransaction(); + + } + + /** + * POST - We expect XACML requests to be posted by PEP applications. They can be in the form of XML or JSON according + * to the XACML 3.0 Specifications for both. + * + * + * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + ONAPLoggingContext loggingContext = ONAPLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + loggingContext.transactionStarted(); + loggingContext.setServiceName("PDP.decide"); + if ((loggingContext.getRequestID() == null) || ("".equals(loggingContext.getRequestID()))){ + UUID requestID = UUID.randomUUID(); + loggingContext.setRequestID(requestID.toString()); + PolicyLogger.info("requestID not provided in call to XACMLPdpSrvlet (doPost) so we generated one"); + } else { + PolicyLogger.info("requestID was provided in call to XACMLPdpSrvlet (doPost)"); + } + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 1 of 2"); + loggingContext.metricStarted(); + loggingContext.metricEnded(); + PolicyLogger.metrics("Metric example posted here - 2 of 2"); + monitor.pdpEvaluationAttempts(); + + try { + im.startTransaction(); + } + catch (AdministrativeStateException | StandbyStatusException e) { + String message = e.toString(); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message + e); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + return; + } + // + // no point in doing any work if we know from the get-go that we cannot do anything with the request + // + if (status.getLoadedRootPolicies().isEmpty()) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Request from PEP at " + request.getRequestURI() + " for service when PDP has No Root Policies loaded"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "Request from PEP at " + request.getRequestURI() + " for service when PDP has No Root Policies loaded"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + im.endTransaction(); + return; + } + + XACMLRest.dumpRequest(request); + // + // Set our no-cache header + // + response.setHeader("Cache-Control", "no-cache"); + // + // They must send a Content-Type + // + if (request.getContentType() == null) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Must specify a Content-Type"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Must specify a Content-Type"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_BAD_REQUEST, "no content-type given"); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + im.endTransaction(); + return; + } + // + // Limit the Content-Length to something reasonable + // + try{ + if (request.getContentLength() > Integer.parseInt(XACMLProperties.getProperty("MAX_CONTENT_LENGTH", "32767"))) { + String message = "Content-Length larger than server will accept."; + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); + im.endTransaction(); + return; + } + }catch(Exception e){ + logger.error("Exception occured while getting max content length"+e); + } + + if (request.getContentLength() <= 0) { + String message = "Content-Length is negative"; + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + im.endTransaction(); + return; + } + ContentType contentType = null; + try { + contentType = ContentType.parse(request.getContentType()); + } + catch (Exception e) { + String message = "Parsing Content-Type: " + request.getContentType() + ", error=" + e.getMessage(); + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message, e); + loggingContext.transactionEnded(); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, message); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + im.endTransaction(); + return; + } + // + // What exactly did they send us? + // + String incomingRequestString = null; + Request pdpRequest = null; + if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType()) || + contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || + contentType.getMimeType().equalsIgnoreCase("application/xacml+xml") ) { + // + // Read in the string + // + StringBuilder buffer = new StringBuilder(); + BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); + String line; + try{ + while((line = reader.readLine()) != null){ + buffer.append(line); + } + }catch(Exception e){ + logger.error("Exception Occured while reading line"+e); + } + + incomingRequestString = buffer.toString(); + logger.info(incomingRequestString); + // + // Parse into a request + // + try { + if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { + pdpRequest = JSONRequest.load(incomingRequestString); + } else if ( contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || + contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { + pdpRequest = DOMRequest.load(incomingRequestString); + } + } + catch(Exception e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not parse request", e); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "Could not parse request"); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + im.endTransaction(); + return; + } + } else { + String message = "unsupported content type" + request.getContentType(); + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + im.endTransaction(); + return; + } + // + // Did we successfully get and parse a request? + // + if (pdpRequest == null || pdpRequest.getRequestAttributes() == null || pdpRequest.getRequestAttributes().size() <= 0) { + String message = "Zero Attributes found in the request"; + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_BAD_REQUEST, message); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + im.endTransaction(); + return; + } + // + // Run it + // + try { + // + // Authenticating the Request here. + // + if(!authorizeRequest(request)){ + String message = "PEP not Authorized for making this Request!! \n Contact Administrator for this Scope. "; + logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + message ); + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_FORBIDDEN, message); + im.endTransaction(); + return; + } + // + // Get the pointer to the PDP Engine + // + PDPEngine myEngine = null; + synchronized(pdpEngineLock) { + myEngine = XACMLPdpServlet.pdpEngine; + } + if (myEngine == null) { + String message = "No engine loaded."; + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + im.endTransaction(); + return; + } + // + // Send the request and save the response + // + long lTimeStart; + long lTimeEnd; + Response pdpResponse = null; + + synchronized(pdpEngineLock) { + myEngine = XACMLPdpServlet.pdpEngine; + try { + PolicyList.clearPolicyList(); + lTimeStart = System.currentTimeMillis(); + pdpResponse = myEngine.decide(pdpRequest); + lTimeEnd = System.currentTimeMillis(); + } catch (PDPException e) { + String message = "Exception during decide: " + e.getMessage(); + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message +e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + im.endTransaction(); + return; + } + } + monitor.computeLatency(lTimeEnd - lTimeStart); + requestLogger.info(lTimeStart + "=" + incomingRequestString); + for(String policy : PolicyList.getpolicyList()){ + monitor.policyCountAdd(policy, 1); + } + + + logger.info("PolicyID triggered in Request: " + PolicyList.getpolicyList()); + + //need to go through the list and find out if the value is unique and then add it other wise + // monitor.policyCountAdd(PolicyList.getpolicyList(), 1); + + if (logger.isDebugEnabled()) { + logger.debug("Request time: " + (lTimeEnd - lTimeStart) + "ms"); + } + // + // Convert Response to appropriate Content-Type + // + if (pdpResponse == null) { + requestLogger.info(lTimeStart + "=" + "{}"); + try{ + throw new PDPException("Failed to get response from PDP engine."); + }catch(Exception e1){ + logger.error("Exception occured while throwing Exception" +e1); + } + } + // + // Set our content-type + // + response.setContentType(contentType.getMimeType()); + // + // Convert the PDP response object to a String to + // return to our caller as well as dump to our loggers. + // + String outgoingResponseString = ""; + try{ + if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { + // + // Get it as a String. This is not very efficient but we need to log our + // results for auditing. + // + outgoingResponseString = JSONResponse.toString(pdpResponse, logger.isDebugEnabled()); + if (logger.isDebugEnabled()) { + logger.debug(outgoingResponseString); + // + // Get rid of whitespace + // + outgoingResponseString = JSONResponse.toString(pdpResponse, false); + } + } else if ( contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || + contentType.getMimeType().equalsIgnoreCase("application/xacml+xml")) { + // + // Get it as a String. This is not very efficient but we need to log our + // results for auditing. + // + outgoingResponseString = DOMResponse.toString(pdpResponse, logger.isDebugEnabled()); + if (logger.isDebugEnabled()) { + logger.debug(outgoingResponseString); + // + // Get rid of whitespace + // + outgoingResponseString = DOMResponse.toString(pdpResponse, false); + } + } + // adding the jmx values for NA, Permit and Deny + // + if (outgoingResponseString.contains("NotApplicable") || outgoingResponseString.contains("Decision not a Permit")){ + monitor.pdpEvaluationNA(); + } + + if (outgoingResponseString.contains("Permit") && !outgoingResponseString.contains("Decision not a Permit")){ + monitor.pdpEvaluationPermit(); + } + + if (outgoingResponseString.contains("Deny")){ + monitor.pdpEvaluationDeny(); + } + // + // lTimeStart is used as an ID within the requestLogger to match up + // request's with responses. + // + requestLogger.info(lTimeStart + "=" + outgoingResponseString); + response.getWriter().print(outgoingResponseString); + }catch(Exception e){ + logger.error("Exception Occured"+e ); + } + } + catch (Exception e) { + String message = "Exception executing request: " + e; + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + message, e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, message); + loggingContext.transactionEnded(); + PolicyLogger.audit("Transaction Failed - See Error.log"); + try{ + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); + }catch(Exception e1){ + logger.error("Exception occured while sending error in response" +e1); + } + return; + } + + monitor.pdpEvaluationSuccess(); + response.setStatus(HttpServletResponse.SC_OK); + + loggingContext.transactionEnded(); + auditLogger.info("Success"); + PolicyLogger.audit("Success"); + + } + + /* + * Added for Authorizing the PEP Requests for Environment check. + */ + private boolean authorizeRequest(HttpServletRequest request) { + // Get the client Credentials from the Request header. + HttpServletRequest httpServletRequest = request; + String clientCredentials = httpServletRequest.getHeader(ENVIORNMENT_HEADER); + if(clientCredentials!=null && clientCredentials.equalsIgnoreCase(environment)){ + return true; + }else{ + return false; + } + } + + @Override + public void run() { + // + // Keep running until we are told to terminate + // + try { + // variable not used, but constructor has needed side-effects so don't remove: + while (! this.configThreadTerminate) { + PutRequest request = XACMLPdpServlet.queue.take(); + StdPDPStatus newStatus = new StdPDPStatus(); + + PDPEngine newEngine = null; + synchronized(pdpStatusLock) { + XACMLPdpServlet.status.setStatus(Status.UPDATING_CONFIGURATION); + newEngine = XACMLPdpLoader.loadEngine(newStatus, request.policyProperties, request.pipConfigProperties); + } + if (newEngine != null) { + synchronized(XACMLPdpServlet.pdpEngineLock) { + XACMLPdpServlet.pdpEngine = newEngine; + try { + logger.info("Saving configuration."); + if (request.policyProperties != null) { + try (OutputStream os = Files.newOutputStream(XACMLPdpLoader.getPDPPolicyCache())) { + request.policyProperties.store(os, ""); + } + } + if (request.pipConfigProperties != null) { + try (OutputStream os = Files.newOutputStream(XACMLPdpLoader.getPIPConfig())) { + request.pipConfigProperties.store(os, ""); + } + } + newStatus.setStatus(Status.UP_TO_DATE); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to store new properties."+e); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, "Failed to store new properties"); + newStatus.setStatus(Status.LOAD_ERRORS); + newStatus.addLoadWarning("Unable to save configuration: " + e.getMessage()); + } + } + } else { + newStatus.setStatus(Status.LAST_UPDATE_FAILED); + } + synchronized(pdpStatusLock) { + XACMLPdpServlet.status.set(newStatus); + } + } + } catch (InterruptedException e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "interrupted"+e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "interrupted"); + Thread.currentThread().interrupt(); + } + } + + public static PDPEngine getPDPEngine(){ + PDPEngine myEngine = null; + synchronized(pdpEngineLock) { + myEngine = XACMLPdpServlet.pdpEngine; + } + return myEngine; + } + + public static Constructor getCreateUpdatePolicyConstructor(){ + return createUpdatePolicyConstructor; + } + + private static void setCreateUpdatePolicyConstructor(String createUpdateResourceName) throws ServletException{ + try{ + Class createUpdateclass = Class.forName(createUpdateResourceName); + createUpdatePolicyConstructor = createUpdateclass.getConstructor(PolicyParameters.class, String.class, boolean.class); + }catch(Exception e){ + PolicyLogger.error(MessageCodes.MISS_PROPERTY_ERROR, "createUpdatePolicy.impl.className", "xacml.pdp.init" +e); + throw new ServletException("Could not find the Class name : " +createUpdateResourceName + "\n" +e.getMessage()); + } + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/controller/PolicyEngineServices.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/controller/PolicyEngineServices.java new file mode 100644 index 000000000..2348fd0da --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/controller/PolicyEngineServices.java @@ -0,0 +1,658 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.controller; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; + +import java.lang.reflect.InvocationTargetException; +import java.util.Collection; +import java.util.concurrent.atomic.AtomicLong; + +import javax.servlet.http.HttpServletRequest; + +import org.onap.policy.api.ConfigRequestParameters; +import org.onap.policy.api.DecisionRequestParameters; +import org.onap.policy.api.DecisionResponse; +import org.onap.policy.api.DeletePolicyParameters; +import org.onap.policy.api.DictionaryParameters; +import org.onap.policy.api.DictionaryResponse; +import org.onap.policy.api.EventRequestParameters; +import org.onap.policy.api.MetricsResponse; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.PolicyResponse; +import org.onap.policy.api.PushPolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.XACMLPdpServlet; +import org.onap.policy.pdp.rest.api.models.ConfigFirewallPolicyAPIRequest; +import org.onap.policy.pdp.rest.api.models.ConfigNameRequest; +import org.onap.policy.pdp.rest.api.models.ConfigPolicyAPIRequest; +import org.onap.policy.pdp.rest.api.models.PolicyConfig; +import org.onap.policy.pdp.rest.api.services.CreateUpdateConfigPolicyService; +import org.onap.policy.pdp.rest.api.services.CreateUpdateDictionaryService; +import org.onap.policy.pdp.rest.api.services.CreateUpdateFirewallPolicyService; +import org.onap.policy.pdp.rest.api.services.CreateUpdatePolicyService; +import org.onap.policy.pdp.rest.api.services.DeletePolicyService; +import org.onap.policy.pdp.rest.api.services.GetConfigService; +import org.onap.policy.pdp.rest.api.services.GetDecisionService; +import org.onap.policy.pdp.rest.api.services.GetDictionaryService; +import org.onap.policy.pdp.rest.api.services.GetMetricsService; +import org.onap.policy.pdp.rest.api.services.ListConfigService; +import org.onap.policy.pdp.rest.api.services.NotificationService; +import org.onap.policy.pdp.rest.api.services.NotificationService.NotificationServiceType; +import org.onap.policy.pdp.rest.api.services.PolicyEngineImportService; +import org.onap.policy.pdp.rest.api.services.PushPolicyService; +import org.onap.policy.pdp.rest.api.services.SendEventService; +import org.onap.policy.pdp.rest.config.PDPApiAuth; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import springfox.documentation.annotations.ApiIgnore; + +@RestController +@Api(value = "Policy Engine Services") +@RequestMapping("/") +public class PolicyEngineServices { + private static Logger logger = FlexLogger.getLogger(PolicyEngineServices.class.getName()); + private static final String NOTIFICATIONPERM = "notification"; + + private final AtomicLong configCounter = new AtomicLong(); + private final AtomicLong configNameCounter = new AtomicLong(); + private final AtomicLong eventCounter = new AtomicLong(); + private final AtomicLong decisionCounter = new AtomicLong(); + private final AtomicLong pushCounter = new AtomicLong(); + private final AtomicLong deleteCounter = new AtomicLong(); + private final AtomicLong createPolicyCounter = new AtomicLong(); + private final AtomicLong updatePolicyCounter = new AtomicLong(); + private final AtomicLong createDictionaryCounter = new AtomicLong(); + private final AtomicLong updateDictionaryCounter = new AtomicLong(); + private final AtomicLong getDictionaryCounter = new AtomicLong(); + private final AtomicLong policyEngineImportCounter = new AtomicLong(); + private final AtomicLong deprecatedCounter = new AtomicLong(); + private final AtomicLong metricCounter = new AtomicLong(); + private final AtomicLong notificationCounter = new AtomicLong(); + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Gets the configuration from the PolicyDecisionPoint(PDP)") + @RequestMapping(value = "/getConfig", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity> getConfig( + @RequestBody ConfigRequestParameters configRequestParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + Collection policyConfig = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "getConfig")) { + GetConfigService getConfigService = new GetConfigService( + configRequestParameters, requestID); + policyConfig = getConfigService.getResult(); + status = getConfigService.getResponseCode(); + } + configCounter.incrementAndGet(); + return new ResponseEntity<>(policyConfig, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Gets the configuration from the PolicyDecisionPoint(PDP) using PolicyName") + @RequestMapping(value = "/getConfigByPolicyName", method = RequestMethod.POST) + @ResponseBody + @Deprecated + public ResponseEntity> getConfigByPolicyName( + @RequestBody ConfigNameRequest configNameRequest, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + Collection policyConfig = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID,"getConfigByPolicyName")) { + ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); + configRequestParameters.setPolicyName(configNameRequest + .getPolicyName()); + GetConfigService getConfigService = new GetConfigService( + configRequestParameters, requestID); + policyConfig = getConfigService.getResult(); + status = getConfigService.getResponseCode(); + } + configNameCounter.incrementAndGet(); + return new ResponseEntity<>(policyConfig, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Gets the list of configuration policies from the PDP") + @RequestMapping(value = "/listConfig", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity> listConfig( + @RequestBody ConfigRequestParameters configRequestParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + Collection results = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth + .checkPermissions(clientEncoding, requestID, "listConfig")) { + ListConfigService listConfigService = new ListConfigService( + configRequestParameters, requestID); + results = listConfigService.getResult(); + status = listConfigService.getResponseCode(); + } + configCounter.incrementAndGet(); + return new ResponseEntity<>(results, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name ="Environment", required = true, paramType = "Header") + }) + @ApiOperation(value= "Gets the policy metrics from the PolicyAccessPoint(PAP)") + @RequestMapping(value="/getMetrics", method=RequestMethod.GET) + @ResponseBody + public ResponseEntity getMetrics( + @RequestHeader(value="ClientAuth", required=true)String clientEncoding, + @RequestHeader(value="X-ECOMP-RequestID", required=false)String requestID) { + MetricsResponse response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if(PDPApiAuth.checkPermissions(clientEncoding, requestID, "getMetrics")){ + GetMetricsService getMetricsService = new GetMetricsService(requestID); + response = getMetricsService.getResult(); + status = getMetricsService.getResponseCode(); + } + metricCounter.incrementAndGet(); + return new ResponseEntity<>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Registers DMaaP Topic to recieve notification from Policy Engine") + @RequestMapping(value = "/getNotification", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity getNotification( + @RequestBody String notificationTopic, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String policyResponse = "Error Unauthorized to use Notification Service."; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, NOTIFICATIONPERM)) { + NotificationService notificationService = new NotificationService(notificationTopic, requestID, NotificationServiceType.ADD); + policyResponse = notificationService.getResult(); + status = notificationService.getResponseCode(); + } + notificationCounter.incrementAndGet(); + return new ResponseEntity<>(policyResponse, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "De-Registers DMaaP Topic to stop recieving notifications from Policy Engine") + @RequestMapping(value = "/stopNotification", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity stopNotification( + @RequestBody String notificationTopic, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String policyResponse = "Error Unauthorized to use Notification Service."; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, NOTIFICATIONPERM)) { + NotificationService notificationService = new NotificationService(notificationTopic, requestID, NotificationServiceType.REMOVE); + policyResponse = notificationService.getResult(); + status = notificationService.getResponseCode(); + } + notificationCounter.incrementAndGet(); + return new ResponseEntity<>(policyResponse, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Sends Heartbeat to DMaaP Topic Registry to continue recieving notifications from Policy Engine") + @RequestMapping(value = "/sendHeartbeat", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity sendHeartbeat( + @RequestBody String notificationTopic, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String policyResponse = "Error Unauthorized to use Heartbeat Service."; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, NOTIFICATIONPERM)) { + NotificationService notificationService = new NotificationService(notificationTopic, requestID, NotificationServiceType.HB); + policyResponse = notificationService.getResult(); + status = notificationService.getResponseCode(); + } + return new ResponseEntity<>(policyResponse, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Sends the Events specified to the Policy Engine") + @RequestMapping(value = "/sendEvent", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity> sendEvent( + @RequestBody EventRequestParameters eventRequestParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + Collection policyResponse = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, "sendEvent")) { + SendEventService sendEventService = new SendEventService( + eventRequestParameters, requestID); + policyResponse = sendEventService.getResult(); + status = sendEventService.getResponseCode(); + } + eventCounter.incrementAndGet(); + return new ResponseEntity<>(policyResponse, + status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Gets the Decision using specified decision parameters") + @RequestMapping(value = "/getDecision", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity getDecision( + @RequestBody DecisionRequestParameters decisionRequestParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + DecisionResponse decisionResponse = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "getDecision")) { + GetDecisionService getDecisionService = new GetDecisionService( + decisionRequestParameters, requestID); + decisionResponse = getDecisionService.getResult(); + status = getDecisionService.getResponseCode(); + } + decisionCounter.incrementAndGet(); + return new ResponseEntity<>(decisionResponse, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Pushes the specified policy to the PDP Group.") + @RequestMapping(value = "/pushPolicy", method = RequestMethod.PUT) + @ResponseBody + public ResponseEntity pushPolicy( + @RequestBody PushPolicyParameters pushPolicyParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth + .checkPermissions(clientEncoding, requestID, "pushPolicy")) { + PushPolicyService pushPolicyService = new PushPolicyService( + pushPolicyParameters, requestID); + response = pushPolicyService.getResult(); + status = pushPolicyService.getResponseCode(); + } + pushCounter.incrementAndGet(); + return new ResponseEntity<>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Deletes the specified policy from the PDP Group or PAP.") + @RequestMapping(value = "/deletePolicy", method = RequestMethod.DELETE) + @ResponseBody + public ResponseEntity deletePolicy( + @RequestBody DeletePolicyParameters deletePolicyParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "deletePolicy")) { + DeletePolicyService deletePolicyService = new DeletePolicyService( + deletePolicyParameters, requestID); + response = deletePolicyService.getResult(); + status = deletePolicyService.getResponseCode(); + } + deleteCounter.incrementAndGet(); + return new ResponseEntity<>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Creates a Policy based on given Policy Parameters.") + @RequestMapping(value = "/createPolicy", method = RequestMethod.PUT) + @ResponseBody + public ResponseEntity createPolicy( + @RequestBody PolicyParameters policyParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "createPolicy")) { + CreateUpdatePolicyService createPolicyService; + try { + createPolicyService = (CreateUpdatePolicyService) XACMLPdpServlet.getCreateUpdatePolicyConstructor().newInstance( + policyParameters, requestID, false); + response = createPolicyService.getResult(); + status = createPolicyService.getResponseCode(); + } catch (InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + logger.error(e.getMessage(), e); + response = "Problem with CreateUpdate Policy Service. "; + status = HttpStatus.INTERNAL_SERVER_ERROR; + } + } + createPolicyCounter.incrementAndGet(); + return new ResponseEntity<>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Updates a Policy based on given Policy Parameters.") + @RequestMapping(value = "/updatePolicy", method = RequestMethod.PUT) + @ResponseBody + public ResponseEntity updatePolicy( + @RequestBody PolicyParameters policyParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "updatePolicy")) { + CreateUpdatePolicyService updatePolicyService; + try { + updatePolicyService = (CreateUpdatePolicyService) XACMLPdpServlet.getCreateUpdatePolicyConstructor().newInstance( + policyParameters, requestID, true); + response = updatePolicyService.getResult(); + status = updatePolicyService.getResponseCode(); + } catch (InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + logger.error(e.getMessage(), e); + response = "Problem with CreateUpdate Policy Service. "; + status = HttpStatus.INTERNAL_SERVER_ERROR; + } + } + updatePolicyCounter.incrementAndGet(); + return new ResponseEntity<>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Creates a Dictionary Item for a specific dictionary based on given Parameters.") + @RequestMapping(value = "/createDictionaryItem", method = RequestMethod.PUT) + @ResponseBody + public ResponseEntity createDictionaryItem( + @RequestBody DictionaryParameters dictionaryParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "createDictionary")) { + CreateUpdateDictionaryService createDictionaryService = new CreateUpdateDictionaryService( + dictionaryParameters, requestID, false); + response = createDictionaryService.getResult(); + status = createDictionaryService.getResponseCode(); + } + createDictionaryCounter.incrementAndGet(); + return new ResponseEntity<>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Updates a Dictionary Item for a specific dictionary based on given Parameters.") + @RequestMapping(value = "/updateDictionaryItem", method = RequestMethod.PUT) + @ResponseBody + public ResponseEntity updateDictionaryItem( + @RequestBody DictionaryParameters dictionaryParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "updateDictionary")) { + CreateUpdateDictionaryService updateDictionaryService = new CreateUpdateDictionaryService( + dictionaryParameters, requestID, true); + response = updateDictionaryService.getResult(); + status = updateDictionaryService.getResponseCode(); + } + updateDictionaryCounter.incrementAndGet(); + return new ResponseEntity<>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Gets the dictionary items from the PAP") + @RequestMapping(value = "/getDictionaryItems", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity getDictionaryItems( + @RequestBody DictionaryParameters dictionaryParameters, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + DictionaryResponse dictionaryResponse = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "getDictionary")) { + GetDictionaryService getDictionaryService = new GetDictionaryService( + dictionaryParameters, requestID); + dictionaryResponse = getDictionaryService.getResult(); + status = getDictionaryService.getResponseCode(); + } + getDictionaryCounter.incrementAndGet(); + return new ResponseEntity<>(dictionaryResponse, + status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Imports Policy based on the parameters which represent the service used to create a policy Service.") + @RequestMapping(value = "/policyEngineImport", method = RequestMethod.POST) + @ResponseBody + public ResponseEntity policyEngineImport( + @RequestParam("importParametersJson") String importParametersJson, + @RequestParam("file") MultipartFile file, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "policyEngineImport")) { + PolicyEngineImportService policyEngineImportService = new PolicyEngineImportService( + importParametersJson, file, requestID); + response = policyEngineImportService.getResult(); + status = policyEngineImportService.getResponseCode(); + } + policyEngineImportCounter.incrementAndGet(); + return new ResponseEntity<>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Creates a Config Policy based on given Policy Parameters.") + @RequestMapping(value = "/createConfig", method = RequestMethod.PUT) + @ResponseBody + @Deprecated + public ResponseEntity createConfig( + @RequestBody ConfigPolicyAPIRequest configPolicyAPIRequest, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "createPolicy")) { + CreateUpdateConfigPolicyService createPolicyService = new CreateUpdateConfigPolicyService( + configPolicyAPIRequest, requestID, false); + response = createPolicyService.getResult(); + status = createPolicyService.getResponseCode(); + } + deprecatedCounter.incrementAndGet(); + return new ResponseEntity<>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Updates a Config Policy based on given Policy Parameters.") + @RequestMapping(value = "/updateConfig", method = RequestMethod.PUT) + @ResponseBody + @Deprecated + public ResponseEntity updateConfig( + @RequestBody ConfigPolicyAPIRequest configPolicyAPIRequest, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "updatePolicy")) { + CreateUpdateConfigPolicyService updatePolicyService = new CreateUpdateConfigPolicyService( + configPolicyAPIRequest, requestID, true); + response = updatePolicyService.getResult(); + status = updatePolicyService.getResponseCode(); + } + deprecatedCounter.incrementAndGet(); + return new ResponseEntity<>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Creates a Config Firewall Policy") + @RequestMapping(value = "/createFirewallConfig", method = RequestMethod.PUT) + @ResponseBody + @Deprecated + public ResponseEntity createFirewallConfig( + @RequestBody ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "createPolicy")) { + CreateUpdateFirewallPolicyService createFirewallPolicyService = new CreateUpdateFirewallPolicyService( + configFirewallPolicyAPIRequest, requestID, false); + response = createFirewallPolicyService.getResult(); + status = createFirewallPolicyService.getResponseCode(); + } + deprecatedCounter.incrementAndGet(); + return new ResponseEntity<>(response, status); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name = "Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name = "Environment", required = true, paramType = "Header") }) + @ApiOperation(value = "Updates a Config Firewall Policy") + @RequestMapping(value = "/updateFirewallConfig", method = RequestMethod.PUT) + @ResponseBody + @Deprecated + public ResponseEntity updateFirewallConfig( + @RequestBody ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest, + @RequestHeader(value = "ClientAuth", required = true) String clientEncoding, + @RequestHeader(value = "X-ECOMP-RequestID", required = false) String requestID) { + String response = null; + HttpStatus status = HttpStatus.UNAUTHORIZED; + // Check Permissions. + if (PDPApiAuth.checkPermissions(clientEncoding, requestID, + "updatePolicy")) { + CreateUpdateFirewallPolicyService updateFirewallPolicyService = new CreateUpdateFirewallPolicyService( + configFirewallPolicyAPIRequest, requestID, true); + response = updateFirewallPolicyService.getResult(); + status = updateFirewallPolicyService.getResponseCode(); + } + deprecatedCounter.incrementAndGet(); + return new ResponseEntity<>(response, status); + } + + @ApiOperation(value = "Gets the API Services usage Information") + @ApiIgnore + @RequestMapping(value = "/count", method = RequestMethod.GET) + public String getCount() { + return "Total Config Calls : " + configCounter + "\n" + + "Total Config calls made using Policy File Name: " + + configNameCounter + "\n" + "Total Event Calls : " + + eventCounter + "\nTotal Decision Calls: " + decisionCounter + + "\nTotal Push policy Calls: " + pushCounter + + "\nTotal Delete Policy Calls: " + deleteCounter + + "\nTotal Create Policy Calls: " + createPolicyCounter + + "\nTotal Update Policy Calls: " + updatePolicyCounter + + "\nTotal Create Dictionary Calls: " + createDictionaryCounter + + "\nTotal Update Dictionary Calls: " + updateDictionaryCounter + + "\nTotal Get Dictionary Calls: " + getDictionaryCounter + + "\nTotal PolicyEngine Import Calls: " + + policyEngineImportCounter + + "\nTotal Deprecated Policy Calls: " + deprecatedCounter + + "\nTotal Metrics Calls:" + metricCounter + + "\nTotal Notification Calls:" + notificationCounter; + } + + @ExceptionHandler({ HttpMessageNotReadableException.class }) + public ResponseEntity messageNotReadableExceptionHandler( + HttpServletRequest req, HttpMessageNotReadableException exception) { + logger.error("Request not readable: {}", exception); + StringBuilder message = new StringBuilder(); + message.append(exception.getMessage()); + if (exception.getCause() != null) { + message.append(" Reason Caused: " + + exception.getCause().getMessage()); + } + return new ResponseEntity<>(message.toString(), HttpStatus.BAD_REQUEST); + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/ConfigFirewallPolicyAPIRequest.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/ConfigFirewallPolicyAPIRequest.java new file mode 100644 index 000000000..5c9b9efcc --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/ConfigFirewallPolicyAPIRequest.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.models; + +import io.swagger.annotations.ApiModel; + +import java.io.Serializable; + +@ApiModel +public class ConfigFirewallPolicyAPIRequest implements Serializable{ + private static final long serialVersionUID = -7460640390070215401L; + + private String policyName = null; + private String policyScope = null; + private String firewallJson = null; + private String riskType = "default"; + private String riskLevel = "5"; + private String guard = "false"; + private String ttlDate = null; + + public String getPolicyName() { + return policyName; + } + public String getPolicyScope() { + return policyScope; + } + public String getFirewallJson() { + return firewallJson; + } + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + public void setPolicyScope(String policyScope) { + this.policyScope = policyScope; + } + public void setFirewallJson(String firewallJson) { + this.firewallJson = firewallJson; + } + 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 getGuard() { + return guard; + } + public void setGuard(String guard) { + this.guard = guard; + } + public String getTtlDate() { + return ttlDate; + } + public void setTtlDate(String ttlDate) { + this.ttlDate = ttlDate; + } +} \ No newline at end of file diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/ConfigNameRequest.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/ConfigNameRequest.java new file mode 100644 index 000000000..945445991 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/ConfigNameRequest.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.models; + +import io.swagger.annotations.ApiModel; + +import java.io.Serializable; + +@ApiModel +public class ConfigNameRequest implements Serializable{ + private static final long serialVersionUID = 4487978240532425305L; + + private String policyName = null; + + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + + public String getPolicyName() { + return policyName; + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/ConfigPolicyAPIRequest.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/ConfigPolicyAPIRequest.java new file mode 100644 index 000000000..dd40bfe5f --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/ConfigPolicyAPIRequest.java @@ -0,0 +1,188 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.models; + +import io.swagger.annotations.ApiModel; + +import java.io.Serializable; +import java.util.Map; + +@ApiModel +public class ConfigPolicyAPIRequest implements Serializable{ + private static final long serialVersionUID = -4103391389984557025L; + + private String policyScope = null; + private String policyName = null; + private String policyDescription = null; + private String onapName = null; + private String configName = null; + private Map configAttributes = null; + private String configType = null; + private String body = null; + private String riskType = "default"; + private String riskLevel = "5"; + private String guard = "false"; + private String ttlDate = null; + + /** + * @return the policyScope + */ + public String getPolicyScope() { + return policyScope; + } + /** + * @return the policyName + */ + public String getPolicyName() { + return policyName; + } + /** + * @return the policyDescription + */ + public String getPolicyDescription() { + return policyDescription; + } + /** + * @return the onapName + */ + public String getOnapName() { + return onapName; + } + /** + * @return the configName + */ + public String getConfigName() { + return configName; + } + /** + * @return the configAttributes + */ + public Map getConfigAttributes() { + return configAttributes; + } + /** + * @return the configType + */ + public String getConfigType() { + return configType; + } + /** + * @return the body + */ + public String getBody() { + return body; + } + /** + * @param policyScope the policyScope to set + */ + public void setPolicyScope(String policyScope) { + this.policyScope = policyScope; + } + /** + * @param policyName the policyName to set + */ + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + /** + * @param policyDescription the policyDescription to set + */ + public void setPolicyDescription(String policyDescription) { + this.policyDescription = policyDescription; + } + /** + * @param onapName the onapName to set + */ + public void setOnapName(String onapName) { + this.onapName = onapName; + } + /** + * @param configName the configName to set + */ + public void setConfigName(String configName) { + this.configName = configName; + } + /** + * @param configAttributes the configAttributes to set + */ + public void setConfigAttributes(Map configAttributes) { + this.configAttributes = configAttributes; + } + /** + * @param configType the configType to set + */ + public void setConfigType(String configType) { + this.configType = configType; + } + /** + * @param body the body to set + */ + public void setBody(String body) { + this.body = body; + } + /** + * @return the guard + */ + public String getGuard() { + return guard; + } + /** + * @param guard the guard to set + */ + public void setGuard(String guard) { + this.guard = guard; + } + /** + * @return the riskLevel + */ + public String getRiskLevel() { + return riskLevel; + } + /** + * @param riskLevel the riskLevel to set + */ + public void setRiskLevel(String riskLevel) { + this.riskLevel = riskLevel; + } + /** + * @return the ttlDate + */ + public String getTtlDate() { + return ttlDate; + } + /** + * @param ttlDate the ttlDate to set + */ + public void setTtlDate(String ttlDate) { + this.ttlDate = ttlDate; + } + /** + * @return the riskType + */ + public String getRiskType() { + return riskType; + } + /** + * @param riskType the riskType to set + */ + public void setRiskType(String riskType) { + this.riskType = riskType; + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/PDPResponse.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/PDPResponse.java new file mode 100644 index 000000000..c2dbbdef0 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/PDPResponse.java @@ -0,0 +1,159 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.models; + +import java.util.Map; + +import org.onap.policy.api.DecisionResponse; +import org.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.api.PolicyDecision; +import org.onap.policy.api.PolicyResponse; +import org.onap.policy.api.PolicyResponseStatus; +import org.onap.policy.api.PolicyType; +import org.onap.policy.models.APIConfigResponse; + +public class PDPResponse implements APIConfigResponse, PolicyResponse, DecisionResponse{ + private String policyConfigMessage; + private PolicyConfigStatus policyConfigStatus; + private PolicyType type; + private String config; + private String policyName; + private String policyVersion; + private Map matchingConditions; + private Map responseAttributes; + private Map property; + private PolicyResponseStatus policyResponseStatus; + private String policyResponseMessage; + private Map actionAdvised; + private Map actionTaken; + private Map requestAttributes; + private PolicyDecision policyDecision; + private String details; + + public void setStatus(String message, PolicyResponseStatus policyResponseStatus, PolicyConfigStatus policyConfigStatus) { + this.policyConfigMessage = message; + this.policyResponseMessage = message; + this.policyResponseStatus = policyResponseStatus; + this.policyConfigStatus = policyConfigStatus; + } + public String getConfig() { + return config; + } + public void setConfig(String config) { + this.config = config; + } + public PolicyType getType() { + return type; + } + public void setType(PolicyType type) { + this.type = type; + } + public PolicyConfigStatus getPolicyConfigStatus() { + return policyConfigStatus; + } + public void setPolicyConfigStatus(PolicyConfigStatus policyConfigStatus) { + this.policyConfigStatus = policyConfigStatus; + } + public String getPolicyConfigMessage() { + return policyConfigMessage; + } + public void setPolicyConfigMessage(String policyConfigMessage) { + this.policyConfigMessage = policyConfigMessage; + } + public Map getProperty() { + return property; + } + public void setProperty(Map property) { + this.property = property; + } + public String getPolicyName(){ + return policyName; + } + public void setPolicyName(String policyName){ + this.policyName = policyName; + } + public String getPolicyVersion(){ + return policyVersion; + } + public void setPolicyVersion(String policyVersion){ + this.policyVersion = policyVersion; + } + public Map getMatchingConditions(){ + return matchingConditions; + } + public void setMatchingConditions(Map matchingConditions){ + this.matchingConditions = matchingConditions; + } + public void setResponseAttributes(Map responseAttributes){ + this.responseAttributes = responseAttributes; + } + public Map getResponseAttributes(){ + return responseAttributes; + } + public void setPolicyResponseStatus(PolicyResponseStatus policyResponseStatus) { + this.policyResponseStatus = policyResponseStatus; + } + @Override + public PolicyResponseStatus getPolicyResponseStatus() { + return policyResponseStatus; + } + public void setDecision(PolicyDecision policyDecision){ + this.policyDecision = policyDecision; + } + @Override + public PolicyDecision getDecision() { + return policyDecision; + } + public void setDetails(String details){ + this.details = details; + } + @Override + public String getDetails() { + return details; + } + public void setActionAdvised(Map actionAdvised) { + this.actionAdvised = actionAdvised; + } + @Override + public Map getActionAdvised() { + return actionAdvised; + } + public void setActionTaken(Map actionTaken) { + this.actionTaken = actionTaken; + } + @Override + public Map getActionTaken() { + return actionTaken; + } + public void setRequestAttributes(Map requestAttributes) { + this.requestAttributes = requestAttributes; + } + @Override + public Map getRequestAttributes() { + return requestAttributes; + } + public void setPolicyResponseMessage(String policyResponseMessage) { + this.policyResponseMessage = policyResponseMessage; + } + @Override + public String getPolicyResponseMessage() { + return policyResponseMessage; + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/PolicyConfig.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/PolicyConfig.java new file mode 100644 index 000000000..391ef6c8a --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/models/PolicyConfig.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.models; + +import io.swagger.annotations.ApiModel; + +import java.util.Map; + +import org.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.api.PolicyType; +import org.onap.policy.models.APIConfigResponse; + +@ApiModel +public class PolicyConfig implements APIConfigResponse{ + private String policyConfigMessage; + private PolicyConfigStatus policyConfigStatus; + private PolicyType type; + private String config; + private String policyName; + private String policyVersion; + private Map matchingConditions; + private Map responseAttributes; + private Map property; + public String getConfig() { + return config; + } + public void setConfig(String config) { + this.config = config; + } + public PolicyType getType() { + return type; + } + public void setType(PolicyType type) { + this.type = type; + } + public PolicyConfigStatus getPolicyConfigStatus() { + return policyConfigStatus; + } + public void setPolicyConfigStatus(PolicyConfigStatus policyConfigStatus) { + this.policyConfigStatus = policyConfigStatus; + } + public String getPolicyConfigMessage() { + return policyConfigMessage; + } + public void setPolicyConfigMessage(String policyConfigMessage) { + this.policyConfigMessage = policyConfigMessage; + } + public Map getProperty() { + return property; + } + public void setProperty(Map property) { + this.property = property; + } + public String getPolicyName(){ + return policyName; + } + public void setPolicyName(String policyName){ + this.policyName = policyName; + } + public String getPolicyVersion(){ + return policyVersion; + } + public void setPolicyVersion(String policyVersion){ + this.policyVersion = policyVersion; + } + public Map getMatchingConditions(){ + return matchingConditions; + } + public void setMatchingConditions(Map matchingConditions){ + this.matchingConditions = matchingConditions; + } + public void setResponseAttributes(Map responseAttributes){ + this.responseAttributes = responseAttributes; + } + public Map getResponseAttributes(){ + return responseAttributes; + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ActionPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ActionPolicyService.java new file mode 100644 index 000000000..66920e0db --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ActionPolicyService.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.util.Map; + +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Action Policy Implementation. + * + * @version 0.1 + */ +public class ActionPolicyService { + private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyService.class.getName()); + private PAPServices papServices = null; + + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private Map componentAttributes = null; + private String actionAttribute = null; + private String actionPerformer = null; + + public ActionPolicyService(String policyScope, String policyName, + PolicyParameters policyParameters) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + if(policyParameters.getAttributes()==null || policyParameters.getAttributes().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Component Attributes given."; + return false; + } + componentAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING); + if (componentAttributes==null||componentAttributes.isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Component Attributes given."; + return false; + } + actionAttribute = policyParameters.getActionAttribute(); + if (actionAttribute==null||actionAttribute.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Attribute given."; + return false; + } + actionPerformer = policyParameters.getActionPerformer(); + if (actionPerformer==null||actionPerformer.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Performer given."; + return false; + } + if(!"PEP".equalsIgnoreCase(actionPerformer)&& !"PDP".equalsIgnoreCase(actionPerformer)){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Performer given."; + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException { + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + // Create Policy + StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyName, policyParameters.getPolicyDescription(), + componentAttributes, policyParameters.getDynamicRuleAlgorithmLabels(), policyParameters.getDynamicRuleAlgorithmFunctions(), + policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmField2(), actionPerformer, actionAttribute, updateFlag, policyScope, 0); + // send Json to PAP + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Action"}, policyParameters.getRequestID(), "Action"); + LOGGER.info(response); + return response; + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/BRMSParamPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/BRMSParamPolicyService.java new file mode 100644 index 000000000..dd2bd452e --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/BRMSParamPolicyService.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.util.Map; + +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * BRMS Param Policy Implementation. + * + * @version 0.1 + */ +public class BRMSParamPolicyService{ + private static final Logger LOGGER = FlexLogger.getLogger(BRMSParamPolicyService.class.getName()); + private PAPServices papServices = null; + + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String date = null; + private Map> drlRuleAndUIParams = null; + + public BRMSParamPolicyService(String policyName, String policyScope, + PolicyParameters policyParameters, String date) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + this.date = date; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + if(!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + return false; + } + drlRuleAndUIParams = policyParameters.getAttributes(); + if(drlRuleAndUIParams==null || drlRuleAndUIParams.isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Rule Attributes given."; + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException { + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + // Create Policy + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("BRMS_Param",policyName, policyParameters.getPolicyDescription(), + "BRMS_PARAM_RULE",updateFlag,policyScope, + drlRuleAndUIParams.get(AttributeType.MATCHING), 0, "DROOLS", + null, drlRuleAndUIParams.get(AttributeType.RULE), policyParameters.getRiskLevel(), + policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date, policyParameters.getControllerName(), policyParameters.getDependencyNames()); + // Send JSON to PAP + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigBrmsParam"); + LOGGER.info(response); + return response; + } + +} \ No newline at end of file diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/BRMSRawPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/BRMSRawPolicyService.java new file mode 100644 index 000000000..ea17529ba --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/BRMSRawPolicyService.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.util.Map; + +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * BRMS RAW Policy Implementation. + * + * @version 0.1 + */ +public class BRMSRawPolicyService{ + private static Logger LOGGER = FlexLogger.getLogger(BRMSRawPolicyService.class.getName()); + private static PAPServices papServices = null; + + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String date = null; + private boolean levelCheck = false; + private String brmsRawBody = null; + + public BRMSRawPolicyService(String policyName, String policyScope, + PolicyParameters policyParameters, String date) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + this.date = date; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + brmsRawBody = policyParameters.getConfigBody(); + if(brmsRawBody==null || brmsRawBody.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Rule Body given"; + return false; + } + message = PolicyUtils.brmsRawValidate(brmsRawBody); + if(message.contains("[ERR")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Raw rule given is invalid" +message; + return false; + } + levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + if(!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException { + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + Map ruleAttributes = null; + if(policyParameters.getAttributes()!=null){ + ruleAttributes = policyParameters.getAttributes().get(AttributeType.RULE); + } + // Create Policy + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("BRMS_Raw",policyName,policyParameters.getPolicyDescription(), + "BRMS_RAW_RULE",updateFlag,policyScope, ruleAttributes, 0, "DROOLS", + brmsRawBody, policyParameters.getRiskLevel(), + policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date, policyParameters.getControllerName(), policyParameters.getDependencyNames()); + // Send JSON to PAP + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigBrmsRaw"); + LOGGER.info(response); + return response; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java new file mode 100644 index 000000000..5817d7410 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ClosedLoopFaultPolicyService.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Closed Loop Fault Policy Implementation. + * + * @version 0.1 + */ +public class ClosedLoopFaultPolicyService{ + private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopFaultPolicyService.class.getName()); + private PAPServices papServices = null; + + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String date = null; + private JsonObject configBody = null; + + public ClosedLoopFaultPolicyService(String policyName, String policyScope, + PolicyParameters policyParameters, String date) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + this.date = date; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + if(policyParameters.getConfigBody()==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present"; + return false; + } + if(!PolicyApiUtils.validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + return false; + } + try{ + configBody = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); + } catch(JsonException| IllegalStateException e){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + LOGGER.error("Json Parse Exception.", e); + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException { + String response = null; + String operation = null; + String oldPolicyName = null; + if (updateFlag){ + operation = "update"; + if (policyName.endsWith("_Draft")) { + oldPolicyName = policyName + "_Draft.1"; + } + } else { + operation = "create"; + } + // get values and attributes from the JsonObject + if(!configBody.containsKey("onapname")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Onap Name given."; + LOGGER.error(message); + return message; + } + String onapName = configBody.get("onapname").toString().trim().replace("\"", ""); + if (onapName==null||onapName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Onap Name given."; + LOGGER.error(message); + return message; + } + boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + if (!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + LOGGER.error(message); + return message; + } + String jsonBody = configBody.toString(); + // Create Policy. + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_Fault", policyName, policyParameters.getPolicyDescription(), onapName, + jsonBody, false, oldPolicyName, null, updateFlag, policyScope, 0, policyParameters.getRiskLevel(), + policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date); + //send JSON object to PAP + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigClosedLoop"); + return response; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java new file mode 100644 index 000000000..74c4bd71d --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ClosedLoopPMPolicyService.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Closed Loop PM policy Implementation. + * + * @version 0.1 + */ +public class ClosedLoopPMPolicyService{ + private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopPMPolicyService.class.getName()); + + private PAPServices papServices = null; + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String date = null; + private JsonObject configBody = null; + + public ClosedLoopPMPolicyService(String policyName, String policyScope, + PolicyParameters policyParameters, String date) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + this.date = date; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + if(policyParameters.getConfigBody()==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present"; + return false; + } + if(!PolicyApiUtils.validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + return false; + } + try{ + configBody = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); + } catch(JsonException| IllegalStateException e){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + LOGGER.error("Error during parsing JSON config body for Closed loop PM policy " , e); + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException{ + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + // get values and attributes from the JsonObject + if(!configBody.containsKey("onapname")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Onap Name given."; + LOGGER.error(message); + return message; + } + if(!configBody.containsKey("serviceTypePolicyName")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Service Type Policy Name given."; + LOGGER.error(message); + return message; + } + String onapName = configBody.get("onapname").toString().trim().replace("\"", ""); + if (onapName==null||onapName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Onap Name given."; + LOGGER.error(message); + return message; + } + boolean levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + if (!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + LOGGER.error(message); + return message; + } + String jsonBody = configBody.toString(); + String serviceType = configBody.get("serviceTypePolicyName").toString().replace("\"", ""); + // Create Policy. + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_PM", policyName, policyParameters.getPolicyDescription(), onapName, + jsonBody, false, null, serviceType, updateFlag, policyScope, 0, policyParameters.getRiskLevel(), + policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date); + //send JSON object to PAP + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigClosedLoop"); + return response; + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ConfigPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ConfigPolicyService.java new file mode 100644 index 000000000..c8d3d74d1 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ConfigPolicyService.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.util.Map; + +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Config Base Policy Implementation. + * + * @version 0.1 + */ +public class ConfigPolicyService { + private static final Logger LOGGER = FlexLogger.getLogger(ConfigPolicyService.class.getName()); + private PAPServices papServices = null; + + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String date = null; + private String onapName = null; + private String configName = null; + + public ConfigPolicyService(String policyName, String policyScope, + PolicyParameters policyParameters, String date) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + this.date = date; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + if(policyParameters.getConfigBody()==null || policyParameters.getConfigBody().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given."; + return false; + } + if(policyParameters.getConfigBodyType()==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body Type given."; + return false; + } + boolean levelCheck = false; + levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + if (!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + return false; + } + onapName = policyParameters.getOnapName(); + configName = policyParameters.getConfigName(); + if(onapName==null || onapName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ONAP Name given."; + return false; + } + if(configName==null || configName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config Name given."; + return false; + } + message = PolicyUtils.emptyPolicyValidator(onapName); + if(!message.contains("success")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; + return false; + } + message = PolicyUtils.emptyPolicyValidator(configName); + if(!message.contains("success")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException { + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + String configType = policyParameters.getConfigBodyType().toString(); + String body = policyParameters.getConfigBody(); + String configBody = null; + //check body for JSON form and remove single quotes if present + if ("JSON".equalsIgnoreCase(configType)) { + if (body.contains("'")) { + configBody = body.replace("'", "\""); + } else { + configBody = body; + } + } else { + configBody = body; + } + Map configAttributes = null; + if(policyParameters.getAttributes()!=null){ + configAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING); + } + // create Policy. + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Base", policyName, policyParameters.getPolicyDescription(), onapName, configName, configAttributes, configType, + configBody, updateFlag, policyScope,0, policyParameters.getRiskLevel(),policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date); + // Send Json to PAP. + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "Config"); + LOGGER.info(response); + return response; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java new file mode 100644 index 000000000..d8cca2bb9 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateConfigPolicyService.java @@ -0,0 +1,118 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.HashMap; +import java.util.Map; + +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyClass; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.PolicyType; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.models.ConfigPolicyAPIRequest; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class CreateUpdateConfigPolicyService { + private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdateConfigPolicyService.class.getName()); + + private String response = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + + public CreateUpdateConfigPolicyService( + ConfigPolicyAPIRequest configPolicyAPIRequest, String requestID, + boolean updateFlag) { + try{ + run(configPolicyAPIRequest, requestID, updateFlag); + }catch(PolicyException e){ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + private void run(ConfigPolicyAPIRequest configPolicyAPIRequest, + String requestID, boolean updateFlag) throws PolicyException{ + PolicyParameters policyParameters = new PolicyParameters(); + policyParameters.setPolicyClass(PolicyClass.Config); + policyParameters.setPolicyConfigType(PolicyConfigType.Base); + if(configPolicyAPIRequest.getPolicyScope()==null|| configPolicyAPIRequest.getPolicyScope().trim().isEmpty()){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; + LOGGER.error(message); + throw new PolicyException(message); + } + if(configPolicyAPIRequest.getPolicyName()==null|| configPolicyAPIRequest.getPolicyName().trim().isEmpty()){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + LOGGER.error(message); + throw new PolicyException(message); + } + policyParameters.setPolicyName(configPolicyAPIRequest.getPolicyScope()+"."+configPolicyAPIRequest.getPolicyName()); + policyParameters.setPolicyDescription(configPolicyAPIRequest.getPolicyDescription()); + policyParameters.setOnapName(configPolicyAPIRequest.getOnapName()); + policyParameters.setConfigName(configPolicyAPIRequest.getConfigName()); + Map> attributes = new HashMap<>(); + attributes.put(AttributeType.MATCHING, configPolicyAPIRequest.getConfigAttributes()); + policyParameters.setAttributes(attributes); + if(configPolicyAPIRequest.getConfigType()==null){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy ConfigType given."; + LOGGER.error(message); + throw new PolicyException(message); + } + try{ + policyParameters.setConfigBodyType(PolicyType.valueOf(configPolicyAPIRequest.getConfigType())); + }catch(IllegalArgumentException e){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Improper ConfigType given."; + LOGGER.error(message, e); + throw new PolicyException(message); + } + policyParameters.setConfigBody(configPolicyAPIRequest.getBody()); + policyParameters.setRiskLevel(configPolicyAPIRequest.getRiskLevel()); + policyParameters.setRiskType(configPolicyAPIRequest.getRiskType()); + policyParameters.setGuard(Boolean.parseBoolean(configPolicyAPIRequest.getGuard())); + if(configPolicyAPIRequest.getTtlDate()==null){ + LOGGER.warn("No TTL date given "); + policyParameters.setTtlDate(null); + }else{ + try { + policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(configPolicyAPIRequest.getTtlDate())); + } catch (ParseException e) { + LOGGER.warn("Error Parsing date given " + configPolicyAPIRequest.getTtlDate(), e); + policyParameters.setTtlDate(null); + } + } + CreateUpdatePolicyService createUpdatePolicyService = new CreateUpdatePolicyServiceImpl(policyParameters, requestID, updateFlag); + status = createUpdatePolicyService.getResponseCode(); + response = createUpdatePolicyService.getResult(); + } + + public String getResult() { + return response; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java new file mode 100644 index 000000000..9d2577426 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateDictionaryService.java @@ -0,0 +1,153 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.io.ByteArrayInputStream; +import java.util.UUID; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.onap.policy.api.DictionaryParameters; +import org.onap.policy.api.PolicyException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class CreateUpdateDictionaryService { + private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdateDictionaryService.class.getName()); + + private String dictionaryResult = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private String message = null; + private Boolean updateFlag = false; + private DictionaryParameters dictionaryParameters = null; + + public CreateUpdateDictionaryService( + DictionaryParameters dictionaryParameters, String requestID, + boolean updateFlag) { + this.updateFlag = updateFlag; + this.dictionaryParameters = dictionaryParameters; + if(dictionaryParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(),e); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.dictionaryParameters.setRequestID(requestUUID); + } + try{ + run(); + specialCheck(); + }catch(PolicyException e){ + dictionaryResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + private void specialCheck() { + if(dictionaryResult== null || dictionaryResult.contains("BAD REQUEST")||dictionaryResult.contains("PE300")){ + status = HttpStatus.BAD_REQUEST; + } else if (dictionaryResult.contains("Policy Exist Error")) { + status = HttpStatus.CONFLICT; + } else if (dictionaryResult.contains("PE200")){ + status = HttpStatus.INTERNAL_SERVER_ERROR; + } + } + + private void run() throws PolicyException{ + // Check Validation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyException(message); + } + // Get Result. + try{ + status = HttpStatus.OK; + dictionaryResult = processResult(); + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + private String processResult() throws PolicyException{ + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + JsonObject json = null; + try{ + json = PolicyApiUtils.stringToJsonObject(dictionaryParameters.getDictionaryJson()); + } catch(JsonException| IllegalStateException e){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper Dictionary JSON object : " + dictionaryParameters.getDictionaryJson(); + LOGGER.error(message, e); + return message; + } + String dictionaryFields = json.toString(); + PAPServices papServices = new PAPServices(); + return (String) papServices.callPAP(new ByteArrayInputStream(dictionaryFields.getBytes()), new String[] {"operation="+operation, "apiflag=api", "dictionaryType="+dictionaryParameters.getDictionary()}, dictionaryParameters.getRequestID(), "dictionaryItem"); + } + + private boolean getValidation() { + if(dictionaryParameters==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Dictionary Parameters are not given."; + return false; + } + if(dictionaryParameters.getDictionaryType()==null || dictionaryParameters.getDictionaryType().toString().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Type given."; + return false; + } + if(dictionaryParameters.getDictionary()==null || dictionaryParameters.getDictionary().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary given."; + return false; + } + if(dictionaryParameters.getDictionaryJson()==null || dictionaryParameters.getDictionaryJson().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary JSON given."; + return false; + } + if (updateFlag && "MicroServiceDictionary".equalsIgnoreCase(dictionaryParameters.getDictionary())&& !dictionaryParameters.getDictionaryJson().contains("initialFields")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Mising the required field initialFields."; + return false; + } + return true; + } + + public String getResult() { + return dictionaryResult; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java new file mode 100644 index 000000000..d4d686a13 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdateFirewallPolicyService.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import org.onap.policy.api.PolicyClass; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.models.ConfigFirewallPolicyAPIRequest; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class CreateUpdateFirewallPolicyService { + private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdateFirewallPolicyService.class.getName()); + + private String response = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + + public CreateUpdateFirewallPolicyService( + ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest, + String requestID, boolean updateFlag) { + try{ + run(configFirewallPolicyAPIRequest, requestID, updateFlag); + }catch(PolicyException e){ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + private void run( + ConfigFirewallPolicyAPIRequest configFirewallPolicyAPIRequest, + String requestID, boolean updateFlag) throws PolicyException{ + PolicyParameters policyParameters = new PolicyParameters(); + policyParameters.setPolicyClass(PolicyClass.Config); + policyParameters.setPolicyConfigType(PolicyConfigType.Firewall); + if(configFirewallPolicyAPIRequest.getPolicyScope()==null|| configFirewallPolicyAPIRequest.getPolicyScope().trim().isEmpty()){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; + LOGGER.error(message); + throw new PolicyException(message); + } + if(configFirewallPolicyAPIRequest.getPolicyName()==null|| configFirewallPolicyAPIRequest.getPolicyName().trim().isEmpty()){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + LOGGER.error(message); + throw new PolicyException(message); + } + policyParameters.setPolicyName(configFirewallPolicyAPIRequest.getPolicyScope()+"."+configFirewallPolicyAPIRequest.getPolicyName()); + policyParameters.setConfigBody(configFirewallPolicyAPIRequest.getFirewallJson()); + policyParameters.setRiskLevel(configFirewallPolicyAPIRequest.getRiskLevel()); + policyParameters.setRiskType(configFirewallPolicyAPIRequest.getRiskType()); + policyParameters.setGuard(Boolean.parseBoolean(configFirewallPolicyAPIRequest.getGuard())); + try { + policyParameters.setTtlDate(new SimpleDateFormat("dd-MM-yyyy").parse(configFirewallPolicyAPIRequest.getTtlDate())); + } catch (NullPointerException | ParseException e) { + LOGGER.warn("Error Parsing date given " + configFirewallPolicyAPIRequest.getTtlDate(), e); + policyParameters.setTtlDate(null); + } + CreateUpdatePolicyService createUpdatePolicyService = new CreateUpdatePolicyServiceImpl(policyParameters, requestID, updateFlag); + status = createUpdatePolicyService.getResponseCode(); + response = createUpdatePolicyService.getResult(); + } + + public String getResult() { + return response; + } + + public HttpStatus getResponseCode() { + return status; + } + +} \ No newline at end of file diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyService.java new file mode 100644 index 000000000..0ff5f4a0a --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyService.java @@ -0,0 +1,35 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import org.onap.policy.api.PolicyException; +import org.springframework.http.HttpStatus; + +public interface CreateUpdatePolicyService { + + public void run() throws PolicyException; + + public String processResult() throws PolicyException; + + public String getResult(); + + public HttpStatus getResponseCode(); + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java new file mode 100644 index 000000000..945cdba8b --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java @@ -0,0 +1,293 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class CreateUpdatePolicyServiceImpl implements CreateUpdatePolicyService { + private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdatePolicyServiceImpl.class.getName()); + + private String policyResult = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private Boolean updateFlag = false; + private String message = null; + private PolicyParameters policyParameters = new PolicyParameters(); + private String policyName = null; + private String policyScope = null; + private String date = null; + + public CreateUpdatePolicyServiceImpl(PolicyParameters policyParameters, + String requestID, boolean updateFlag) { + this.updateFlag = updateFlag; + this.policyParameters = policyParameters; + if(policyParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.policyParameters.setRequestID(requestUUID); + } + try{ + run(); + specialCheck(); + }catch(PolicyException e){ + policyResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + public void run() throws PolicyException{ + // Check Validation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyException(message); + } + // Get Result. + try{ + status = HttpStatus.OK; + policyResult = processResult(); + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + @SuppressWarnings("incomplete-switch") + public String processResult() throws PolicyException{ + String response = null; + if(policyParameters.getPolicyConfigType()!=null){ + // This is a Config Type Policy. + switch(policyParameters.getPolicyConfigType()){ + case BRMS_PARAM: + BRMSParamPolicyService bRMSParamPolicyService = new BRMSParamPolicyService(policyName, policyScope, policyParameters, date); + // Check Validation. + if(!bRMSParamPolicyService.getValidation()){ + LOGGER.error(bRMSParamPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return bRMSParamPolicyService.getMessage(); + } + // Get Result. + response = bRMSParamPolicyService.getResult(updateFlag); + break; + case BRMS_RAW: + BRMSRawPolicyService bRMSRawPolicyService = new BRMSRawPolicyService(policyName, policyScope, policyParameters, date); + // Check Validation. + if(!bRMSRawPolicyService.getValidation()){ + LOGGER.error(bRMSRawPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return bRMSRawPolicyService.getMessage(); + } + // Get Result. + response = bRMSRawPolicyService.getResult(updateFlag); + break; + case Base: + ConfigPolicyService configPolicyService = new ConfigPolicyService(policyName, policyScope, policyParameters, date); + // Check Validation. + if(!configPolicyService.getValidation()){ + LOGGER.error(configPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return configPolicyService.getMessage(); + } + // Get Result. + response = configPolicyService.getResult(updateFlag); + break; + case ClosedLoop_Fault: + ClosedLoopFaultPolicyService closedLoopFaultPolicyService = new ClosedLoopFaultPolicyService(policyName, policyScope, policyParameters, date); + // Check Validation. + if(!closedLoopFaultPolicyService.getValidation()){ + LOGGER.error(closedLoopFaultPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return closedLoopFaultPolicyService.getMessage(); + } + // Get Result. + response = closedLoopFaultPolicyService.getResult(updateFlag); + break; + case ClosedLoop_PM: + ClosedLoopPMPolicyService closedLoopPMPolicyService = new ClosedLoopPMPolicyService(policyName, policyScope, policyParameters, date); + // Check Validation. + if(!closedLoopPMPolicyService.getValidation()){ + LOGGER.error(closedLoopPMPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return closedLoopPMPolicyService.getMessage(); + } + // Get Result. + response = closedLoopPMPolicyService.getResult(updateFlag); + break; + case Firewall: + FirewallPolicyService firewallPolicyService = new FirewallPolicyService(policyName, policyScope, policyParameters, date); + // Check Validation. + if(!firewallPolicyService.getValidation()){ + LOGGER.error(firewallPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return firewallPolicyService.getMessage(); + } + // Get Result. + response = firewallPolicyService.getResult(updateFlag); + break; + case MicroService: + MicroServicesPolicyService microServicesPolicyService = new MicroServicesPolicyService(policyName, policyScope, policyParameters, date); + // Check Validation. + if(!microServicesPolicyService.getValidation()){ + LOGGER.error(microServicesPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return microServicesPolicyService.getMessage(); + } + // Get Result. + response = microServicesPolicyService.getResult(updateFlag); + break; + default: + String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " Invalid Config Type Present"; + LOGGER.error(message); + status = HttpStatus.BAD_REQUEST; + return message; + } + }else if (policyParameters.getPolicyClass()!=null){ + switch (policyParameters.getPolicyClass()){ + case Action: + ActionPolicyService actionPolicyService = new ActionPolicyService(policyScope, policyName, policyParameters); + // Check Validation. + if(!actionPolicyService.getValidation()){ + LOGGER.error(actionPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return actionPolicyService.getMessage(); + } + // Get Result. + response = actionPolicyService.getResult(updateFlag); + break; + case Decision: + DecisionPolicyService decisionPolicyService = new DecisionPolicyService(policyScope, policyName, policyParameters); + // Check Validation. + if(!decisionPolicyService.getValidation()){ + LOGGER.error(decisionPolicyService.getMessage()); + status = HttpStatus.BAD_REQUEST; + return decisionPolicyService.getMessage(); + } + // Get Result. + response = decisionPolicyService.getResult(updateFlag); + break; + } + }else { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Class found."; + LOGGER.error(message); + status = HttpStatus.BAD_REQUEST; + response = message; + } + return response; + } + + protected boolean getValidation() { + if(policyParameters == null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy parameters given. "; + return false; + } + if(policyParameters.getPolicyName() == null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + return false; + } + if (policyParameters.getPolicyName().contains(".")) { + policyName = policyParameters.getPolicyName().substring(policyParameters.getPolicyName().lastIndexOf('.') + 1, + policyParameters.getPolicyName().length()); + policyScope = policyParameters.getPolicyName().substring(0,policyParameters.getPolicyName().lastIndexOf('.')); + LOGGER.info("Name is " + policyName + " scope is " + policyScope); + } else { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; + return false; + } + if (policyName==null||policyName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + return false; + } + message = PolicyUtils.emptyPolicyValidator(policyScope); + if(!message.contains("success")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; + return false; + } + message = PolicyUtils.emptyPolicyValidator(policyName); + if(!message.contains("success")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; + return false; + } + if(policyParameters.getPolicyDescription()!=null){ + message = PolicyUtils.descriptionValidator(policyParameters.getPolicyDescription()); + if(!message.contains("success")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; + return false; + } + } + if(!PolicyApiUtils.validateNONASCIICharactersAndAllowSpaces(policyParameters.toString())){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "This requests contains Non ASCII Characters. Please review your input parameter" + + " values and correct the illegal characters."; + return false; + } + // Set some default Values. + if (policyParameters.getTtlDate()!=null){ + date = convertDate(policyParameters.getTtlDate()); + } + return true; + } + + protected String convertDate(Date date) { + String strDate = null; + if (date!=null) { + SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy"); + strDate = dateformatJava.format(date); + } + return (strDate==null) ? "NA": strDate; + } + + protected void specialCheck() { + if(policyResult== null || policyResult.contains("BAD REQUEST")||policyResult.contains("PE300")){ + status = HttpStatus.BAD_REQUEST; + } else if (policyResult.contains("Policy Exist Error")) { + status = HttpStatus.CONFLICT; + } else if (policyResult.contains("PE200")||policyResult.contains("PE900")){ + status = HttpStatus.INTERNAL_SERVER_ERROR; + } + } + + public String getResult() { + return policyResult; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DecisionPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DecisionPolicyService.java new file mode 100644 index 000000000..c283ff14c --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DecisionPolicyService.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.util.Map; + +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.RuleProvider; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Decision Policy Implementation + * + * @version 0.1 + */ +public class DecisionPolicyService{ + private static Logger LOGGER = FlexLogger.getLogger(DecisionPolicyService.class.getName()); + private static PAPServices papServices = null; + + private String message = null; + private String policyScope = null; + private String policyName = null; + private PolicyParameters policyParameters = null; + private String onapName = null; + + public DecisionPolicyService(String policyScope, String policyName, + PolicyParameters policyParameters) { + this.policyScope = policyScope; + this.policyName = policyName; + this.policyParameters = policyParameters; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + onapName = policyParameters.getOnapName(); + if (onapName==null||onapName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ONAP Name given."; + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException { + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + RuleProvider ruleProvider = policyParameters.getRuleProvider(); + if (ruleProvider==null) { + ruleProvider = RuleProvider.CUSTOM ; + } + Map matchingAttributes = null; + Map settingsAttributes = null; + if (policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)) { + matchingAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING); + settingsAttributes = policyParameters.getAttributes().get(AttributeType.SETTINGS); + }else if(policyParameters.getAttributes()!=null && !policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){ + settingsAttributes = policyParameters.getAttributes().get(AttributeType.SETTINGS); + }else if(policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && !policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){ + matchingAttributes = policyParameters.getAttributes().get(AttributeType.MATCHING); + } + // Create Policy. + StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyName, policyParameters.getPolicyDescription(), onapName, ruleProvider.toString(), matchingAttributes, settingsAttributes, policyParameters.getDynamicRuleAlgorithmLabels(), + policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmField2(), null, null, null, updateFlag, policyScope, 0); + // Send JSON to PAP. + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Decision"}, policyParameters.getRequestID(), "Decision"); + LOGGER.info(message); + return response; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java new file mode 100644 index 000000000..01670a5fd --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/DeletePolicyService.java @@ -0,0 +1,258 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.io.File; +import java.util.UUID; + +import org.onap.policy.api.DeletePolicyParameters; +import org.onap.policy.api.PolicyException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; +import org.springframework.http.HttpStatus; + +public class DeletePolicyService { + private static final Logger LOGGER = FlexLogger.getLogger(DeletePolicyService.class.getName()); + + private String deleteResult = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private DeletePolicyParameters deletePolicyParameters = null; + private String message = null; + private String filePrefix = null; + private String clientScope = null; + private String policyType = null; + private String policyName = null; + private String policyScope = null; + + public DeletePolicyService(DeletePolicyParameters deletePolicyParameters, + String requestID) { + this.deletePolicyParameters = deletePolicyParameters; + if(deletePolicyParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.deletePolicyParameters.setRequestID(requestUUID); + } + try{ + run(); + specialCheck(); + }catch(PolicyException e){ + deleteResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + private void specialCheck() { + if(deleteResult==null){ + return; + } + if (deleteResult.contains("BAD REQUEST")||deleteResult.contains("PE300")||deleteResult.contains("PE200")||deleteResult.contains("not exist")||deleteResult.contains("Invalid policyName")) { + status = HttpStatus.BAD_REQUEST; + } else if (deleteResult.contains("locked down")){ + status = HttpStatus.ACCEPTED; + } else if (deleteResult.contains("not Authorized")) { + status = HttpStatus.FORBIDDEN; + } else if (deleteResult.contains("groupId")) { + status = HttpStatus.NOT_FOUND; + } else if (deleteResult.contains("JPAUtils")||deleteResult.contains("database")||deleteResult.contains("policy file")|| + deleteResult.contains("unknown")||deleteResult.contains("configuration")) { + status = HttpStatus.INTERNAL_SERVER_ERROR; + } + } + + private void run() throws PolicyException{ + // Check Validation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyException(message); + } + // Get Result. + try{ + status = HttpStatus.OK; + deleteResult = processResult(); + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + private String processResult() throws PolicyException{ + String response = null; + String fullPolicyName = null; + String pdpGroup = deletePolicyParameters.getPdpGroup(); + // PDP Group Check. + if (pdpGroup==null){ + pdpGroup="NA"; + } + PAPServices papServices = new PAPServices(); + if (!deletePolicyParameters.getPolicyName().contains("xml")) { + + String activeVersion = papServices.getActiveVersion(policyScope, filePrefix, policyName, clientScope, deletePolicyParameters.getRequestID()); + LOGGER.debug("The active version of " + policyScope + File.separator + filePrefix + policyName + " is " + activeVersion); + String id = null; + if ("pe100".equalsIgnoreCase(activeVersion)) { + response = XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is 403. PEP is not Authorized for making this Request!! " + + "Contact Administrator for this Scope. "; + LOGGER.error(response); + return response; + } else if ("pe300".equalsIgnoreCase(activeVersion)) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404. " + + "This indicates a problem with getting the version from the PAP or the policy does not exist."; + LOGGER.error(response); + return response; + } + if (!activeVersion.equalsIgnoreCase("0")) { + id = policyScope + "." + filePrefix + policyName + "." + activeVersion + ".xml"; + LOGGER.debug("The policyId is " + id); + } else { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the activeVersion for this policy. could not retrieve the activeVersion for this policy. " + + "This indicates the policy does not exist, please verify the policy exists."; + LOGGER.error(response); + return response; + } + + fullPolicyName = policyScope + "." + filePrefix + policyName + "." + activeVersion + ".xml"; + + } else { + fullPolicyName = policyName; + } + + if ("PAP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())) { + if (deletePolicyParameters.getDeleteCondition()==null||deletePolicyParameters.getDeleteCondition().toString().trim().isEmpty()){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Delete Condition given."; + LOGGER.error(message); + return message; + } + + StdPAPPolicy deletePapPolicy = new StdPAPPolicy(fullPolicyName, deletePolicyParameters.getDeleteCondition().toString()); + //send JSON object to PAP + response = (String) papServices.callPAP(deletePapPolicy, new String[] {"groupId="+pdpGroup, "apiflag=deletePapApi", "operation=delete" }, deletePolicyParameters.getRequestID(), clientScope); + } else if ("PDP".equalsIgnoreCase(deletePolicyParameters.getPolicyComponent())) { + if (deletePolicyParameters.getPdpGroup()==null||deletePolicyParameters.getPdpGroup().trim().isEmpty()){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PDP Group given."; + LOGGER.error(message); + return message; + } + //send JSON object to PAP + response = (String) papServices.callPAP(null, new String[] {"policyName="+fullPolicyName, "groupId="+pdpGroup, "apiflag=deletePdpApi", "operation=delete" }, deletePolicyParameters.getRequestID(), clientScope); + } else { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Component does not exist. Please enter either PAP or PDP to delete the policy from a specified Policy Component."; + LOGGER.error(message); + response = message; + } + return response; + } + + private boolean getValidation() { + // While Validating, extract the required values. + if (deletePolicyParameters.getPolicyName()==null||deletePolicyParameters.getPolicyName().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + return false; + } + if (!deletePolicyParameters.getPolicyName().contains("xml")) { + if (deletePolicyParameters.getPolicyName() != null + && deletePolicyParameters.getPolicyName().contains(".")) { + policyName = deletePolicyParameters.getPolicyName().substring(deletePolicyParameters.getPolicyName().lastIndexOf(".") + 1, + deletePolicyParameters.getPolicyName().length()); + policyScope = deletePolicyParameters.getPolicyName().substring(0,deletePolicyParameters.getPolicyName().lastIndexOf(".")); + LOGGER.info("Name is " + policyName + " scope is " + policyScope); + } else { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; + return false; + } + } else { + policyName = deletePolicyParameters.getPolicyName(); + } + policyType = deletePolicyParameters.getPolicyType(); + if(policyType== null || policyType.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PolicyType given."; + return false; + } + setClientScope(); + if (clientScope==null||clientScope.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + deletePolicyParameters.getPolicyType() + " is not a valid Policy Type."; + LOGGER.error(message); + return false; + } + LOGGER.debug("clientScope is " + clientScope); + LOGGER.debug("filePrefix is " + filePrefix); + if(deletePolicyParameters.getPolicyComponent()==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Component given."; + return false; + } + return true; + } + + private void setClientScope() { + if ("Firewall".equalsIgnoreCase(policyType)) { + clientScope = "ConfigFirewall"; + filePrefix = "Config_FW_"; + } else if ("Action".equalsIgnoreCase(policyType)) { + clientScope = "Action"; + filePrefix = "Action_"; + } else if ("Decision".equalsIgnoreCase(policyType)) { + clientScope = "Decision"; + filePrefix = "Decision_"; + } else if ("Base".equalsIgnoreCase(policyType)) { + clientScope = "Config"; + filePrefix = "Config_"; + } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyType)) { + clientScope = "ConfigClosedLoop"; + filePrefix = "Config_Fault_"; + } else if ("ClosedLoop_PM".equalsIgnoreCase(policyType)) { + clientScope = "ConfigClosedLoop"; + filePrefix = "Config_PM_"; + } else if ("MicroService".equalsIgnoreCase(policyType)) { + clientScope = "ConfigMS"; + filePrefix = "Config_MS_"; + }else if ("BRMS_RAW".equalsIgnoreCase(policyType)) { + clientScope = "ConfigBrmsRaw"; + filePrefix = "Config_BRMS_Raw_"; + } else if ("BRMS_PARAM".equalsIgnoreCase(policyType)) { + clientScope = "ConfigBrmsParam"; + filePrefix = "Config_BRMS_Param_"; + } else { + clientScope = null; + message = XACMLErrorConstants.ERROR_DATA_ISSUE + policyType + + " is not a valid Policy Type."; + } + } + + public String getResult() { + return deleteResult; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/FirewallPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/FirewallPolicyService.java new file mode 100644 index 000000000..8f4ba9a79 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/FirewallPolicyService.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * Firewall Policy Implementation. + * + * @version 0.1 + */ +public class FirewallPolicyService { + private static final Logger LOGGER = FlexLogger.getLogger(FirewallPolicyService.class.getName()); + + private PAPServices papServices = null; + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String date = null; + private JsonObject firewallJson = null; + + public FirewallPolicyService(String policyName, String policyScope, + PolicyParameters policyParameters, String date) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + this.date = date; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + if(policyParameters.getConfigBody()==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given."; + return false; + } + try{ + firewallJson = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); + } catch(JsonException| IllegalStateException e){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + LOGGER.error("Error while parsing JSON body for creating Firewall Policy " , e); + return false; + } + if(firewallJson==null|| firewallJson.isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config-Body given."; + return false; + } + boolean levelCheck = false; + levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + if (!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException { + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + //set values for basic policy information + if(!firewallJson.containsKey("configName")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No configName given in firwall JSON."; + LOGGER.error(message); + return message; + } + String configName = firewallJson.get("configName").toString(); + String configDescription = ""; + String json = firewallJson.toString(); + // Create Policy. + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Firewall Config", policyName, configDescription, configName, updateFlag, policyScope, json, 0, + policyParameters.getRiskLevel(),policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date); + // Send Json to PAP. + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigFirewall"); + LOGGER.info(response); + return response; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetConfigService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetConfigService.java new file mode 100644 index 000000000..1817d8861 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetConfigService.java @@ -0,0 +1,318 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; + +import org.onap.policy.api.ConfigRequestParameters; +import org.onap.policy.api.PolicyConfigException; +import org.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.models.PDPResponse; +import org.onap.policy.pdp.rest.api.models.PolicyConfig; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class GetConfigService { + private static final Logger LOGGER = FlexLogger.getLogger(GetConfigService.class.getName()); + + private ConfigRequestParameters configRequestParameters = null; + private String message = null; + private HttpStatus responseCode = HttpStatus.BAD_REQUEST; + private Collection policyConfigs = null; + private boolean unique = false; + + public GetConfigService(ConfigRequestParameters configRequestParameters, + String requestID){ + this.configRequestParameters = configRequestParameters; + if(configRequestParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(),e); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.configRequestParameters.setRequestID(requestUUID); + } + policyConfigs = new ArrayList<>(); + try{ + run(); + specialCheck(); + }catch(PolicyConfigException e){ + LOGGER.error(e); + PolicyConfig policyConfig = new PolicyConfig(); + policyConfig.setPolicyConfigMessage(e.getMessage()); + policyConfig.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); + policyConfigs.add(policyConfig); + responseCode = HttpStatus.BAD_REQUEST; + } + } + + private void specialCheck() { + if(policyConfigs==null || policyConfigs.isEmpty()){ + responseCode = HttpStatus.BAD_REQUEST; + }else if(policyConfigs.size()==1){ + for(PolicyConfig policyConfig: policyConfigs){ + if(policyConfig.getPolicyConfigMessage()!=null && policyConfig.getPolicyConfigMessage().contains("PE300")){ + responseCode = HttpStatus.BAD_REQUEST; + } + } + }else{ + responseCode = HttpStatus.OK; + } + } + + private void run() throws PolicyConfigException{ + // getValidation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyConfigException(message); + } + // Generate Request. + String modelString = getModel().toString(); + LOGGER.debug("Generated JSON Request is: " + modelString); + if(configRequestParameters.getUnique()){ + LOGGER.info("Requested for Unique Result only. "); + unique = true; + } + // Process Result. + try { + PDPServices pdpServices = new PDPServices(); + responseCode = HttpStatus.OK; + policyConfigs = configResult(pdpServices.generateRequest(modelString, configRequestParameters.getRequestID(), unique, false)); + // Filter addition. + policyConfigs = filterResults(policyConfigs, configRequestParameters); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + responseCode = HttpStatus.BAD_REQUEST; + throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e); + } + } + + private Collection configResult( + Collection generateRequest) { + Collection result = new HashSet<>(); + if (generateRequest == null) { + return null; + } + if (!generateRequest.isEmpty()) { + for (PDPResponse stdStatus : generateRequest) { + PolicyConfig policyConfig = new PolicyConfig(); + policyConfig.setConfig(stdStatus.getConfig()); + policyConfig.setMatchingConditions(stdStatus.getMatchingConditions()); + policyConfig.setPolicyConfigMessage(stdStatus.getPolicyConfigMessage()); + policyConfig.setPolicyConfigStatus(stdStatus.getPolicyConfigStatus()); + policyConfig.setPolicyName(stdStatus.getPolicyName()); + policyConfig.setPolicyVersion(stdStatus.getPolicyVersion()); + policyConfig.setProperty(stdStatus.getProperty()); + policyConfig.setResponseAttributes(stdStatus.getResponseAttributes()); + policyConfig.setType(stdStatus.getType()); + result.add(policyConfig); + } + } + return result; + } + + // Filter logic required for results comparing with requests. + private Collection filterResults( + Collection policyConfigs, + ConfigRequestParameters configRequestParameters) { + List policyConfig = new ArrayList<>(); + for(PolicyConfig config: policyConfigs){ + if(config.getPolicyName()!=null && configRequestParameters.getPolicyName()!=null && configRequestParameters.getPolicyName().trim().length()>0){ + if(!config.getPolicyName().matches(configRequestParameters.getPolicyName())){ + continue; + } + } + if(config.getMatchingConditions()!=null && config.getMatchingConditions().size()>0){ + if(configRequestParameters.getOnapName()!=null && configRequestParameters.getOnapName().trim().length()>0 && config.getMatchingConditions().containsKey("ONAPName")){ + if(!config.getMatchingConditions().get("ONAPName").matches(configRequestParameters.getOnapName())){ + continue; + } + } + if(configRequestParameters.getConfigName()!=null && configRequestParameters.getConfigName().trim().length()>0 && config.getMatchingConditions().containsKey("ConfigName")){ + if(!config.getMatchingConditions().get("ConfigName").matches(configRequestParameters.getConfigName())){ + continue; + } + } + if(configRequestParameters.getConfigAttributes()!=null && configRequestParameters.getConfigAttributes().size()>0){ + boolean flag = false; + for(String key: configRequestParameters.getConfigAttributes().keySet()){ + if(key.equals("RiskType")||key.equals("RiskLevel")||key.equals("guard")||key.equals("TTLDate")){ + continue; + } + if(config.getMatchingConditions().containsKey(key)){ + if(config.getMatchingConditions().get(key).contains(",")){ + List elements = Arrays.asList(config.getMatchingConditions().get(key).split(",")); + if(!elements.contains(configRequestParameters.getConfigAttributes().get(key))){ + flag=true; + } + }else if(!config.getMatchingConditions().get(key).matches(configRequestParameters.getConfigAttributes().get(key))){ + flag = true; + } + }else{ + flag = true; + } + if(flag){ + break; + } + } + if(flag){ + continue; + } + } + } + policyConfig.add(config); + } + if(policyConfig.isEmpty()){ + PolicyConfig pConfig = new PolicyConfig(); + pConfig.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); + pConfig.setPolicyConfigMessage(XACMLErrorConstants.ERROR_DATA_ISSUE+"No Match Found, for the parameters sent."); + policyConfig.add(pConfig); + } + return policyConfig; + } + + private JsonObject getModel() throws PolicyConfigException{ + String policyName = configRequestParameters.getPolicyName(); + if(policyName!= null && !policyName.trim().isEmpty() && !policyName.endsWith("xml")){ + policyName = policyName + ".[\\d].*"; + configRequestParameters.setPolicyName(policyName); + } + JsonArrayBuilder subjectArray = Json.createArrayBuilder(); + JsonArrayBuilder resourceArray = Json.createArrayBuilder(); + if(configRequestParameters.getPolicyName()!=null){ + JsonObjectBuilder subjectBuilder = Json.createObjectBuilder(); + subjectBuilder.add("Value", policyName); + subjectBuilder.add("AttributeId", "PolicyName"); + subjectArray.add(subjectBuilder); + }else{ + LOGGER.info("PolicyName values are not given. "); + } + if(configRequestParameters.getOnapName()!=null){ + JsonObjectBuilder subjectBuilder = Json.createObjectBuilder(); + subjectBuilder.add("Value", configRequestParameters.getOnapName()); + subjectBuilder.add("AttributeId", "ONAPName"); + subjectArray.add(subjectBuilder); + if(configRequestParameters.getConfigName()!=null){ + subjectBuilder = Json.createObjectBuilder(); + subjectBuilder.add("Value", configRequestParameters.getConfigName()); + subjectBuilder.add("AttributeId", "ConfigName"); + subjectArray.add(subjectBuilder); + resourceArray = getResourceArray(configRequestParameters.getConfigAttributes()); + }else{ + LOGGER.info("Config Name is not given. "); + } + }else{ + LOGGER.info("Onap Name is not given. "); + } + return Json.createObjectBuilder() + .add("Request",Json.createObjectBuilder() + .add("AccessSubject",Json.createObjectBuilder() + .add("Attribute",subjectArray)) + .add("Action",Json.createObjectBuilder() + .add("Attribute",Json.createObjectBuilder() + .add("Value","ACCESS") + .add("AttributeId","urn:oasis:names:tc:xacml:1.0:action:action-id"))) + .add("Resource",Json.createObjectBuilder() + .add("Attribute",resourceArray + .add(Json.createObjectBuilder() + .add("Value","Config") + .add("AttributeId","urn:oasis:names:tc:xacml:1.0:resource:resource-id"))))) + .build(); + } + + private JsonArrayBuilder getResourceArray(Map configAttributes) throws PolicyConfigException{ + JsonArrayBuilder resourceArray = Json.createArrayBuilder(); + configAttributes = configRequestParameters.getConfigAttributes(); + if (configAttributes != null && !configAttributes.isEmpty()) { + if(!configAttributes.containsKey("RiskType")){ + configAttributes.put("RiskType", ".*"); + } + if(!configAttributes.containsKey("RiskLevel")){ + configAttributes.put("RiskLevel", ".*"); + } + if(!configAttributes.containsKey("guard")){ + configAttributes.put("guard", ".*"); + } + if(!configAttributes.containsKey("TTLDate")){ + configAttributes.put("TTLDate", ".*"); + } + }else{ + // ConfigAttributes is Null. So add basic values. + configAttributes = new HashMap<>(); + configAttributes.put("RiskType", ".*"); + configAttributes.put("RiskLevel", ".*"); + configAttributes.put("guard", ".*"); + configAttributes.put("TTLDate", ".*"); + } + for (String key : configAttributes.keySet()) { + if (key.isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key"; + LOGGER.error(message); + throw new PolicyConfigException(message); + } + JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); + resourceBuilder.add("Value", configAttributes.get(key)); + resourceBuilder.add("AttributeId", key); + resourceArray.add(resourceBuilder); + } + return resourceArray; + } + + private Boolean getValidation(){ + if(configRequestParameters==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No config Request Parameters given."; + return false; + } + if(configRequestParameters.getOnapName()==null && configRequestParameters.getPolicyName()==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot proceed without onapComponentName or PolicyName"; + return false; + } + return true; + } + + public Collection getResult() { + return policyConfigs; + } + + public HttpStatus getResponseCode() { + return responseCode; + } +} \ No newline at end of file diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDecisionService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDecisionService.java new file mode 100644 index 000000000..66beb0663 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDecisionService.java @@ -0,0 +1,189 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; + +import org.onap.policy.api.DecisionRequestParameters; +import org.onap.policy.api.DecisionResponse; +import org.onap.policy.api.PolicyDecision; +import org.onap.policy.api.PolicyDecisionException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.models.PDPResponse; +import org.onap.policy.std.StdDecisionResponse; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class GetDecisionService { + private static final Logger LOGGER = FlexLogger.getLogger(GetDecisionService.class.getName()); + + private DecisionResponse decisionResponse = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private DecisionRequestParameters decisionRequestParameters = null; + private String message = null; + private String onapComponentName = null; + private Map decisionAttributes = null; + + public GetDecisionService( + DecisionRequestParameters decisionRequestParameters, + String requestID) { + this.decisionRequestParameters = decisionRequestParameters; + if(decisionRequestParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(),e); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.decisionRequestParameters.setRequestID(requestUUID); + } + try{ + run(); + }catch(PolicyDecisionException e){ + StdDecisionResponse decisionResponse = new StdDecisionResponse(); + decisionResponse.setDecision(PolicyDecision.ERROR); + decisionResponse.setDetails(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + this.decisionResponse = decisionResponse; + status = HttpStatus.BAD_REQUEST; + } + } + + private void run() throws PolicyDecisionException{ + // Get Validation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyDecisionException(message); + } + // Generate Request. + String modelString = getModel().toString(); + LOGGER.debug("Generated JSON Request is: " + modelString); + // Process Result. + try { + PDPServices pdpServices = new PDPServices(); + status = HttpStatus.OK; + decisionResponse = decisionResult(pdpServices.generateRequest(modelString, decisionRequestParameters.getRequestID(), false, true)); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyDecisionException(e); + } + } + + private DecisionResponse decisionResult( + Collection generateRequest) { + StdDecisionResponse policyDecision = new StdDecisionResponse(); + if (generateRequest == null) { + return policyDecision; + } + if (!generateRequest.isEmpty()) { + for (PDPResponse stdStatus : generateRequest) { + policyDecision.setDecision(stdStatus.getDecision()); + policyDecision.setDetails(stdStatus.getDetails()); + } + } + return policyDecision; + } + + private JsonObject getModel() throws PolicyDecisionException{ + JsonArrayBuilder resourceArray = Json.createArrayBuilder(); + for (Entry key : decisionAttributes.entrySet()) { + if (key.getKey().isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key"; + LOGGER.error(message); + throw new PolicyDecisionException(message); + } + JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); + if (key.getValue().matches("[0-9]+")) { + + if ((key.getKey().equals("ErrorCode")) || (key.getKey().equals("WorkStep"))) { + + resourceBuilder.add("Value", key.getValue()); + + } else { + + int val = Integer.parseInt(key.getValue()); + resourceBuilder.add("Value", val); + + } + + } else { + resourceBuilder.add("Value", key.getValue()); + } + resourceBuilder.add("AttributeId", key.getKey()); + resourceArray.add(resourceBuilder); + } + return Json.createObjectBuilder() + .add("Request", Json.createObjectBuilder() + .add("AccessSubject", Json.createObjectBuilder() + .add("Attribute", Json.createObjectBuilder() + .add("Value", onapComponentName) + .add("AttributeId", "ONAPName"))) + .add("Resource", Json.createObjectBuilder() + .add("Attribute", resourceArray)) + .add("Action", Json.createObjectBuilder() + .add("Attribute", Json.createObjectBuilder() + .add("Value", "DECIDE") + .add("AttributeId", "urn:oasis:names:tc:xacml:1.0:action:action-id")))) + .build(); + } + + private boolean getValidation() { + if(decisionRequestParameters==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Paramaters"; + return false; + } + onapComponentName = decisionRequestParameters.getONAPComponentName(); + decisionAttributes = decisionRequestParameters.getDecisionAttributes(); + if (onapComponentName == null || onapComponentName.isEmpty()) { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No onapComponentName given : " + onapComponentName; + return false; + } + if (decisionAttributes == null || decisionAttributes.isEmpty()) { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Attributes Given. "; + return false; + } + return true; + } + + public DecisionResponse getResult() { + return decisionResponse; + } + + public HttpStatus getResponseCode() { + return status; + } + +} + diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDictionaryService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDictionaryService.java new file mode 100644 index 000000000..8f88ef7c7 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetDictionaryService.java @@ -0,0 +1,276 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.util.UUID; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.onap.policy.api.DictionaryParameters; +import org.onap.policy.api.DictionaryResponse; +import org.onap.policy.api.PolicyException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.std.StdDictionaryResponse; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class GetDictionaryService { + private static final Logger LOGGER = FlexLogger.getLogger(GetDictionaryService.class.getName()); + + private DictionaryResponse dictionaryResponse = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private String message = null; + private DictionaryParameters dictionaryParameters = null; + + public GetDictionaryService(DictionaryParameters dictionaryParameters, + String requestID) { + this.dictionaryParameters = dictionaryParameters; + if(dictionaryParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.dictionaryParameters.setRequestID(requestUUID); + } + try{ + run(); + specialCheck(); + }catch(PolicyException e){ + StdDictionaryResponse dictionaryResponse = new StdDictionaryResponse(); + dictionaryResponse.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + this.dictionaryResponse = dictionaryResponse; + status = HttpStatus.BAD_REQUEST; + } + } + + private void specialCheck() { + if(dictionaryResponse!=null && (dictionaryResponse.getResponseMessage()!=null && dictionaryResponse.getResponseMessage().contains("PE300"))){ + status = HttpStatus.BAD_REQUEST; + } + } + + private void run() throws PolicyException{ + // Check Validation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyException(message); + } + // Get Result. + try{ + status = HttpStatus.OK; + dictionaryResponse = processResult(); + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + private DictionaryResponse processResult() throws PolicyException{ + StdDictionaryResponse response = new StdDictionaryResponse(); + PAPServices papServices = new PAPServices(); + String result = (String) papServices.callPAP(null, new String[] {"operation=get", "apiflag=api", "dictionaryType="+dictionaryParameters.getDictionary()}, dictionaryParameters.getRequestID(), "dictionaryItem"); + + if (result!=null && result.contains("data")) { + String jsonString = formatDictionaryJson(result); + String responseMessage = result.substring(0, 82); + JsonObject json = null; + try{ + json = PolicyApiUtils.stringToJsonObject(jsonString.replace("\\\\\\", "\\")); + String datas = json.getString("data").replaceFirst("\"\\[", "["); + int i = datas.lastIndexOf("]"); + if( i>=0 ) { + datas = new StringBuilder(datas).replace(i, i+2,"]").toString(); + } + json = PolicyApiUtils.stringToJsonObject(datas); + } catch(JsonException| IllegalStateException e){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper Dictionary JSON object : " + dictionaryParameters.getDictionaryJson(); + LOGGER.error(message, e); + response.setResponseMessage(message); + response.setResponseCode(400); + return response; + } + response.setResponseCode(papServices.getResponseCode()); + response.setDictionaryJson(json); + response.setResponseMessage(responseMessage); + } else { + response.setResponseCode(400); + response.setResponseMessage(result); + if(result!=null && result.contains("PE200")){ + status=HttpStatus.INTERNAL_SERVER_ERROR; + }else{ + status=HttpStatus.BAD_REQUEST; + } + } + return response; + } + + private String formatDictionaryJson(String result) { + String jsonString = result.substring(82); + String dictionary = dictionaryParameters.getDictionary(); + + switch (dictionary) { + case "OnapName": + jsonString = jsonString.replace("onapNameDictionaryDatas", "DictionaryDatas"); + break; + case "Attribute": + jsonString = jsonString.replace("attributeDictionaryDatas", "DictionaryDatas"); + break; + case "Action": + jsonString = jsonString.replace("actionPolicyDictionaryDatas", "DictionaryDatas"); + break; + case "BRMSParamTemplate": + jsonString = jsonString.replace("brmsParamDictionaryDatas", "DictionaryDatas"); + break; + case "VSCLAction": + jsonString = jsonString.replace("vsclActionDictionaryDatas", "DictionaryDatas"); + break; + case "VNFType": + jsonString = jsonString.replace("vnfTypeDictionaryDatas", "DictionaryDatas"); + break; + case "PEPOptions": + jsonString = jsonString.replace("pepOptionsDictionaryDatas", "DictionaryDatas"); + break; + case "Varbind": + jsonString = jsonString.replace("varbindDictionaryDatas", "DictionaryDatas"); + break; + case "Service": + jsonString = jsonString.replace("closedLoopServiceDictionaryDatas", "DictionaryDatas"); + break; + case "Site": + jsonString = jsonString.replace("closedLoopSiteDictionaryDatas", "DictionaryDatas"); + break; + case "Settings": + jsonString = jsonString.replace("settingsDictionaryDatas", "DictionaryDatas"); + break; + case "DescriptiveScope": + jsonString = jsonString.replace("descriptiveScopeDictionaryDatas", "DictionaryDatas"); + break; + case "Enforcer": + jsonString = jsonString.replace("enforcerDictionaryDatas", "DictionaryDatas"); + break; + case "ActionList": + jsonString = jsonString.replace("actionListDictionaryDatas", "DictionaryDatas"); + break; + case "ProtocolList": + jsonString = jsonString.replace("protocolListDictionaryDatas", "DictionaryDatas"); + break; + case "Zone": + jsonString = jsonString.replace("zoneDictionaryDatas", "DictionaryDatas"); + break; + case "SecurityZone": + jsonString = jsonString.replace("securityZoneDictionaryDatas", "DictionaryDatas"); + break; + case "PrefixList": + jsonString = jsonString.replace("prefixListDictionaryDatas", "DictionaryDatas"); + break; + case "AddressGroup": + jsonString = jsonString.replace("addressGroupDictionaryDatas", "DictionaryDatas"); + break; + case "ServiceGroup": + jsonString = jsonString.replace("serviceGroupDictionaryDatas", "DictionaryDatas"); + break; + case "ServiceList": + jsonString = jsonString.replace("serviceListDictionaryDatas", "DictionaryDatas"); + break; + case "TermList": + case "RuleList": + case "FirewallRuleList": + case "Term": + jsonString = jsonString.replace("termListDictionaryDatas", "DictionaryDatas"); + break; + case "MicroServiceLocation": + jsonString = jsonString.replace("microServiceLocationDictionaryDatas", "DictionaryDatas"); + break; + case "MicroServiceConfigName": + jsonString = jsonString.replace("microServiceCongigNameDictionaryDatas", "DictionaryDatas"); + break; + case "DCAEUUID": + jsonString = jsonString.replace("dcaeUUIDDictionaryDatas", "DictionaryDatas"); + break; + case "MicroServiceModels": + jsonString = jsonString.replace("microServiceModelsDictionaryDatas", "DictionaryDatas"); + break; + case "PolicyScopeService": + jsonString = jsonString.replace("psServiceDictionaryDatas", "DictionaryDatas"); + break; + case "PolicyScopeResource": + jsonString = jsonString.replace("psResourceDictionaryDatas", "DictionaryDatas"); + break; + case "PolicyScopeType": + jsonString = jsonString.replace("psTypeDictionaryDatas", "DictionaryDatas"); + break; + case "PolicyScopeClosedLoop": + jsonString = jsonString.replace("psClosedLoopDictionaryDatas", "DictionaryDatas"); + break; + case "GroupPolicyScopeList": + jsonString = jsonString.replace("groupPolicyScopeListDatas", "DictionaryDatas"); + break; + case "RiskType": + jsonString = jsonString.replace("riskTypeDictionaryDatas", "DictionaryDatas"); + break; + case "SafePolicyWarning": + jsonString = jsonString.replace("safePolicyWarningDatas", "DictionaryDatas"); + break; + case "MicroServiceDictionary": + jsonString = jsonString.replace("microServiceDictionaryDatas", "DictionaryDatas"); + break; + default: + return null; + } + return jsonString; + } + + private boolean getValidation() { + if(dictionaryParameters==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Dictionary Parameters are not given."; + return false; + } + if(dictionaryParameters.getDictionaryType()==null || dictionaryParameters.getDictionaryType().toString().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Type given."; + return false; + } + if(dictionaryParameters.getDictionary()==null || dictionaryParameters.getDictionary().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary given."; + return false; + } + return true; + } + + public DictionaryResponse getResult() { + return dictionaryResponse; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetMetricsService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetMetricsService.java new file mode 100644 index 000000000..a0a477cdf --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/GetMetricsService.java @@ -0,0 +1,157 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.util.UUID; + +import javax.json.JsonException; + +import org.json.JSONObject; +import org.onap.policy.api.MetricsRequestParameters; +import org.onap.policy.api.MetricsResponse; +import org.onap.policy.api.PolicyException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.std.StdMetricsResponse; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class GetMetricsService { + private static final Logger LOGGER = FlexLogger + .getLogger(GetMetricsService.class.getName()); + + private MetricsResponse response = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private MetricsRequestParameters metricsParameters = null; + + public GetMetricsService(String requestID) { + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); + } + } else { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + metricsParameters = new MetricsRequestParameters(); + this.metricsParameters.setRequestID(requestUUID); + + try { + run(); + specialCheck(); + } catch (PolicyException e) { + StdMetricsResponse metricsResponse = new StdMetricsResponse(); + metricsResponse + .setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + + e); + this.response = metricsResponse; + status = HttpStatus.BAD_REQUEST; + } + } + + private void specialCheck() { + if (response != null && (response.getResponseMessage() != null + && response.getResponseMessage().contains("PE300"))) { + status = HttpStatus.BAD_REQUEST; + } + } + + private void run() throws PolicyException { + // Get Result. + try { + status = HttpStatus.OK; + response = processResult(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + private MetricsResponse processResult() throws PolicyException { + StdMetricsResponse metricsResponse = new StdMetricsResponse(); + PAPServices papServices = new PAPServices(); + String result = (String) papServices.callPAP(null, new String[] { + "operation=get", "apiflag=getMetrics" }, + metricsParameters.getRequestID(), "metrics"); + + JSONObject json = null; + String message = null; + if (result != null) { + if (result.length() > 81 && result.contains("{")) { + try { + String responseMessage = result.substring(0, 82); + String jsonString = result.substring(result.indexOf('{'), + result.length()); + json = new JSONObject(jsonString); + + int papCount = (int) json.get("papCount"); + int pdpCount = (int) json.get("pdpCount"); + + metricsResponse.setResponseCode(papServices + .getResponseCode()); + metricsResponse.setResponseMessage(responseMessage); + metricsResponse.setPapMetrics(papCount); + metricsResponse.setPdpMetrics(pdpCount); + + } catch (JsonException | IllegalStateException e) { + String jsonString = null; + if(json != null){ + jsonString = json.toString(); + } + message = XACMLErrorConstants.ERROR_DATA_ISSUE + + " improper JSON object : " + jsonString; + LOGGER.error(message + e); + metricsResponse.setResponseMessage(message); + metricsResponse.setResponseCode(400); + return metricsResponse; + } + } else { + message = result; + metricsResponse.setResponseCode(400); + metricsResponse.setResponseMessage(message); + return metricsResponse; + } + + } else { + message = XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "There was an issue with connecting to the PAP, " + + "review the logs for further debugging."; + metricsResponse.setResponseCode(500); + metricsResponse.setResponseMessage(message); + return metricsResponse; + } + + return metricsResponse; + } + + public MetricsResponse getResult() { + return response; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ListConfigService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ListConfigService.java new file mode 100644 index 000000000..26f491963 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/ListConfigService.java @@ -0,0 +1,64 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.util.ArrayList; +import java.util.Collection; + +import org.onap.policy.api.ConfigRequestParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.models.PolicyConfig; +import org.springframework.http.HttpStatus; + +public class ListConfigService { + private static Logger LOGGER = FlexLogger.getLogger(ListConfigService.class.getName()); + + private Collection results = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + + public ListConfigService(ConfigRequestParameters configRequestParameters, + String requestID) { + GetConfigService getConfigService = new GetConfigService(configRequestParameters,requestID); + Collection policyConfigs = getConfigService.getResult(); + LOGGER.info("Transferring Config Results to List. "); + if(policyConfigs!=null){ + results = new ArrayList(); + status = HttpStatus.OK; + for(PolicyConfig policyConfig : policyConfigs){ + if(policyConfig.getPolicyConfigMessage()!=null && policyConfig.getPolicyConfigMessage().contains("PE300")){ + results.add(policyConfig.getPolicyConfigMessage()); + status = HttpStatus.BAD_REQUEST; + } else { + results.add("Policy Name: " + policyConfig.getPolicyName()); + } + } + } + } + + public Collection getResult() { + return results; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/MicroServicesPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/MicroServicesPolicyService.java new file mode 100644 index 000000000..22d8873d7 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/MicroServicesPolicyService.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import javax.json.JsonException; +import javax.json.JsonObject; + +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +/** + * MicroServices Policy implementation. + * + * @version 0.1 + */ +public class MicroServicesPolicyService{ + private static final Logger LOGGER = FlexLogger.getLogger(MicroServicesPolicyService.class.getName()); + + private PAPServices papServices = null; + private PolicyParameters policyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String date = null; + private String onapName = null; + private JsonObject microServiceAttributes = null; + + public MicroServicesPolicyService(String policyName, String policyScope, PolicyParameters policyParameters, String date) { + this.policyParameters = policyParameters; + this.policyName = policyName; + this.policyScope = policyScope; + this.date = date; + papServices = new PAPServices(); + } + + public Boolean getValidation() { + if(policyParameters.getConfigBody()==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Micro Service or Attributes Config Body Present"; + return false; + } + try{ + microServiceAttributes = PolicyApiUtils.stringToJsonObject(policyParameters.getConfigBody()); + } catch(JsonException| IllegalStateException e){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody(); + LOGGER.error("Error while parsing JSON body for MicroService Policy creation. ", e); + return false; + } + onapName = policyParameters.getOnapName(); + if (onapName==null||onapName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Onap Name given."; + return false; + } + boolean levelCheck = false; + levelCheck = PolicyApiUtils.isNumeric(policyParameters.getRiskLevel()); + if (!levelCheck){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given."; + return false; + } + return true; + } + + public String getMessage() { + return message; + } + + public String getResult(boolean updateFlag) throws PolicyException{ + String response = null; + String operation = null; + if (updateFlag){ + operation = "update"; + } else { + operation = "create"; + } + // get values and attributes from the JsonObject + String uuid = null; + String msLocation = null; + String configName = null; + String microService = null; + String policyDescription=null; + String priority=null; + String version=null; + if (microServiceAttributes.get("service")!=null){ + microService = microServiceAttributes.get("service").toString().replace("\"", ""); + } + if (microServiceAttributes.get("uuid")!=null){ + uuid = microServiceAttributes.get("uuid").toString().replace("\"", ""); + } + if (microServiceAttributes.get("location")!=null){ + msLocation = microServiceAttributes.get("location").toString().replace("\"", ""); + } + if (microServiceAttributes.get("configName")!=null){ + configName = microServiceAttributes.get("configName").toString().replace("\"", ""); + } + if(microServiceAttributes.containsKey("description")){ + policyDescription = microServiceAttributes.get("description").toString().replace("\"", ""); + } + if(microServiceAttributes.containsKey("priority")){ + priority = microServiceAttributes.get("priority").toString().replace("\"", ""); + } + if(microServiceAttributes.containsKey("version")){ + version = microServiceAttributes.get("version").toString().replace("\"", ""); + } + // Create Policy. + StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Micro Service", policyName, policyDescription, onapName, + configName, microService, uuid, msLocation, microServiceAttributes.toString(), priority, + version, updateFlag, policyScope, 0, policyParameters.getRiskLevel(), + policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date); + // Send JSON Object to PAP. + response = (String) papServices.callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, policyParameters.getRequestID(), "ConfigMS"); + LOGGER.info("Policy MS created Response: " + response); + return response; + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/NotificationService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/NotificationService.java new file mode 100644 index 000000000..c1b9f63e1 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/NotificationService.java @@ -0,0 +1,314 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.onap.policy.api.PolicyException; +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.utils.BusPublisher; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +import com.att.research.xacml.util.XACMLProperties; + +public class NotificationService { + public static final String BACKUPFILE = "topicBackup.txt"; + private static Logger logger = FlexLogger.getLogger(GetDictionaryService.class.getName()); + private static ConcurrentHashMap topicQueue = new ConcurrentHashMap<>(); + private static int interval = 15000; + private static Thread backUpthread = null; + private static Object resourceLock = new Object(); + private static List dmaapList = null; + private static String dmaapServers = null; + private static String aafLogin = null; + private static String aafPassword = null; + + private String notificationResponse = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + + /** + * NotificationService Constructor. + * + * @param notificationTopic Topic Name in String format. + * @param requestID Request ID in String format. + * @param serviceType Needs to be NotificationServiceType based enumeration value. + */ + public NotificationService(String notificationTopic, String requestID, NotificationServiceType serviceType) { + init(); + if(dmaapServers==null || aafLogin==null || aafPassword==null){ + notificationResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file"; + return; + } + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + logger.info("Generated Random UUID: " + requestUUID.toString(), e); + } + }else{ + requestUUID = UUID.randomUUID(); + logger.info("Generated Random UUID: " + requestUUID.toString()); + } + try{ + run(notificationTopic, serviceType); + }catch(PolicyException e){ + notificationResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + private static void init() { + if(dmaapServers==null || aafLogin==null || aafPassword==null){ + dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); + aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN"); + aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD"); + interval = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_DELAY, Integer.toString(interval))); + if(dmaapServers==null || aafLogin==null || aafPassword==null){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); + return; + } + // Cleanup Values. + dmaapServers= dmaapServers.trim(); + aafLogin = aafLogin.trim(); + aafPassword = aafPassword.trim(); + // Get servers to List. + if(dmaapServers.contains(",")) { + dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*"))); + } else { + dmaapList = new ArrayList<>(); + dmaapList.add(dmaapServers); + } + callThread(); + } + } + + private void run(String notificationTopic, NotificationServiceType serviceType) throws PolicyException{ + // Check Validation + if(notificationTopic==null){ + String message = "Notification Topic is null"; + logger.error(message); + throw new PolicyException(message); + } + notificationTopic = notificationTopic.trim(); + if(notificationTopic.isEmpty()){ + String message = "Notification Topic is not valid. "; + logger.error(message); + throw new PolicyException(message); + } + // if already exists give error.Saying already registered. + // Get Result. + try{ + status = HttpStatus.OK; + switch (serviceType) { + case ADD: + addTopic(notificationTopic); + notificationResponse = "Success!! Please give permissions to " + aafLogin + " that PDP will use to publish on given topic :" + notificationTopic + + "\n Start calling /sendHeartbeat API at an interval less than " + Integer.toString(interval) + "ms"; + break; + case REMOVE: + removeTopic(notificationTopic); + notificationResponse = "Notification Topic :" + notificationTopic + " has been removed and PDP will not publish notifications to this Topic."; + break; + case HB: + heartBeat(notificationTopic); + notificationResponse = "Success!! HeartBeat registered."; + break; + } + }catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + // Used to register Heart beat. + private void heartBeat(String notificationTopic) throws PolicyException{ + if(!topicQueue.isEmpty()&& topicQueue.containsKey(notificationTopic)){ + topicQueue.put(notificationTopic, new Date()); + }else{ + logger.info("Failed HeartBeat, Topic " + notificationTopic + "is not registered."); + throw new PolicyException("Failed HeartBeat, Topic " + notificationTopic + "is not registered."); + } + } + + // Used to remove Topic. + private static void removeTopic(String notificationTopic) throws PolicyException{ + if(topicQueue.containsKey(notificationTopic)){ + topicQueue.remove(notificationTopic); + removeTopicFromBackup(notificationTopic); + }else{ + logger.info("Failed Removal, Topic " + notificationTopic + " is not registered."); + throw new PolicyException("Failed Removal, Topic " + notificationTopic + " is not registered."); + } + } + + private static void removeTopicFromBackup(String notificationTopic) { + synchronized (resourceLock) { + try (Stream lines = Files.lines(Paths.get(BACKUPFILE))) { + List replaced = lines.map(line-> (line.split("=")[0].equals(notificationTopic)?"":line)).collect(Collectors.toList()); + try (PrintWriter pw = new PrintWriter( BACKUPFILE, "UTF-8")) { + replaced.forEach(line-> { + if(line.trim().isEmpty()){ + return; + } + pw.println(line); + }); + } + lines.close(); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + " Could not remove/recreate the backup. ", e); + } + } + } + + // Used to add Topic. + private void addTopic(String notificationTopic) throws PolicyException{ + // validate if topic exists. + if(!topicQueue.isEmpty()&& topicQueue.containsKey(notificationTopic)){ + topicQueue.put(notificationTopic, new Date()); + logger.info("Topic " + notificationTopic + " is already registered."); + throw new PolicyException("Topic " + notificationTopic + " is already registered."); + } + topicQueue.put(notificationTopic, new Date()); + addTopictoBackUp(notificationTopic); + } + + private void addTopictoBackUp(String notificationTopic) { + synchronized (resourceLock) { + try { + Files.write(Paths.get(BACKUPFILE),( notificationTopic+"="+new Date().toString()+"\n").getBytes() , StandardOpenOption.APPEND); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + " Could not add to the backup. ", e); + } + } + } + + // Maintains BackUp and Queue Topic. + private static void callThread() { + // Create the backup file if it not exists. + backup(); + if(backUpthread==null){ + Runnable task = () -> { + logger.info("BackUpThread not set. Starting now !"); + threadTask(); + }; + backUpthread = new Thread(task); + backUpthread.start(); + } + } + + private static void backup(){ + synchronized (resourceLock) { + try{ + File backUpFile = new File(BACKUPFILE); + if(!backUpFile.exists() && backUpFile.createNewFile()){ + logger.info(" BackUp File for topic's has been created !"); + }else{ + // File Already exists. Process file and load the Memory. + Stream stream = Files.lines(Paths.get(BACKUPFILE)); + Map data = stream.map(line -> line.split(",")).collect(Collectors.toMap(e->e[0],e-> new Date())); + stream.close(); + data.forEach((key, value)->logger.debug("Topic retrieved from backUp : " + key + " with Time : " + value)); + topicQueue.putAll(data); + } + }catch(IOException e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + " Could not process the backup. ", e); + } + } + } + + private static void threadTask() { + while(true){ + try { + TimeUnit.MILLISECONDS.sleep(interval); + for(Map.Entry map : topicQueue.entrySet()){ + Date currentTime = new Date(); + long timeDiff = 0; + timeDiff = currentTime.getTime()-map.getValue().getTime(); + if(timeDiff < (interval+1500)){ + removeTopic(map.getKey()); + } + } + } catch (InterruptedException | PolicyException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error during thread execution ", e); + } + } + } + + public String getResult() { + return notificationResponse; + } + + public HttpStatus getResponseCode() { + return status; + } + + /** + * Entry point for sending Notifications from Notification Server. + * @param notification String JSON format of notification message which needs to be sent. + */ + public static void sendNotification(String notification) { + init(); + for (String topic: topicQueue.keySet()){ + sendDmaapMessage(topic, notification); + } + } + + private static void sendDmaapMessage(String topic, String notification) { + BusPublisher publisher = new BusPublisher.DmaapPublisherWrapper(dmaapList, + topic, + aafLogin, + aafPassword); + // Sending notification through DMaaP Message Router + publisher.send( "MyPartitionKey", notification); + logger.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + topic); + publisher.close(); + } + + /** + * Notification service Type Enumeration + */ + public enum NotificationServiceType{ + ADD, + REMOVE, + HB + } + +} \ No newline at end of file diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java new file mode 100644 index 000000000..e7216e152 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java @@ -0,0 +1,656 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.apache.commons.io.IOUtils; +import org.onap.policy.api.PolicyException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.config.PDPApiAuth; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; + +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PAPServices { + private static final String SUCCESS = "success"; + private static Logger LOGGER = FlexLogger.getLogger(PAPServices.class + .getName()); + + private int responseCode = 0; + private static String environment = "DEVL"; + private static Boolean junit = false; + private static List paps = null; + private static final Object papResourceLock = new Object(); + private String operation = null; + private String requestMethod = null; + private String encoding = null; + + public PAPServices() { + environment = PDPApiAuth.getEnvironment(); + if(paps == null){ + synchronized (papResourceLock) { + String urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URLS); + if(urlList == null){ + urlList = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + } + paps = Arrays.asList(urlList.split(",")); + } + } + } + + private String getPAPEncoding(){ + if(encoding == null){ + String userID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + String pass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + Base64.Encoder encoder = Base64.getEncoder(); + encoding = encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8)); + } + return encoding; + } + + private void rotatePAPList(){ + synchronized (papResourceLock) { + Collections.rotate(paps, -1); + } + } + + private String getPAP(){ + String result; + synchronized (papResourceLock) { + result = paps.get(0); + } + return result; + } + + public int getResponseCode() { + return responseCode; + } + + public Object callPAP(Object content, String[] parameters, UUID requestID, + String clientScope) throws PolicyException { + String response = null; + HttpURLConnection connection = null; + responseCode = 0; + // Checking for the available PAPs is done during the first Request and + // the List is going to have the connected PAP as first element. + // This makes it Real-Time to change the list depending on their + // availability. + if (paps == null || paps.isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty."; + LOGGER.error(message); + throw new PolicyException(message); + } + int papsCount = 0; + boolean connected = false; + while (papsCount < paps.size()) { + try { + String fullURL = getPAP(); + fullURL = checkParameter(parameters, fullURL); + URL url = new URL(fullURL); + LOGGER.debug("--- Sending Request to PAP : "+ url.toString() + " ---"); + // Open the connection + connection = (HttpURLConnection) url.openConnection(); + // Setting Content-Type + connection.setRequestProperty("Content-Type","application/json"); + // Adding Authorization + connection.setRequestProperty("Authorization", "Basic "+ getPAPEncoding()); + connection.setRequestProperty("Environment", environment); + connection.setRequestProperty("ClientScope", clientScope); + // set the method and headers + connection.setRequestMethod(requestMethod); + connection.setUseCaches(false); + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + // Adding RequestID + if (requestID == null) { + requestID = UUID.randomUUID(); + LOGGER.info("No request ID provided, sending generated ID: " + + requestID.toString()); + } else { + LOGGER.info("Using provided request ID: " + + requestID.toString()); + } + connection.setRequestProperty("X-ECOMP-RequestID", + requestID.toString()); + if (content != null && (content instanceof InputStream)) { + // send current configuration + try (OutputStream os = connection.getOutputStream()) { + int count = IOUtils.copy((InputStream) content, os); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("copied to output, bytes=" + count); + } + } + } else if(content != null){ + // the content is an object to be encoded in JSON + ObjectMapper mapper = new ObjectMapper(); + if (!junit) { + mapper.writeValue(connection.getOutputStream(), + content); + } + } + // DO the connect + connection.connect(); + responseCode = connection.getResponseCode(); + // If Connected to PAP then break from the loop and continue + // with the Request + if (connection.getResponseCode() > 0 || junit) { + connected = true; + break; + } else { + LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : " + connection.getResponseCode()); + rotatePAPList(); + } + } catch (Exception e) { + // This means that the PAP is not working + if (junit) { + connected = true; + break; + } + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "PAP connection Error : " + e); + rotatePAPList(); + } + papsCount++; + } + if (connected) { + // Read the Response + LOGGER.debug("connected to the PAP : " + getPAP()); + LOGGER.debug("--- Response: ---"); + if(connection != null){ + Map> headers = connection.getHeaderFields(); + for (String key : headers.keySet()) { + LOGGER.debug("Header :" + key + " Value: " + headers.get(key)); + } + + try { + response = checkResponse(connection, requestID); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + e; + throw new PolicyException( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Decoding the result ", e); + } + if (junit) { + response = SUCCESS; + } + }else{ + response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "connection is null"; + } + return response; + } else { + response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Unable to get valid response from PAP(s) " + paps; + return response; + } + } + + public String getActiveVersion(String policyScope, String filePrefix, String policyName, String clientScope, UUID requestID) { + String version = null; + HttpURLConnection connection = null; + String [] parameters = {"apiflag=version","policyScope="+policyScope, "filePrefix="+filePrefix, "policyName="+policyName}; + if (paps == null || paps.isEmpty()) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty."); + try { + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty."); + } catch (Exception e) { + LOGGER.error(e.getMessage() + e); + } + }else { + int papsCount = 0; + boolean connected = false; + while (papsCount < paps.size()) { + try { + String fullURL = getPAP(); + if (parameters != null && parameters.length > 0) { + String queryString = ""; + for (String p : parameters) { + queryString += "&" + p; + } + fullURL += "?" + queryString.substring(1); + } + + URL url = new URL (fullURL); + + //Open the connection + connection = (HttpURLConnection)url.openConnection(); + + // Setting Content-Type + connection.setRequestProperty("Content-Type", + "application/json"); + + // Adding Authorization + connection.setRequestProperty("Authorization", "Basic " + + getPAPEncoding()); + + connection.setRequestProperty("Environment", environment); + connection.setRequestProperty("ClientScope", clientScope); + + + //set the method and headers + connection.setRequestMethod("GET"); + connection.setUseCaches(false); + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString()); + + //DO the connect + connection.connect(); + + // If Connected to PAP then break from the loop and continue with the Request + if (connection.getResponseCode() > 0) { + connected = true; + break; + + } else { + LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error"); + } + } catch (Exception e) { + // This means that the PAP is not working + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e); + rotatePAPList(); + } + papsCount++; + } + + if (connected) { + //Read the Response + LOGGER.debug("connected to the PAP : " + getPAP()); + LOGGER.debug("--- Response: ---"); + Map> headers = connection.getHeaderFields(); + for (String key : headers.keySet()) { + LOGGER.debug("Header :" + key + " Value: " + headers.get(key)); + } + try { + if (connection.getResponseCode() == 200) { + // Check for successful creation of policy + version = connection.getHeaderField("version"); + LOGGER.debug("ActiveVersion from the Header: " + version); + } else if (connection.getResponseCode() == 403) { + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is " + + connection.getResponseCode() + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. "); + version = "pe100"; + } else if (connection.getResponseCode() == 404) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is " + + connection.getResponseCode() + ". This indicates a problem with getting the version from the PAP"); + version = "pe300"; + } else { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: Error occured while getting the version from the PAP. The request may be incorrect."); + } + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + try { + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e); + } catch (Exception e1) { + LOGGER.error(e1.getMessage() + e1); + } + } + + } else { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps); + try { + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP "); + } catch (Exception e) { + LOGGER.error(e.getMessage() + e); + } + } + } + return version; + } + + private String checkResponse(HttpURLConnection connection, UUID requestID) throws IOException { + String response = null; + if (responseCode == 200 || junit) { + // Check for successful creation of policy + String isSuccess = null; + if (!junit) { // is this a junit test? + isSuccess = connection.getHeaderField("successMapKey"); + operation = connection.getHeaderField("operation"); + } else { + isSuccess = SUCCESS; + } + if (SUCCESS.equals(isSuccess)) { + if ("update".equals(operation)) { + response = "Transaction ID: " + requestID + " --Policy with the name "+ connection.getHeaderField("policyName") + + " was successfully updated. "; + if (connection.getHeaderField("safetyChecker")!=null) { + response = response + + "\n\nPolicy Safety Checker Warning: This closedLoopControlName " + + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") + + " that already exists." + " See detailed information on ClosedLoop Pairs below: " + +"\n\n"+connection.getHeaderField("safetyChecker"); + } + } else if ("create".equals(operation)) { + response = "Transaction ID: " + requestID + " --Policy with the name "+ connection.getHeaderField("policyName") + + " was successfully created."; + if (connection.getHeaderField("safetyChecker")!=null) { + response = response + + "\n\nPolicy Safety Checker Warning: This closedLoopControlName " + + "is potentially in conflict with " + connection.getHeaderField("conflictCLName") + + " that already exists. " + "See detailed information on ClosedLoop Pairs below: " + +"\n\n"+connection.getHeaderField("safetyChecker"); + } + } else if ("delete".equals(operation)) { + response = "Transaction ID: " + requestID + " --The policy was successfully deleted."; + } else if ("import".equals(operation)) { + response = "Transaction ID: " + requestID + " --The policy engine import for "+ connection.getHeaderField("service") + + " was successfull."; + } else if ("createDictionary".equals(operation)) { + response = "Transaction ID: " + requestID + " --Dictionary Item was added successfully!"; + } else if ("updateDictionary".equals(operation)) { + response = "Transaction ID: " + requestID + " --Dictionary Item was updated successfully!"; + } else if ("getDictionary".equals(operation)) { + String json = null; + try { + + //get the json string from the response + InputStream is = connection.getInputStream(); + + // 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(is); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + + } catch (IOException e1) { + LOGGER.error(e1.getMessage() + e1); + } + response = "Transaction ID: " + requestID + " --Dictionary Items Retrieved " + json; + } else if ("getMetrics".equals(operation)) { + response = "Transaction ID: " + requestID + " --Policy Metrics Retrieved " + connection.getHeaderField("metrics"); + } + LOGGER.info(response); + } else { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Operation unsuccessful, unable to complete the request!"; + LOGGER.error(message); + response = message; + } + } else if (connection.getResponseCode() == 202) { + if ("delete".equalsIgnoreCase(connection.getHeaderField("operation")) && + "true".equals(connection.getHeaderField("lockdown"))) { + response = "Transaction ID: " + + requestID + + " --Policies are locked down, please try again later."; + LOGGER.warn(response); + } + } else if (connection.getResponseCode() == 204) { + if ("push".equals(connection.getHeaderField("operation"))) { + response = "Transaction ID: " + + requestID + + " --Policy '" + + connection.getHeaderField("policyId") + + "' was successfully pushed to the PDP group '" + + connection.getHeaderField("groupId") + "'."; + LOGGER.info(response); + } + } else if (connection.getResponseCode() == 400 && connection.getHeaderField("error") != null) { + response = connection.getHeaderField("error"); + LOGGER.error(response); + } else if (connection.getResponseCode() == 403) { + response = XACMLErrorConstants.ERROR_PERMISSIONS + + "response code of the URL is " + + connection.getResponseCode() + + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. "; + LOGGER.error(response); + } else if (connection.getResponseCode() == 404 && connection.getHeaderField("error") != null) { + if ("unknownGroupId".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + connection.getHeaderField("message") + + " Please check the pdpGroup you are requesting to move the policy to."; + LOGGER.error(response); + } + } else if (connection.getResponseCode() == 409 && connection.getHeaderField("error") != null) { + if ("modelExistsDB".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Import Value Exist Error: The import value " + + connection.getHeaderField("service") + + " already exist on the PAP. " + + "Please create a new import value."; + } else if ("policyExists".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Policy Exist Error: The Policy " + + connection.getHeaderField("policyName") + + " already exist on the PAP. " + + "Please create a new policy or use the update API to modify the existing one."; + } else if ("dictionaryItemExists".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Dictionary Item Exist Error: The Dictionary Item already exist in the database. " + + "Please create a new Dictionary Item or use the update API to modify the existing one."; + } else if ("duplicateGroup".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Group Policy Scope List Exist Error: The Group Policy Scope List for this Dictionary Item already exist in the database. " + + "Duplicate Group Policy Scope Lists for multiple groupNames is not allowed. " + + "Please review the request and verify that the groupPolicyScopeListData1 is unique compared to existing groups."; + } else if("PolicyInPDP".equals(connection.getHeaderField("error"))){ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Policy Exist Error: The Policy trying to be deleted is active in PDP. " + + "Active PDP Polcies are not allowed to be deleted from PAP. " + + "Please First remove the policy from PDP in order to successfully delete the Policy from PAP."; + } + LOGGER.error(response); + } else if (connection.getResponseCode() == 500 && connection.getHeaderField("error") != null) { + if ("jpautils".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Could not create JPAUtils instance on the PAP"; + } else if ("deleteDB".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Failed to delete Policy from database."; + } else if ("deleteFile".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Cannot delete the policy file"; + } else if ("groupUpdate".equals(connection.getHeaderField("error"))) { + response = connection.getHeaderField("message"); + } else if ("unknown".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_UNKNOWN + + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information."; + } else if ("deleteConfig".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Cannot delete the configuration or action body file in specified location."; + } else if ("missing".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Failed to create value in database because service does match a value in file"; + } else if ("importDB".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Database errors during policy engine import"; + } else if ("policyCopyError".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_PROCESS_FLOW + + connection.getHeaderField("message"); + } else if ("addGroupError".equals(connection.getHeaderField("error"))) { + response = connection.getHeaderField("message"); + } else if ("validation".equals(connection.getHeaderField("error"))){ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "Validation errors during policy engine " + connection.getHeaderField("operation") + + " for " + connection.getHeaderField("service"); + } else if ("error".equals(connection.getHeaderField("error"))) { + response = XACMLErrorConstants.ERROR_UNKNOWN + + "Could not create or update the policy for and unknown reason"; + }else{ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "BAD REQUEST: Error occured while attempting perform this operation.. the request may be incorrect. " + connection.getHeaderField("error"); + } + LOGGER.error(response); + } else { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + + "BAD REQUEST: Error occured while attempting perform this operation.. the request may be incorrect."; + LOGGER.error(response); + } + return response; + } + + private String checkParameter(String[] parameters, String fullURL) { + if (parameters != null && parameters.length > 0) { + String queryString = ""; + for (String p : parameters) { + queryString += "&" + p; + if (p.equalsIgnoreCase("operation=post")) { + requestMethod = "POST"; + } else if (p.equalsIgnoreCase("operation=delete")) { + requestMethod = "DELETE"; + operation = "delete"; + } else if (p.equalsIgnoreCase("operation=get")) { + requestMethod = "GET"; + operation = "get"; + } else if (p.equalsIgnoreCase("operation=put")||p.equalsIgnoreCase("operation=create") + ||p.equalsIgnoreCase("operation=update")||p.equalsIgnoreCase("operation=createDictionary")){ + requestMethod = "PUT"; + if (p.equalsIgnoreCase("operation=create")) { + operation = "create"; + } else if (p.equalsIgnoreCase("operation=update")) { + operation = "update"; + } else if (p.equalsIgnoreCase("operation=createDictionary")){ + operation = "createDictionary"; + } + }else if (p.equalsIgnoreCase("importService=MICROSERVICE")||p.equalsIgnoreCase("importService=BRMSPARAM")){ + requestMethod = "PUT"; + } + } + fullURL += "?" + queryString.substring(1); + } + return fullURL; + } + + public StdPDPPolicy pushPolicy(String policyScope, String filePrefix, + String policyName, String clientScope, String pdpGroup, + UUID requestID) throws PolicyException { + String json = "{ " + + "\"apiflag\": \"api\"," + + "\"policyScope\": \""+policyScope+"\"," + + "\"filePrefix\": \""+filePrefix+"\"," + + "\"policyName\": \""+policyName+"\"," + + "\"clientScope\": \""+clientScope+"\"," + + "\"pdpGroup\": \""+pdpGroup+"\"}"; + //String response = null; + HttpURLConnection connection = null; + responseCode = 0; + if (paps == null || paps.isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty."; + LOGGER.error(message); + throw new PolicyException(message); + } + int papsCount = 0; + boolean connected = false; + while (papsCount < paps.size()) { + try { + String fullURL = getPAP(); + fullURL = (fullURL.endsWith("/"))? fullURL+"onap/pushPolicy" : fullURL+"/onap/pushPolicy"; + URL url = new URL(fullURL); + LOGGER.debug("--- Sending Request to PAP : "+ url.toString() + " ---"); + // Open the connection + connection = (HttpURLConnection) url.openConnection(); + // Setting Content-Type + connection.setRequestProperty("Content-Type","application/json"); + // Adding Authorization + connection.setRequestProperty("Authorization", "Basic "+ getPAPEncoding()); + connection.setRequestProperty("Environment", environment); + connection.setRequestProperty("ClientScope", clientScope); + // set the method and headers + connection.setRequestMethod("POST"); + connection.setUseCaches(false); + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + // Adding RequestID + if (requestID == null) { + requestID = UUID.randomUUID(); + LOGGER.info("No request ID provided, sending generated ID: " + + requestID.toString()); + } else { + LOGGER.info("Using provided request ID: " + + requestID.toString()); + } + connection.setRequestProperty("X-ECOMP-RequestID", + requestID.toString()); + // DO the connect + try (OutputStream os = connection.getOutputStream()) { + int count = IOUtils.copy(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), os); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("copied to output, bytes=" + count); + } + } + connection.connect(); + responseCode = connection.getResponseCode(); + // If Connected to PAP then break from the loop and continue + // with the Request + if (connection.getResponseCode() > 0 || junit) { + connected = true; + break; + } else { + LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PAP Response Code : " + connection.getResponseCode()); + rotatePAPList(); + } + } catch (Exception e) { + // This means that the PAP is not working + if (junit) { + connected = true; + break; + } + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "PAP connection Error : " + e); + rotatePAPList(); + } + papsCount++; + } + if (connected) { + // Read the Response + LOGGER.debug("connected to the PAP : " + getPAP()); + LOGGER.debug("--- Response: ---"); + if(connection != null){ + Map> headers = connection.getHeaderFields(); + for (String key : headers.keySet()) { + LOGGER.debug("Header :" + key + " Value: " + headers.get(key)); + } + try { + if(responseCode==202){ + StdPDPPolicy policy = (StdPDPPolicy) new ObjectInputStream(connection.getInputStream()).readObject(); + return policy; + } + } catch (IOException | ClassNotFoundException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + throw new PolicyException( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Decoding the result ", e); + } + } + return null; + } else { + return null; + } + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java new file mode 100644 index 000000000..e495c9950 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PDPServices.java @@ -0,0 +1,439 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.MalformedURLException; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonReader; +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.commons.io.IOUtils; +import org.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.api.PolicyDecision; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PolicyResponseStatus; +import org.onap.policy.api.PolicyType; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.XACMLPdpServlet; +import org.onap.policy.pdp.rest.api.models.PDPResponse; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.std.Matches; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.w3c.dom.Document; + +import com.att.research.xacml.api.Advice; +import com.att.research.xacml.api.AttributeAssignment; +import com.att.research.xacml.api.Decision; +import com.att.research.xacml.api.Obligation; +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.Response; +import com.att.research.xacml.api.Result; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.std.json.JSONRequest; +import com.att.research.xacml.std.json.JSONResponse; +import com.att.research.xacml.util.XACMLProperties; + +public class PDPServices { + private static final Logger LOGGER = FlexLogger.getLogger(PDPServices.class.getName()); + // Change the default Priority value here. + private static final int DEFAULT_PRIORITY = 9999; + private boolean unique = false; + private Boolean decide = false; + private Request rainydayRequest = null; + + public Collection generateRequest(String jsonString, UUID requestID, boolean unique, boolean decide) throws PolicyException{ + this.unique = unique; + this.decide = decide; + Collection results = null; + Response response = null; + // Create Request. We need XACML API here. + try { + Request request = JSONRequest.load(jsonString); + // Assign a rainy day treatment request to parse the decided treatment + if (jsonString.contains("BB_ID")) { + rainydayRequest = request; + } + // Call the PDP + LOGGER.info("--- Generating Request: ---\n" + JSONRequest.toString(request)); + response = callPDP(request, requestID); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e); + PDPResponse pdpResponse = new PDPResponse(); + results = new HashSet<>(); + pdpResponse.setPolicyConfigMessage("Unable to Call PDP. Error with the URL"); + pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); + pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED); + results.add(pdpResponse); + throw new PolicyException(e); + } + if (response != null) { + results = checkResponse(response); + } else { + LOGGER.info("No Response Received from PDP"); + PDPResponse pdpResponse = new PDPResponse(); + results = new HashSet<>(); + pdpResponse.setPolicyConfigMessage("No Response Received"); + pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); + pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED); + results.add(pdpResponse); + } + return results; + } + + private Collection checkResponse(Response response) throws PolicyException{ + String pdpConfigLocation = null; + Collection combinedResult = new HashSet<>(); + int priority = DEFAULT_PRIORITY; + Map uniqueResult = new HashMap<>(); + for (Result result : response.getResults()) { + if (!result.getDecision().equals(Decision.PERMIT)) { + LOGGER.info("Decision not a Permit. " + result.getDecision().toString()); + PDPResponse pdpResponse = new PDPResponse(); + if (decide) { + String indeterminatePropValue = XACMLProperties.getProperty("decision.inStringdeterminate.response"); + if(result.getDecision().equals(Decision.INDETERMINATE)&& indeterminatePropValue != null){ + if("PERMIT".equalsIgnoreCase(indeterminatePropValue)){ + pdpResponse.setDecision(PolicyDecision.PERMIT); + }else{ + pdpResponse.setDecision(PolicyDecision.DENY); + } + }else{ + pdpResponse.setDecision(PolicyDecision.DENY); + } + for(Advice advice: result.getAssociatedAdvice()){ + for(AttributeAssignment attribute: advice.getAttributeAssignments()){ + pdpResponse.setDetails(attribute.getAttributeValue().getValue().toString()); + break; + } + } + combinedResult.add(pdpResponse); + return combinedResult; + } + pdpResponse.setStatus(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Params passed: Decision not a Permit.",PolicyResponseStatus.NO_ACTION_REQUIRED,PolicyConfigStatus.CONFIG_NOT_FOUND); + combinedResult.add(pdpResponse); + return combinedResult; + } else { + if (decide) { + // check for Decision for decision based calls. + PDPResponse pdpResponse = new PDPResponse(); + pdpResponse.setDecision(PolicyDecision.PERMIT); + + //if this is a Rainy Day treatment decision we need to get the selected treatment + if(rainydayRequest!=null){ + pdpResponse.setDetails(getRainyDayTreatment(result)); + } else { + pdpResponse.setDetails("Decision Permit. OK!"); + } + combinedResult.add(pdpResponse); + return combinedResult; + } + if (!result.getAssociatedAdvice().isEmpty()) { + // Configurations should be in advice. + // Also PDP took actions could be here. + for (Advice advice : result.getAssociatedAdvice()) { + int config = 0, uri = 0; + String configURL = null; + String policyName = null; + String policyVersion = null; + Matches match = new Matches(); + Map matchingConditions = new HashMap<>(); + Map configAttributes = new HashMap<>(); + Map responseAttributes = new HashMap<>(); + Map actionTaken = new HashMap<>(); + PDPResponse pdpResponse = new PDPResponse(); + Map adviseAttributes = new HashMap<>(); + for (AttributeAssignment attribute : advice.getAttributeAssignments()) { + adviseAttributes.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString()); + if ("CONFIGURATION".equalsIgnoreCase(attribute.getAttributeValue().getValue().toString())) { + config++; + } else if (attribute.getDataTypeId().stringValue().endsWith("anyURI")) { + uri++; + if (uri == 1) { + configURL = attribute.getAttributeValue().getValue().toString(); + pdpConfigLocation = configURL.replace("$URL", XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)); + } else { + if (!("PDP".equalsIgnoreCase(attribute.getIssuer()))) { + throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error having multiple URI in the Policy"); + } + } + } else if ("PolicyName".equalsIgnoreCase(attribute.getAttributeId().stringValue())) { + policyName = attribute.getAttributeValue().getValue().toString(); + } else if ("VersionNumber".equalsIgnoreCase(attribute.getAttributeId().stringValue())) { + policyVersion = attribute.getAttributeValue().getValue().toString(); + } else if ("Priority".equalsIgnoreCase(attribute.getAttributeId().stringValue())){ + try{ + priority = Integer.parseInt(attribute.getAttributeValue().getValue().toString()); + } catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Unable to Parse Integer for Priority. Setting to default value",e); + priority = DEFAULT_PRIORITY; + } + } else if (attribute.getAttributeId().stringValue().startsWith("matching")) { + matchingConditions.put(attribute.getAttributeId().stringValue() + .replaceFirst("(matching).", ""),attribute.getAttributeValue().getValue().toString()); + if ("ONAPName".equals(attribute.getAttributeId().stringValue() + .replaceFirst("(matching).", ""))) { + match.setOnapName(attribute.getAttributeValue().getValue().toString()); + } else if ("ConfigName".equals(attribute.getAttributeId().stringValue() + .replaceFirst("(matching).", ""))) { + match.setConfigName(attribute.getAttributeValue().getValue().toString()); + } else { + configAttributes.put(attribute.getAttributeId().stringValue() + .replaceFirst("(matching).", ""),attribute.getAttributeValue().getValue().toString()); + } + } else if (attribute.getAttributeId().stringValue().startsWith("key:")) { + responseAttributes.put(attribute.getAttributeId().stringValue().replaceFirst("(key).", ""), + attribute.getAttributeValue().getValue().toString()); + } else if (attribute.getAttributeId().stringValue().startsWith("controller:")) { + responseAttributes.put("$"+ attribute.getAttributeId().stringValue(), + attribute.getAttributeValue().getValue().toString()); + } else if (attribute.getAttributeId().stringValue().startsWith("dependencies:")) { + responseAttributes.put("$dependency$", + attribute.getAttributeValue().getValue().toString()); + } + } + if (!configAttributes.isEmpty()) { + match.setConfigAttributes(configAttributes); + } + if ((config == 1) && (uri == 1)) { + // If there is a configuration. + try { + LOGGER.debug("Configuration Call to : " + configURL); + pdpResponse = configCall(pdpConfigLocation); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ e); + pdpResponse.setStatus("Error in Calling the Configuration URL "+ e, + PolicyResponseStatus.NO_ACTION_REQUIRED, + PolicyConfigStatus.CONFIG_NOT_FOUND); + } + pdpResponse.setPolicyName(policyName); + pdpResponse.setPolicyVersion(policyVersion); + pdpResponse.setMatchingConditions(matchingConditions); + pdpResponse.setResponseAttributes(responseAttributes); + if(!unique){ + combinedResult.add(pdpResponse); + }else{ + if(!uniqueResult.isEmpty()){ + if(uniqueResult.containsKey(priority)){ + // Not any more unique, check the matching conditions size + int oldSize = uniqueResult.get(priority).getMatchingConditions().size(); + int newSize = matchingConditions.size(); + if(oldSize < newSize){ + uniqueResult.put(priority, pdpResponse); + }else if(oldSize == newSize){ + pdpResponse = new PDPResponse(); + pdpResponse.setStatus("Two/more Policies have Same Priority and matching conditions, Please correct your policies.", + PolicyResponseStatus.NO_ACTION_REQUIRED, + PolicyConfigStatus.CONFIG_NOT_FOUND); + combinedResult.add(pdpResponse); + unique = false; + return combinedResult; + } + }else{ + uniqueResult.put(priority, pdpResponse); + } + }else{ + uniqueResult.put(priority, pdpResponse); + } + } + } else { + // Else it is Action Taken. + LOGGER.info("Action Taken by PDP. "); + actionTaken.putAll(adviseAttributes); + pdpResponse.setActionTaken(actionTaken); + pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.ACTION_TAKEN); + pdpResponse.setPolicyResponseMessage("Action Taken by the PDP"); + combinedResult.add(pdpResponse); + } + } + } + if (!result.getObligations().isEmpty()) { + // Obligation actions + // Action advised should be in obligations. + for (Obligation obligation : result.getObligations()) { + Map actionAdvised = new HashMap<>(); + PDPResponse pdpResponse = new PDPResponse(); + for (AttributeAssignment attribute : obligation.getAttributeAssignments()) { + actionAdvised.put(attribute.getAttributeId().stringValue(), + attribute.getAttributeValue().getValue().toString()); + } + pdpResponse.setActionAdvised(actionAdvised); + pdpResponse.setPolicyResponseStatus(PolicyResponseStatus.ACTION_ADVISED); + pdpResponse.setPolicyResponseMessage("Action has been Advised "); + combinedResult.add(pdpResponse); + } + } + } + } + if(unique){ + // Select Unique policy. + int minNum = DEFAULT_PRIORITY; + for(int num: uniqueResult.keySet()){ + if(num < minNum){ + minNum = num; + } + } + combinedResult.add(uniqueResult.get(minNum)); + // Turn off Unique + unique = false; + } + + return combinedResult; + } + + private String getRainyDayTreatment(Result result) { + String treatment = null; + if (rainydayRequest!=null&& !result.getAssociatedAdvice().isEmpty()) { + // Get the desired treatment for requested errorCode from the Advice + for (Advice advice : result.getAssociatedAdvice()) { + Map adviseAttributes = new HashMap<>(); + for (AttributeAssignment attribute : advice.getAttributeAssignments()) { + adviseAttributes.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString()); + if ("treatment".equalsIgnoreCase(attribute.getAttributeId().stringValue())){ + treatment = attribute.getAttributeValue().getValue().toString(); + } + } + } + } + return treatment; + } + + private PDPResponse configCall(String pdpConfigLocation) throws Exception{ + PDPResponse pdpResponse = new PDPResponse(); + if(pdpConfigLocation.contains("/")){ + pdpConfigLocation = pdpConfigLocation.replace("/", File.separator); + } + InputStream inputStream = null; + try { + inputStream = new FileInputStream(new File(pdpConfigLocation)); + try { + if (pdpConfigLocation.endsWith("json")) { + pdpResponse.setType(PolicyType.JSON); + JsonReader jsonReader = Json.createReader(inputStream); + pdpResponse.setConfig(jsonReader.readObject().toString()); + jsonReader.close(); + } else if (pdpConfigLocation.endsWith("xml")) { + pdpResponse.setType(PolicyType.XML); + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + DocumentBuilder db = null; + try { + db = dbf.newDocumentBuilder(); + Document document = db.parse(inputStream); + DOMSource domSource = new DOMSource(document); + StringWriter writer = new StringWriter(); + StreamResult result = new StreamResult(writer); + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer transformer; + transformer = tf.newTransformer(); + transformer.transform(domSource, result); + pdpResponse.setConfig(writer.toString()); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ e); + throw new Exception(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ "Unable to parse the XML config", e); + } + } else if (pdpConfigLocation.endsWith("properties")) { + pdpResponse.setType(PolicyType.PROPERTIES); + Properties configProp = new Properties(); + configProp.load(inputStream); + Map propVal = new HashMap<>(); + for(String name: configProp.stringPropertyNames()) { + propVal.put(name, configProp.getProperty(name)); + } + pdpResponse.setProperty(propVal); + } else if (pdpConfigLocation.endsWith("txt")) { + pdpResponse.setType(PolicyType.OTHER); + String other = IOUtils.toString(inputStream); + IOUtils.closeQuietly(inputStream); + pdpResponse.setConfig(other); + } else { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config Not Found"); + pdpResponse.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); + pdpResponse.setPolicyConfigMessage("Illegal form of Configuration Type Found."); + inputStream.close(); + return pdpResponse; + } + LOGGER.info("config Retrieved " + pdpConfigLocation); + pdpResponse.setStatus("Config Retrieved! ", + PolicyResponseStatus.NO_ACTION_REQUIRED, + PolicyConfigStatus.CONFIG_RETRIEVED); + return pdpResponse; + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + throw new Exception(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Cannot open a connection to the configURL", e); + } + } catch (MalformedURLException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in ConfigURL", e); + }finally{ + if(inputStream != null){ + inputStream.close(); + } + } + } + + private Response callPDP(Request request, + UUID requestID) throws Exception{ + Response response = null; + // Get the PDPEngine + if (requestID == null) { + requestID = UUID.randomUUID(); + LOGGER.debug("No request ID provided, sending generated ID: " + requestID.toString()); + } else { + LOGGER.debug("Using provided request ID: " + requestID.toString()); + } + PDPEngine pdpEngine = XACMLPdpServlet.getPDPEngine(); + if (pdpEngine == null) { + String message = "PDPEngine not loaded."; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message); + return response; + } + // call the PDPEngine to decide and give the response on the Request. + try { + response = pdpEngine.decide(request); + LOGGER.info("Response from the PDP is: \n" + JSONResponse.toString(response)); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + return null; + } + return response; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java new file mode 100644 index 000000000..2d8af54c5 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PolicyEngineImportService.java @@ -0,0 +1,186 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.UUID; + +import org.onap.policy.api.ImportParameters; +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.ImportParameters.IMPORT_TYPE; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; +import org.springframework.web.multipart.MultipartFile; + +public class PolicyEngineImportService { + private static Logger LOGGER = FlexLogger.getLogger(PolicyEngineImportService.class.getName()); + + private String importResponse = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private String message = null; + private ImportParameters importParameters = null; + private MultipartFile file = null; + + public PolicyEngineImportService(String importParametersJson, + MultipartFile file, + String requestID) { + try { + this.importParameters = PolicyUtils.jsonStringToObject(importParametersJson, ImportParameters.class); + } catch (Exception e) { + importResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + // This needs to stop here in case if there a issue here. Avoiding Null pointer exceptions. + return; + } + this.file = file; + if(importParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.importParameters.setRequestID(requestUUID); + } + try{ + run(); + specialCheck(); + }catch(PolicyException e){ + importResponse = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + private void specialCheck() { + if(importResponse==null || importResponse.contains("PE200")){ + status = HttpStatus.INTERNAL_SERVER_ERROR; + }else if(importResponse.contains("BAD REQUEST") || importResponse.contains("PE300")){ + status = HttpStatus.BAD_REQUEST; + } + } + + private void run() throws PolicyException{ + // Check Validation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyException(message); + } + // Get Result. + try{ + status = HttpStatus.OK; + importResponse = processResult(); + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + private String processResult() throws PolicyException{ + String response = null; + InputStream targetStream = null; + String fileName = file.getOriginalFilename(); + switch (importParameters.getServiceType()){ + case MICROSERVICE: + if (fileName.endsWith(".xmi") || fileName.endsWith(".zip")){ + try { + targetStream = new BufferedInputStream(file.getInputStream()); + } catch (IOException e) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in reading in the file provided"; + LOGGER.error(response + e); + return response; + } + }else{ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect File Type Given. Please use a file of type .xmi or .zip."; + LOGGER.error(response); + return response; + } + break; + case BRMSPARAM: + if (fileName.endsWith(".drl")){ + try { + targetStream = new BufferedInputStream(file.getInputStream()); + } catch (IOException e) { + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in reading in the file provided"; + LOGGER.error(response + e); + return response; + } + }else{ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect File Type Given. Please use a file of type .drl"; + LOGGER.error(response); + return response; + } + break; + default: + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect ServiceType Given. "; + LOGGER.error(response); + return response; + } + String[] parameters = new String[] {"importService=" + importParameters.getServiceType(), "serviceName=" + + importParameters.getServiceName(), "fileName=" + fileName, "version=" + importParameters.getVersion(), "description=" + importParameters.getDescription()}; + PAPServices papServices = new PAPServices(); + response = (String) papServices.callPAP(targetStream, parameters, importParameters.getRequestID(), "importMS"); + return response; + } + + private boolean getValidation() { + if(importParameters==null){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + " no Import Parameters given. "; + return false; + } + if(importParameters.getServiceName()==null || importParameters.getServiceName().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing service name value."; + return false; + } + if(importParameters.getServiceType()==null || importParameters.getServiceType().toString().trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing service Type value."; + return false; + } + if(importParameters.getServiceType().equals(IMPORT_TYPE.MICROSERVICE) && (importParameters.getVersion()==null || importParameters.getVersion().trim().isEmpty())){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing version value."; + return false; + } + if(file==null || file.isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing File."; + return false; + } + return true; + } + + public String getResult() { + return importResponse; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PushPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PushPolicyService.java new file mode 100644 index 000000000..f2c6c221c --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PushPolicyService.java @@ -0,0 +1,236 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.util.UUID; + +import org.onap.policy.api.PolicyException; +import org.onap.policy.api.PushPolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; +import org.springframework.http.HttpStatus; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; + +public class PushPolicyService { + private static final Logger LOGGER = FlexLogger.getLogger(PushPolicyService.class.getName()); + + private String pushResult = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private PushPolicyParameters pushPolicyParameters = null; + private String message = null; + private String policyName = null; + private String policyScope = null; + private String pdpGroup = null; + private String policyType = null; + private String filePrefix = null; + private String clientScope = null; + + public PushPolicyService(PushPolicyParameters pushPolicyParameters, + String requestID) { + this.pushPolicyParameters = pushPolicyParameters; + if(pushPolicyParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.pushPolicyParameters.setRequestID(requestUUID); + } + try{ + run(); + specialCheck(); + }catch(PolicyException e){ + pushResult = XACMLErrorConstants.ERROR_DATA_ISSUE + e; + status = HttpStatus.BAD_REQUEST; + } + } + + private void specialCheck() { + if(pushResult.contains("BAD REQUEST") || pushResult.contains("PE300")){ + status = HttpStatus.BAD_REQUEST; + } + } + + private void run() throws PolicyException{ + // Check Validation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyException(message); + } + // Process Results. + try{ + status = HttpStatus.OK; + pushResult = processResult(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyException(e); + } + } + + private String processResult() throws PolicyException{ + PAPServices papServices = new PAPServices(); + String response = null; + StdPDPPolicy selectedPolicy = papServices.pushPolicy(policyScope, filePrefix, policyName, clientScope, pdpGroup, pushPolicyParameters.getRequestID()); + if(selectedPolicy==null){ + response = XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404. " + + "This indicates a problem with getting the version from the PAP or the policy does not exist."; + LOGGER.error(response); + return response; + } + try { + LOGGER.debug("StdPDPPolicy object contains: " + selectedPolicy.getId() + ", " + selectedPolicy.getName() + ", " + selectedPolicy.getLocation().toString()); + response = copyPolicy(selectedPolicy, pdpGroup, clientScope, pushPolicyParameters.getRequestID()); + } catch (PAPException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+e.getMessage()); + throw new PolicyException(e); + } + LOGGER.debug("copyPolicy response: " + response); + if(response.contains("successfully")){ + response = (String) papServices.callPAP(selectedPolicy, new String[]{"groupId=" + pdpGroup, "policyId="+selectedPolicy.getId(), "apiflag=addPolicyToGroup", "operation=PUT"}, pushPolicyParameters.getRequestID(), clientScope); + } + LOGGER.debug("Final API response: " + response); + return response; + } + + private String copyPolicy(PDPPolicy policy, String group, String policyType, UUID requestID) throws PAPException { + String response = null; + if (policy == null || group == null) { + throw new PAPException("Null input policy="+policy+" group="+group); + } + try { + StdPAPPolicy location = new StdPAPPolicy(policy.getLocation()); + response = copyFile(policy.getId(), group, location, policyType, requestID); + } 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); + } + return response; + } + + private String copyFile(String policyId, String group, StdPAPPolicy location, String clientScope, UUID requestID) throws PAPException { + String response = null; + // send the policy file to the PAP Servlet + PAPServices papService = new PAPServices(); + try { + response = (String) papService.callPAP(location, new String[] {"groupId=" + group, "policyId="+policyId, "apiflag=api", "operation=post"}, requestID, clientScope); + } catch (Exception e) { + String message = "Unable to PUT policy '" + policyId + "', e:" + e; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + throw new PAPException(message); + } + return response; + } + + private boolean getValidation() { + // While Validating, extract the required values. + if (pushPolicyParameters.getPolicyName() != null + && pushPolicyParameters.getPolicyName().contains(".")) { + policyName = pushPolicyParameters.getPolicyName().substring(pushPolicyParameters.getPolicyName().lastIndexOf('.') + 1, + pushPolicyParameters.getPolicyName().length()); + policyScope = pushPolicyParameters.getPolicyName().substring(0,pushPolicyParameters.getPolicyName().lastIndexOf('.')); + LOGGER.info("Name is " + policyName + " scope is " + policyScope); + } else { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; + return false; + } + if (policyName==null||policyName.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; + return false; + } + policyType = pushPolicyParameters.getPolicyType(); + if(policyType== null || policyType.trim().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PolicyType given."; + return false; + } + + setClientScope(); + if(clientScope==null){ + return false; + } + + pdpGroup = pushPolicyParameters.getPdpGroup(); + if(pdpGroup==null || pdpGroup.trim().isEmpty()){ + pdpGroup = "default"; + } + + LOGGER.debug("clientScope is " + clientScope); + LOGGER.debug("filePrefix is " + filePrefix); + + return true; + } + + private void setClientScope() { + if ("Firewall".equalsIgnoreCase(policyType)) { + clientScope = "ConfigFirewall"; + filePrefix = "Config_FW_"; + } else if ("Action".equalsIgnoreCase(policyType)) { + clientScope = "Action"; + filePrefix = "Action_"; + } else if ("Decision".equalsIgnoreCase(policyType)) { + clientScope = "Decision"; + filePrefix = "Decision_"; + } else if ("Base".equalsIgnoreCase(policyType)) { + clientScope = "Config"; + filePrefix = "Config_"; + } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyType)) { + clientScope = "ConfigClosedLoop"; + filePrefix = "Config_Fault_"; + } else if ("ClosedLoop_PM".equalsIgnoreCase(policyType)) { + clientScope = "ConfigClosedLoop"; + filePrefix = "Config_PM_"; + } else if ("MicroService".equalsIgnoreCase(policyType)) { + clientScope = "ConfigMS"; + filePrefix = "Config_MS_"; + } else if ("BRMS_RAW".equalsIgnoreCase(policyType)) { + clientScope = "ConfigBrmsRaw"; + filePrefix = "Config_BRMS_Raw_"; + } else if ("BRMS_PARAM".equalsIgnoreCase(policyType)) { + clientScope = "ConfigBrmsParam"; + filePrefix = "Config_BRMS_Param_"; + } else { + clientScope = null; + message = XACMLErrorConstants.ERROR_DATA_ISSUE + policyType + + " is not a valid Policy Type."; + } + } + + public String getResult() { + return pushResult; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/SendEventService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/SendEventService.java new file mode 100644 index 000000000..c655a2ad4 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/SendEventService.java @@ -0,0 +1,170 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; + +import org.onap.policy.api.EventRequestParameters; +import org.onap.policy.api.PolicyEventException; +import org.onap.policy.api.PolicyResponse; +import org.onap.policy.api.PolicyResponseStatus; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.models.PDPResponse; +import org.onap.policy.std.StdPolicyResponse; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +public class SendEventService { + private static final Logger LOGGER = FlexLogger.getLogger(SendEventService.class.getName()); + + private Collection policyResponses = null; + private HttpStatus status = HttpStatus.BAD_REQUEST; + private EventRequestParameters eventRequestParameters = null; + private String message = null; + + public SendEventService(EventRequestParameters eventRequestParameters, + String requestID) { + this.eventRequestParameters=eventRequestParameters; + if(eventRequestParameters.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString(), e); + } + }else{ + requestUUID = UUID.randomUUID(); + LOGGER.info("Generated Random UUID: " + requestUUID.toString()); + } + this.eventRequestParameters.setRequestID(requestUUID); + } + policyResponses = new ArrayList<>(); + try{ + run(); + }catch(PolicyEventException e){ + StdPolicyResponse policyResponse = new StdPolicyResponse(); + policyResponse.setPolicyResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE+e); + policyResponse.setPolicyResponseStatus(PolicyResponseStatus.NO_ACTION_REQUIRED); + policyResponses.add(policyResponse); + status = HttpStatus.BAD_REQUEST; + } + } + + private void run() throws PolicyEventException{ + // getValidation. + if(!getValidation()){ + LOGGER.error(message); + throw new PolicyEventException(message); + } + // Generate Request. + String modelString = getModel().toString(); + LOGGER.debug("Generated JSON Request is: " + modelString); + // Process Result. + try { + PDPServices pdpServices = new PDPServices(); + status = HttpStatus.OK; + policyResponses = eventResult(pdpServices.generateRequest(modelString, eventRequestParameters.getRequestID(),false, false)); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + status = HttpStatus.BAD_REQUEST; + throw new PolicyEventException(XACMLErrorConstants.ERROR_DATA_ISSUE +e); + } + } + + private Collection eventResult( + Collection generateRequest) { + Collection result = new HashSet<>(); + if (generateRequest == null) { + return result; + } + if (!generateRequest.isEmpty()) { + for (PDPResponse stdStatus : generateRequest) { + StdPolicyResponse policyResponse = new StdPolicyResponse(); + policyResponse.setActionAdvised(stdStatus.getActionAdvised()); + policyResponse.setActionTaken(stdStatus.getActionTaken()); + policyResponse.setPolicyResponseMessage(stdStatus.getPolicyResponseMessage()); + policyResponse.setPolicyResponseStatus(stdStatus.getPolicyResponseStatus()); + policyResponse.setRequestAttributes(eventRequestParameters.getEventAttributes()); + result.add(policyResponse); + } + } + return result; + } + + private JsonObject getModel() throws PolicyEventException{ + JsonArrayBuilder resourceArray = Json.createArrayBuilder(); + Map eventAttributes = eventRequestParameters.getEventAttributes(); + for (Entry key : eventAttributes.entrySet()) { + if (key.getKey().isEmpty()) { + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key"; + LOGGER.error(message); + throw new PolicyEventException(message); + } + JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); + if (key.getValue().matches("[0-9]+")) { + int val = Integer.parseInt(key.getValue()); + resourceBuilder.add("Value", val); + } else { + resourceBuilder.add("Value", key.getValue()); + } + resourceBuilder.add("AttributeId", key.getKey()); + resourceArray.add(resourceBuilder); + } + return Json.createObjectBuilder() + .add("Request", Json.createObjectBuilder() + .add("Resource",Json.createObjectBuilder() + .add("Attribute",resourceArray))) + .build(); + } + + private boolean getValidation() { + if (eventRequestParameters == null) { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Parameters Given. "; + return false; + } + if (eventRequestParameters.getEventAttributes() == null || eventRequestParameters.getEventAttributes().isEmpty()){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Attributes Given. "; + return false; + } + return true; + } + + public Collection getResult() { + return policyResponses; + } + + public HttpStatus getResponseCode() { + return status; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/utils/PolicyApiUtils.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/utils/PolicyApiUtils.java new file mode 100644 index 000000000..cd107d0ba --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/utils/PolicyApiUtils.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.utils; + +import java.io.StringReader; + +import javax.json.Json; +import javax.json.JsonException; +import javax.json.JsonObject; +import javax.json.JsonReader; +import javax.json.stream.JsonParsingException; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +import com.google.common.base.CharMatcher; + +public class PolicyApiUtils { + private static Logger LOGGER = FlexLogger.getLogger(PolicyApiUtils.class + .getName()); + + public static Boolean validateNONASCIICharactersAndAllowSpaces( + String jsonString) { + Boolean isValidForm = false; + if (jsonString.isEmpty()) { + LOGGER.error("The Value is empty."); + return false; + } else { + if (CharMatcher.ASCII.matchesAllOf((CharSequence) jsonString)) { + LOGGER.info("The Value does not contain ASCII Characters"); + isValidForm = true; + } else { + LOGGER.error("The Value Contains Non ASCII Characters"); + isValidForm = false; + } + } + return isValidForm; + } + + public static boolean isNumeric(String str) { + for (char c : str.toCharArray()) { + if (!Character.isDigit(c)) + return false; + } + return true; + } + + public static JsonObject stringToJsonObject(String value) + throws JsonException, JsonParsingException, IllegalStateException { + JsonReader jsonReader = Json.createReader(new StringReader(value)); + JsonObject object = jsonReader.readObject(); + jsonReader.close(); + return object; + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPApiAuth.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPApiAuth.java new file mode 100644 index 000000000..1e3a41aeb --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPApiAuth.java @@ -0,0 +1,189 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.config; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +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.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.StringTokenizer; + +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.common.logging.eelf.MessageCodes; +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.utils.AAFPolicyClient; +import org.onap.policy.utils.AAFPolicyException; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; + +import com.att.research.xacml.util.XACMLProperties; + +public class PDPApiAuth { + private static final Logger LOGGER = FlexLogger.getLogger(PDPApiAuth.class); + + private static String environment = null; + private static Path clientPath = null; + private static Map> clientMap = null; + private static Long oldModified = null; + private static AAFPolicyClient aafClient = null; + + private PDPApiAuth(){ + // Private Constructor + } + + /* + * Set Property by reading the properties File. + */ + public static void setProperty() { + environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL"); + String clientFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PEP_IDFILE); + if(clientFile!=null){ + clientPath = Paths.get(clientFile); + } + try { + aafClient = AAFPolicyClient.getInstance(XACMLProperties.getProperties()); + } catch (AAFPolicyException | IOException e) { + LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AAF Client Not instantiated properly."); + } + } + + /* + * Return Environment value of the PDP servlet. + */ + public static String getEnvironment() { + if(environment==null){ + setProperty(); + } + return environment; + } + + /* + * Security check for authentication and authorizations. + */ + public static boolean checkPermissions(String clientEncoding, String requestID, + String resource) { + try{ + String[] userNamePass = PolicyUtils.decodeBasicEncoding(clientEncoding); + if(userNamePass==null || userNamePass.length==0){ + String usernameAndPassword = null; + byte[] decodedBytes = Base64.getDecoder().decode(clientEncoding); + usernameAndPassword = new String(decodedBytes, "UTF-8"); + StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); + String username = tokenizer.nextToken(); + String password = tokenizer.nextToken(); + userNamePass= new String[]{username, password}; + } + LOGGER.info("User " + userNamePass[0] + " is Accessing Policy Engine API."); + Boolean result = false; + // Check Backward Compatibility. + try{ + result = clientAuth(userNamePass); + }catch(Exception e){ + LOGGER.error(MessageCodes.ERROR_PERMISSIONS, e); + } + if(!result){ + String aafPolicyNameSpace = XACMLProperties.getProperty("policy.aaf.namespace"); + String aafResource = XACMLProperties.getProperty("policy.aaf.resource"); + if(!userNamePass[0].contains("@") && aafPolicyNameSpace!= null){ + userNamePass[0] = userNamePass[0] + "@" + aafPolicyNameSpace; + }else{ + LOGGER.info("No AAF NameSpace specified in properties"); + } + if(aafResource != null){ + resource = aafResource + resource; + }else{ + LOGGER.info("No AAF Resource specified in properties"); + } + LOGGER.info("Contacting AAF in : " + environment); + result = aafClient.checkAuthPerm(userNamePass[0], userNamePass[1], resource, environment, ".*"); + } + return result; + }catch(Exception e){ + LOGGER.error(MessageCodes.ERROR_PERMISSIONS, e); + return false; + } + } + + private static Boolean clientAuth(String[] userNamePass){ + if(clientPath==null){ + setProperty(); + } + if (!clientPath.toFile().exists()) { + return false; + }else if(clientPath.toString().endsWith(".properties")) { + try { + readProps(clientPath); + if (clientMap.containsKey(userNamePass[0]) && clientMap.get(userNamePass[0]).get(0).equals(userNamePass[1])) { + return true; + } + }catch(PolicyEngineException e){ + LOGGER.error(MessageCodes.ERROR_PERMISSIONS, e); + return false; + } + } + return false; + } + + private static Map> readProps(Path clientPath) throws PolicyEngineException{ + if(oldModified!=null){ + Long newModified = clientPath.toFile().lastModified(); + if (newModified == oldModified) { + return clientMap; + } + } + InputStream in; + Properties clientProp = new Properties(); + try { + in = new FileInputStream(clientPath.toFile()); + clientProp.load(in); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR , e); + throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Load the Properties file", e); + } + // Read the Properties and Load the Clients and their scopes. + clientMap = new HashMap<>(); + // + for (Object propKey : clientProp.keySet()) { + String clientID = (String)propKey; + String clientValue = clientProp.getProperty(clientID); + if (clientValue != null && clientValue.contains(",")) { + ArrayList clientValues = new ArrayList<>(Arrays.asList(clientValue.split("\\s*,\\s*"))); + if(clientValues.get(0)!=null || clientValues.get(1)!=null || clientValues.get(0).isEmpty() || clientValues.get(1).isEmpty()){ + clientMap.put(clientID, clientValues); + } + } + } + if (clientMap.isEmpty()) { + LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS + "No Clients ID , Client Key and Scopes are available. Cannot serve any Clients !!"); + throw new PolicyEngineException("Empty Client file"); + } + oldModified = clientPath.toFile().lastModified(); + return clientMap; + } +} \ No newline at end of file diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestConfig.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestConfig.java new file mode 100644 index 000000000..078cab2aa --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestConfig.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.config; + +import javax.servlet.MultipartConfigElement; + +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.pdp.rest.api.controller.PolicyEngineServices; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; + +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@Configuration +@EnableWebMvc +@EnableSwagger2 +@ComponentScan(basePackageClasses = PolicyEngineServices.class) +public class PDPRestConfig extends WebMvcConfigurerAdapter{ + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); + } + + private ApiInfo apiInfo(){ + return new ApiInfoBuilder() + .title("Policy Engine REST API") + .description("This API helps to make queries against Policy Engine") + .version("3.0") + .build(); + } + + @Bean + public Docket policyAPI(){ + PolicyLogger.info("Setting up Swagger... "); + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("org.onap.policy.pdp.rest.api")) + .paths(PathSelectors.any()) + .build() + .apiInfo(apiInfo()); + } + + @Bean + public MultipartConfigElement multipartConfigElement(){ + String location = System.getProperty("java.io.tmpdir"); + MultipartConfigElement mp = new MultipartConfigElement(location); + return mp; + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestInitializer.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestInitializer.java new file mode 100644 index 000000000..0c1e97e62 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestInitializer.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.config; + +import javax.servlet.MultipartConfigElement; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; +import org.springframework.web.servlet.DispatcherServlet; + +/** + * PDP REST API configuration initialization. + * + * @version 0.1 + */ +public class PDPRestInitializer implements WebApplicationInitializer { + @Override + public void onStartup(ServletContext container) throws ServletException { + PolicyLogger.info("PDP-REST Application Initialization Started... "); + AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); + ctx.register(PDPRestConfig.class); + ctx.setServletContext(container); + ctx.refresh(); + ServletRegistration.Dynamic servlet = container.addServlet( + "dispatcher", new DispatcherServlet(ctx)); + servlet.setLoadOnStartup(1); + servlet.addMapping("/api/*"); + servlet.setMultipartConfig(ctx.getBean(MultipartConfigElement.class)); + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/impl/XACMLPdpPIPFinderFactory.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/impl/XACMLPdpPIPFinderFactory.java new file mode 100644 index 000000000..babcafaeb --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/impl/XACMLPdpPIPFinderFactory.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.impl; + +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + +import org.onap.policy.xacml.api.XACMLErrorConstants; +import com.att.research.xacml.api.pip.PIPException; +import com.att.research.xacml.api.pip.PIPFinder; +import com.att.research.xacml.api.pip.PIPFinderFactory; +import com.att.research.xacml.std.pip.finders.ConfigurableEngineFinder; +import com.att.research.xacml.util.XACMLProperties; + +public class XACMLPdpPIPFinderFactory extends PIPFinderFactory { + private ConfigurableEngineFinder pipFinder; + + private static Log LOGGER = LogFactory.getLog(XACMLPdpPIPFinderFactory.class); + + public XACMLPdpPIPFinderFactory() { + } + + public XACMLPdpPIPFinderFactory(Properties properties) { + } + + @Override + public PIPFinder getFinder() throws PIPException { + if (pipFinder == null) { + synchronized(this) { + if (pipFinder == null) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Creating default configurable engine finder"); + } + pipFinder = new ConfigurableEngineFinder(); + Properties xacmlProperties = null; + try { + xacmlProperties = XACMLProperties.getProperties(); + } catch (Exception ex) { + LOGGER.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR+ "Exception getting XACML properties: " + ex.getMessage(), ex); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, ex, "Exception getting XACML properties"); + return null; + } + if (xacmlProperties != null) { + ((ConfigurableEngineFinder)pipFinder).configure(xacmlProperties); + } + } + } + } + return pipFinder; + } + + @Override + public PIPFinder getFinder(Properties properties) throws PIPException { + if (pipFinder == null) { + synchronized(this) { + if (pipFinder == null) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Creating configurable engine finder using: " + properties); + } + pipFinder = new ConfigurableEngineFinder(); + ((ConfigurableEngineFinder)pipFinder).configure(properties); + } + } + } + return this.pipFinder; + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/impl/XACMLPdpPolicyFinderFactory.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/impl/XACMLPdpPolicyFinderFactory.java new file mode 100644 index 000000000..5641d8b0a --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/impl/XACMLPdpPolicyFinderFactory.java @@ -0,0 +1,208 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.impl; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.onap.policy.xacml.api.XACMLErrorConstants; +import com.att.research.xacml.std.StdStatusCode; +import com.att.research.xacml.std.dom.DOMStructureException; +import com.att.research.xacml.util.FactoryException; +import com.att.research.xacml.util.XACMLProperties; +import com.att.research.xacmlatt.pdp.policy.Policy; +import com.att.research.xacmlatt.pdp.policy.PolicyDef; +import com.att.research.xacmlatt.pdp.policy.PolicyFinder; +import com.att.research.xacmlatt.pdp.policy.PolicyFinderFactory; +import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef; +import com.att.research.xacmlatt.pdp.std.StdPolicyFinder; +import com.google.common.base.Splitter; + +public class XACMLPdpPolicyFinderFactory extends PolicyFinderFactory { + public static final String PROP_FILE = ".file"; + public static final String PROP_URL = ".url"; + + private static Log LOGGER = LogFactory.getLog(XACMLPdpPolicyFinderFactory.class); + private List rootPolicies; + private List referencedPolicies; + private boolean needsInit = true; + + private Properties properties = null; + + public XACMLPdpPolicyFinderFactory() { + // + // Here we differ from the StdPolicyFinderFactory in that we initialize right away. + // We do not wait for a policy request to happen to look for and load policies. + // + this.init(); + } + + public XACMLPdpPolicyFinderFactory(Properties properties) { + // + // Save our properties + // + this.properties = properties; + // + // Here we differ from the StdPolicyFinderFactory in that we initialize right away. + // We do not wait for a policy request to happen to look for and load policies. + // + this.init(); + } + + /** + * Loads the PolicyDef for the given String identifier by looking first + * for a ".file" property associated with the ID and using that to load from a File and + * looking for a ".url" property associated with the ID and using that to load from a URL. + * + * @param policyId the String identifier for the policy + * @return a PolicyDef loaded from the given identifier + */ + protected PolicyDef loadPolicyDef(String policyId) { + String propLocation = null; + if (this.properties == null) { + propLocation = XACMLProperties.getProperty(policyId + PROP_FILE); + } else { + propLocation = this.properties.getProperty(policyId + PROP_FILE); + } + if (propLocation != null) { + File fileLocation = new File(propLocation); + if (!fileLocation.exists()) { + XACMLPdpPolicyFinderFactory.LOGGER.error("Policy file " + fileLocation.getAbsolutePath() + " does not exist."); + } else if (!fileLocation.canRead()) { + XACMLPdpPolicyFinderFactory.LOGGER.error("Policy file " + fileLocation.getAbsolutePath() + " cannot be read."); + } else { + try { + XACMLPdpPolicyFinderFactory.LOGGER.info("Loading policy file " + fileLocation); + PolicyDef policyDef = DOMPolicyDef.load(fileLocation); + if (policyDef != null) { + return policyDef; + } + } catch (DOMStructureException ex) { + XACMLPdpPolicyFinderFactory.LOGGER.error( XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error loading policy file " + fileLocation.getAbsolutePath() + ": " + ex.getMessage(), ex); + return new Policy(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, ex.getMessage()); + } + } + } + if (this.properties == null) { + propLocation = XACMLProperties.getProperty(policyId + PROP_URL); + } else { + propLocation = this.properties.getProperty(policyId + PROP_URL); + } + if (propLocation != null) { + InputStream is = null; + try { + URL url = new URL(propLocation); + URLConnection urlConnection = url.openConnection(); + XACMLPdpPolicyFinderFactory.LOGGER.info("Loading policy file " + url.toString()); + is = urlConnection.getInputStream(); + PolicyDef policyDef = DOMPolicyDef.load(is); + if (policyDef != null) { + return policyDef; + } + } catch (MalformedURLException ex) { + XACMLPdpPolicyFinderFactory.LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Invalid URL " + propLocation + ": " + ex.getMessage(), ex); + } catch (IOException ex) { + XACMLPdpPolicyFinderFactory.LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "IOException opening URL " + propLocation + ": " + ex.getMessage(), ex); + } catch (DOMStructureException ex) { + XACMLPdpPolicyFinderFactory.LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Invalid Policy " + propLocation + ": " + ex.getMessage(), ex); + return new Policy(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, ex.getMessage()); + } finally { + if (is != null) { + try { + is.close(); + } catch (IOException e) { + XACMLPdpPolicyFinderFactory.LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Exception closing InputStream for GET of url " + propLocation + " : " + e.getMessage() + " (May be memory leak)", e); + } + } + } + } + + XACMLPdpPolicyFinderFactory.LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"No known location for Policy " + policyId); + return null; + } + + /** + * Finds the identifiers for all of the policies referenced by the given property name in the + * XACMLProperties and loads them using the requested loading method. + * + * @param propertyName the String name of the property containing the list of policy identifiers + * @return a List of PolicyDefs loaded from the given property name + */ + protected List getPolicyDefs(String propertyName) { + String policyIds = XACMLProperties.getProperty(propertyName); + if (policyIds == null || policyIds.length() == 0) { + return null; + } + + Iterable policyIdArray = Splitter.on(',').trimResults().omitEmptyStrings().split(policyIds); + if (policyIdArray == null) { + return null; + } + + List listPolicyDefs = new ArrayList<>(); + for (String policyId : policyIdArray) { + PolicyDef policyDef = this.loadPolicyDef(policyId); + if (policyDef != null) { + listPolicyDefs.add(policyDef); + } + } + return listPolicyDefs; + } + + protected synchronized void init() { + if (this.needsInit) { + if (XACMLPdpPolicyFinderFactory.LOGGER.isDebugEnabled()) { + XACMLPdpPolicyFinderFactory.LOGGER.debug("Initializing"); + } + this.rootPolicies = this.getPolicyDefs(XACMLProperties.PROP_ROOTPOLICIES); + this.referencedPolicies = this.getPolicyDefs(XACMLProperties.PROP_REFERENCEDPOLICIES); + if (XACMLPdpPolicyFinderFactory.LOGGER.isDebugEnabled()) { + XACMLPdpPolicyFinderFactory.LOGGER.debug("Root Policies: " + this.rootPolicies); + XACMLPdpPolicyFinderFactory.LOGGER.debug("Referenced Policies: " + this.referencedPolicies); + } + this.needsInit = false; + } + } + + @Override + public PolicyFinder getPolicyFinder() throws FactoryException { + // + // Force using any properties that were passed upon construction + // + return new StdPolicyFinder(this.rootPolicies, this.referencedPolicies, this.properties); + } + + @Override + public PolicyFinder getPolicyFinder(Properties properties) throws FactoryException { + return new StdPolicyFinder(this.rootPolicies, this.referencedPolicies, properties); + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/jmx/PdpRestMBeanListener.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/jmx/PdpRestMBeanListener.java new file mode 100644 index 000000000..3232b6b8c --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/jmx/PdpRestMBeanListener.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.jmx; + +import java.lang.management.ManagementFactory; + +import javax.management.MBeanServer; +import javax.management.ObjectName; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.xacml.api.XACMLErrorConstants; +/** + * + * + */ + +@WebListener +public class PdpRestMBeanListener implements ServletContextListener { + private static final String JMX_OBJECT_NAME = "PdpRest:type=PdpRestMonitor"; + private static final Logger LOGGER = FlexLogger.getLogger(PdpRestMBeanListener.class); + + private ObjectName objectName; + + @Override + public void contextInitialized(ServletContextEvent contextEvent) { + if (LOGGER.isInfoEnabled()) + LOGGER.info("Registering."); + + final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + try { + objectName = new ObjectName(JMX_OBJECT_NAME); + server.registerMBean(PdpRestMonitor.getSingleton(), objectName); + LOGGER.info("MBean registered: " + objectName); + } catch (Exception e) { + + LOGGER.warn(e.getMessage(), e); + + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to Register " +e.getMessage(), e); + + } + } + // mark + @Override + public void contextDestroyed(ServletContextEvent contextEvent) { + if (LOGGER.isInfoEnabled()) + LOGGER.info("Unregistering"); + final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + try { + objectName = new ObjectName(JMX_OBJECT_NAME); + server.unregisterMBean(objectName); + if (LOGGER.isInfoEnabled()) + LOGGER.info("MBean unregistered: " + objectName); + } catch (Exception e) { + + LOGGER.warn(e.getMessage(), e); + + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to Destroy Context" +e.getMessage(), e); + + } + } + +} + diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/jmx/PdpRestMonitor.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/jmx/PdpRestMonitor.java new file mode 100644 index 000000000..cdeec9acb --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/jmx/PdpRestMonitor.java @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.jmx; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; + +import org.onap.policy.xacml.util.MetricsUtil.AvgLatency; +import org.onap.policy.xacml.util.MetricsUtil.MaxLatency; +import org.onap.policy.xacml.util.MetricsUtil.MinLatency; + +public class PdpRestMonitor implements PdpRestMonitorMBean { + private static PdpRestMonitor singleton = new PdpRestMonitor(); + + private final AtomicLong pdpEvaluationAttempts = new AtomicLong(); + private final AtomicLong pdpEvaluationSuccesses = new AtomicLong(); + private final AtomicLong pdpEvaluationNA = new AtomicLong(); + private final AtomicLong pdpEvaluationPermit = new AtomicLong(); + private final AtomicLong pdpEvaluationDeny = new AtomicLong(); + private final Map policyCount = new HashMap<>(); + + private final MinLatency pdpEngineDecisionMinLatency = new MinLatency(); + private final MaxLatency pdpEngineDecisionMaxLatency = new MaxLatency(); + private final AvgLatency pdpEngineDecisionAvgLatency = new AvgLatency(); + + private volatile long lastDecisionLatency = 0; + + @Override + public long getPdpEvaluationAttempts() { + return pdpEvaluationAttempts.longValue(); + } + @Override + public long getPdpEvaluationPermit() { + return pdpEvaluationPermit.longValue(); + } + @Override + public long getPdpEvaluationDeny() { + return pdpEvaluationDeny.longValue(); + } + @Override + public long getPdpEvaluationSuccesses() { + return pdpEvaluationSuccesses.longValue(); + } + + @Override + public long getpdpEvaluationNA() { + return pdpEvaluationNA.longValue(); + } + @Override + public long getLastDecisionLatency() { + return lastDecisionLatency; + } + + /** + * @return the pdpEngineDecisionMinLatency + */ + @Override + public long getPdpEngineDecisionMinLatency() { + return pdpEngineDecisionMinLatency.min(); + } + + /** + * @return the pdpEngineDecisionMaxLatency + */ + @Override + public long getPdpEngineDecisionMaxLatency() { + return pdpEngineDecisionMaxLatency.max(); + } + + /** + * @return the pdpEngineDecisionAvgLatency + */ + @Override + public long getPdpEngineDecisionAvgLatency() { + return pdpEngineDecisionAvgLatency.avg(); + } + + @Override + public synchronized void resetLatency() { + this.lastDecisionLatency = 0; + this.pdpEngineDecisionMinLatency.reset(); + this.pdpEngineDecisionMaxLatency.reset(); + this.pdpEngineDecisionAvgLatency.reset(); + } + + @Override + public synchronized void resetCounters() { + this.pdpEvaluationAttempts.set(0); + this.pdpEvaluationSuccesses.set(0); + this.pdpEvaluationNA.set(0); + this.policyCount.clear(); + } + + public void pdpEvaluationAttempts() { + pdpEvaluationAttempts.incrementAndGet(); + } + + public void pdpEvaluationSuccess() { + pdpEvaluationSuccesses.incrementAndGet(); + } + + public void pdpEvaluationNA(){ + pdpEvaluationNA.incrementAndGet(); + } + public void pdpEvaluationPermit(){ + pdpEvaluationPermit.incrementAndGet(); + } + public void pdpEvaluationDeny(){ + pdpEvaluationDeny.incrementAndGet(); + } + + public synchronized void computeLatency(long latency) { + this.lastDecisionLatency = latency; + this.pdpEngineDecisionMinLatency.compute(latency); + this.pdpEngineDecisionMaxLatency.compute(latency); + this.pdpEngineDecisionAvgLatency.compute(latency); + } + + public void policyCountAdd(String policyID, Integer count){ + int countValue = count; + if (policyCount.containsKey(policyID)){ + countValue = countValue + policyCount.get(policyID); + } + policyCount.put(policyID, countValue); + } + public Map getpolicyMap() { + return policyCount; + } + public Integer getpolicyCount(String policyID) { + if (policyCount.containsKey(policyID)){ + return policyCount.get(policyID); + } + return null; + } + + public static PdpRestMonitor getSingleton() { + return singleton; + } + public static void setSingleton(PdpRestMonitor singleton) { + PdpRestMonitor.singleton = singleton; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/jmx/PdpRestMonitorMBean.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/jmx/PdpRestMonitorMBean.java new file mode 100644 index 000000000..4acfbb7f5 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/jmx/PdpRestMonitorMBean.java @@ -0,0 +1,40 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.jmx; + +import java.util.Map; + +public interface PdpRestMonitorMBean { + public long getPdpEvaluationAttempts(); + public long getPdpEvaluationSuccesses(); + public long getLastDecisionLatency(); + public long getPdpEngineDecisionMinLatency(); + public long getPdpEngineDecisionMaxLatency(); + public long getPdpEngineDecisionAvgLatency(); + public Integer getpolicyCount(String policyID); + + public void resetLatency(); + public void resetCounters(); + public long getpdpEvaluationNA(); + public long getPdpEvaluationPermit(); + public long getPdpEvaluationDeny(); + public Map getpolicyMap(); +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java new file mode 100644 index 000000000..c1306572f --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/ManualNotificationUpdateThread.java @@ -0,0 +1,229 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.notifications; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.UUID; + +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.utils.BusConsumer; +import org.onap.policy.utils.BusPublisher; +import org.onap.policy.xacml.api.XACMLErrorConstants; + +import com.att.nsa.cambria.client.CambriaClientFactory; +import com.att.nsa.cambria.client.CambriaConsumer; +import com.att.nsa.cambria.client.CambriaPublisher; +import com.att.research.xacml.util.XACMLProperties; + +@SuppressWarnings("deprecation") +public class ManualNotificationUpdateThread implements Runnable { + + private static final Logger LOGGER = FlexLogger.getLogger(ManualNotificationUpdateThread.class); + + private static String topic = null; + private static CambriaConsumer CConsumer = null; + private static String clusterList = null; + private static String update = null; + private static BusConsumer dmaapConsumer = null; + private static List dmaapList = null; + private static String propNotificationType = null; + private static String aafLogin = null; + private static String aafPassword = null; + + public volatile boolean isRunning = false; + + public synchronized boolean isRunning() { + return this.isRunning; + } + + public synchronized void terminate() { + this.isRunning = false; + } + + /** + * + * This is our thread that runs on startup if the system is configured to UEB to accept manual update requests + * + */ + @Override + public void run() { + synchronized(this) { + this.isRunning = true; + } + + URL aURL = null; + String group = UUID.randomUUID ().toString (); + String id = "0"; + String returnTopic = null; + propNotificationType = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TYPE); + if ("ueb".equals(propNotificationType)){ + try { + clusterList = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS).trim(); + String url = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID); + aURL = new URL(url); + topic = aURL.getHost() + aURL.getPort(); + } catch (NumberFormatException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get UEB cluster list or pdp url: ", e); + this.isRunning = false; + } catch (MalformedURLException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing URL to create topic for Notification ", e); + } + if(aURL != null){ + String consumerTopic = aURL.getHost() + aURL.getPort() + "UpdateRequest"; + SendMessage(consumerTopic, "Starting-Topic"); + final LinkedList urlList = new LinkedList<> (); + for ( String u : clusterList.split ( "," ) ){ + urlList.add ( u ); + } + + try { + CConsumer = CambriaClientFactory.createConsumer ( null, urlList, consumerTopic , group, id, 20*1000, 1000 ); + } catch (MalformedURLException | GeneralSecurityException e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create UEB Consumer: ", e1); + } + + while (this.isRunning()) { + LOGGER.debug("While loop test _ take out "); + try { + for ( String msg : CConsumer.fetch () ){ + LOGGER.debug("Manual Notification Recieved Message " + msg + " from UEB cluster : "); + returnTopic = processMessage(msg); + if(returnTopic != null){ + SendMessage(returnTopic, update); + } + } + } catch (IOException e) { + LOGGER.debug(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing UEB message" + e); + } + } + LOGGER.debug("Stopping UEB Consumer loop will no longer fetch messages from the cluster"); + } + } else if ("dmaap".equals(propNotificationType)) { + String dmaapServers = null; + try { + dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); + topic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC); + aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN"); + aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD"); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get DMaaP servers list:", e); + this.isRunning = false; + } + + if(dmaapServers==null || topic==null){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); + try { + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); + } catch (Exception e) { + LOGGER.error(e); + } + } + + dmaapServers.trim(); + topic.trim(); + aafLogin.trim(); + aafPassword.trim(); + + String consumerTopic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC).trim(); + SendMessage(consumerTopic, "Starting-Topic"); + dmaapList = new ArrayList<>(); + for ( String u : dmaapServers.split ( "," ) ){ + dmaapList.add ( u ); + } + + try { + + dmaapConsumer = new BusConsumer.DmaapConsumerWrapper(dmaapList, consumerTopic, aafLogin, aafPassword, group, id, 20*1000, 1000); + } catch (Exception e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Unable to create DMaaP Consumer: ", e1); + } + + while (this.isRunning()) { + LOGGER.debug("While loop test _ take out "); + try { + for ( String msg : dmaapConsumer.fetch () ){ + LOGGER.debug("Manual Notification Recieved Message " + msg + " from DMaaP server : "); + returnTopic = processMessage(msg); + if(returnTopic != null){ + SendMessage(returnTopic, update); + } + } + }catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in processing DMaaP message: ", e); } + } + LOGGER.debug("Stopping DMaaP Consumer loop will no longer fetch messages from the servers"); + } + } + + private void SendMessage( String topic, String message) { + CambriaPublisher pub = null; + BusPublisher publisher = null; + try { + if ("ueb".equals(propNotificationType)) { + pub = CambriaClientFactory.createSimplePublisher (null, clusterList, topic ); + pub.send( "pdpReturnMessage", message ); + LOGGER.debug("Sending Message to UEB topic: " + topic); + pub.close(); + + } else if ("dmaap".equals(propNotificationType)){ + publisher = new BusPublisher.DmaapPublisherWrapper(dmaapList,topic,aafLogin,aafPassword); + publisher.send( "pdpReturnMessage", message ); + LOGGER.debug("Sending to Message to DMaaP topic: " + topic); + publisher.close(); + } + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ "Error sending notification update: ", e); + } + if(pub != null){ + try { + pub.send( "pdpReturnMessage", message ); + LOGGER.debug("Sending to Message to tpoic" + topic); + pub.close(); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ "Error sending notification update" +e); + } + } + } + + private String processMessage(String msg) { + LOGGER.debug("notification message: " + msg); + String[] UID = msg.split("=")[1].split("\""); + + String returnTopic = topic + UID[0]; + if(msg.contains("Starting-Topic")){ + return null; + } + return returnTopic; + } + public static void setUpdate(String update) { + ManualNotificationUpdateThread.update = update; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/Notification.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/Notification.java new file mode 100644 index 000000000..2d68708c8 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/Notification.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.notifications; + +import java.util.Collection; + +import org.onap.policy.api.NotificationType; + +/** + * Notification is the POJO which will be used to send the Notifications to the Server. + * Notification must contain the Removal and Updated policies. + * + * @version 0.2 + * + */ +public class Notification { + private Collection removedPolicies = null; + private Collection loadedPolicies = null; + private NotificationType notificationType= null; + + public Collection getRemovedPolicies() { + return removedPolicies; + } + + public void setRemovedPolicies(Collection removedPolicies) { + this.removedPolicies = removedPolicies; + } + + public Collection getLoadedPolicies() { + return loadedPolicies; + } + + public void setLoadedPolicies(Collection loadedPolicies) { + this.loadedPolicies = loadedPolicies; + } + + public NotificationType getNotificationType() { + return notificationType; + } + + public void setNotificationType(NotificationType notificationType){ + this.notificationType= notificationType; + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationController.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationController.java new file mode 100644 index 000000000..873db4b6c --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationController.java @@ -0,0 +1,415 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.notifications; + +import java.io.File; +import java.io.FileFilter; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Map; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.io.filefilter.WildcardFileFilter; +import org.onap.policy.api.NotificationType; +import org.onap.policy.api.RemovedPolicy; +import org.onap.policy.api.UpdateType; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.PapUrlResolver; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.xacml.api.XACMLErrorConstants; + +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.att.research.xacmlatt.pdp.policy.AllOf; +import com.att.research.xacmlatt.pdp.policy.AnyOf; +import com.att.research.xacmlatt.pdp.policy.Match; +import com.att.research.xacmlatt.pdp.policy.PolicyDef; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; + +/** + * NotificationController Checks for the Updated and Removed policies. It + * notifies the Server to send Notifications to the Client. + * + * @version 0.2 + * + */ +public class NotificationController { + private static final Logger LOGGER = FlexLogger.getLogger(NotificationController.class); + private static Notification record = new Notification(); + private PDPStatus oldStatus = null; + private Removed removed = null; + private Updated updated = null; + private ManualNotificationUpdateThread registerMaunualNotificationRunnable = null; + private Thread manualNotificationThread = null; + private boolean manualThreadStarted = false; + + private static String notificationJSON = null; + private static String propNotificationType = null; + private static String pdpURL = null; + private static Boolean notificationFlag = false; + + public void check(PDPStatus newStatus,Map policyContainer) { + boolean updated = false; + boolean removed = false; + Notification notification = new Notification(); + HashSet removedPolicies = new HashSet<>(); + HashSet updatedPolicies = new HashSet<>(); + + if (oldStatus == null) { + oldStatus = newStatus; + } + // Debugging purpose only. + LOGGER.debug("old config Status :" + oldStatus.getStatus()); + LOGGER.debug("new config Status :" + newStatus.getStatus()); + + // Depending on the above condition taking the Change as an Update. + if (oldStatus.getStatus().toString() != newStatus.getStatus().toString()) { + LOGGER.info("There is an Update to the PDP"); + LOGGER.debug(oldStatus.getLoadedPolicies()); + LOGGER.debug(newStatus.getLoadedPolicies()); + // Check if there is an Update/additions in the policy. + for (PDPPolicy newPolicy : newStatus.getLoadedPolicies()) { + boolean change = true; + for (PDPPolicy oldPolicy : oldStatus.getLoadedPolicies()) { + // Check if there are same policies. + if (oldPolicy.getId().equals(newPolicy.getId())) { + // Check if they have same version. + if (oldPolicy.getVersion().equals(newPolicy.getVersion())) { + change = false; + } + } + } + // if there is a change Send the notifications to the Client. + if (change) { + sendUpdate(newPolicy, policyContainer); + updated = true; + updatedPolicies.add(this.updated); + } + } + // Check if there is any removal of policy. + for (PDPPolicy oldPolicy : oldStatus.getLoadedPolicies()) { + boolean change = true; + for (PDPPolicy newPolicy : newStatus.getLoadedPolicies()) { + // Check if there are same policies. + if (oldPolicy.getId().equals(newPolicy.getId())) { + // Check if they have same version. + if (oldPolicy.getVersion().equals(newPolicy.getVersion())) { + change = false; + } + } + } + // if there is a change Send the notifications to the Client. + if (change) { + sendremove(oldPolicy); + removed = true; + removedPolicies.add(this.removed); + } + } + } + // At the end the oldStatus must be updated with the newStatus. + oldStatus = newStatus; + // Sending Notification to the Server to pass over to the clients + if (updated || removed) { + // Call the Notification Server.. + notification.setRemovedPolicies(removedPolicies); + notification.setLoadedPolicies(updatedPolicies); + notification = setUpdateTypes(updated, removed, notification); + ObjectWriter om = new ObjectMapper().writer(); + try { + notificationJSON = om.writeValueAsString(notification); + LOGGER.info(notificationJSON); + // NotificationServer Method here. + propNotificationType = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TYPE); + pdpURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_ID); + if (("ueb".equals(propNotificationType)||"dmaap".equals(propNotificationType)) && !manualThreadStarted) { + LOGGER.debug("Starting Thread to accept UEB or DMAAP notfications."); + this.registerMaunualNotificationRunnable = new ManualNotificationUpdateThread(); + this.manualNotificationThread = new Thread(this.registerMaunualNotificationRunnable); + this.manualNotificationThread.start(); + manualThreadStarted = true; + } + String notificationJSON= null; + notificationFlag = true; + try{ + notificationJSON= record(notification); + }catch(Exception e){ + LOGGER.error(e); + } + NotificationServer.setUpdate(notificationJSON); + ManualNotificationUpdateThread.setUpdate(notificationJSON); + } catch (JsonProcessingException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() +e); + } + } + } + + public static void sendNotification(){ + if(notificationFlag){ + try { + NotificationServer.sendNotification(notificationJSON, propNotificationType, pdpURL); + } catch (Exception e) { + LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "+ e.getMessage() + e); + } + notificationFlag = false; + } + } + + private void sendremove(PDPPolicy oldPolicy) { + removed = new Removed(); + // Want to know what is removed ? + LOGGER.info("Policy removed: " + oldPolicy.getId()+ " with version number: " + oldPolicy.getVersion()); + removed.setPolicyName(oldPolicy.getId()); + removed.setVersionNo(oldPolicy.getVersion()); + removeFile(oldPolicy); + } + + private void sendUpdate(PDPPolicy newPolicy,Map policyContainer) { + updated = new Updated(); + // Want to know what is new ? + LOGGER.info("The new Policy is: " + newPolicy.getId()); + LOGGER.info("The version no. is: " + newPolicy.getVersion()); + updated.setPolicyName(newPolicy.getId()); + updated.setVersionNo(newPolicy.getVersion()); + updated.setUpdateType(UpdateType.NEW); + // If the policy is of Config type then retrieve its matches. + if (newPolicy.getName().contains(".Config_")) { + // Take a Configuration copy to PDP webapps. + final String urlStart = "attributeId=URLID,expression"; + final String urlEnd = "}}},{"; + String policy = policyContainer.get(newPolicy.getId()).toString(); + if(policy.contains(urlStart)){ + String urlFinePartOne = policy.substring(policy.indexOf(urlStart)+urlStart.length()); + String urlFinePart = urlFinePartOne.substring(0,urlFinePartOne.indexOf(urlEnd)); + String urlString = urlFinePart.substring(urlFinePart.indexOf("value=$URL")+6); + callPap(urlString, "Config"); + } + Iterator anyOfs = policyContainer.get(newPolicy.getId()).getTarget().getAnyOfs(); + while (anyOfs.hasNext()) { + AnyOf anyOf = anyOfs.next(); + Iterator allOfs = anyOf.getAllOfs(); + while (allOfs.hasNext()) { + AllOf allOf = allOfs.next(); + Iterator matches = allOf.getMatches(); + HashMap matchValues = new HashMap<>(); + while (matches.hasNext()) { + Match match = matches.next(); + LOGGER.info("Attribute Value is: "+ match.getAttributeValue().getValue().toString()); + String[] result = match.getAttributeRetrievalBase().toString().split("attributeId="); + result[1] = result[1].replaceAll("}", ""); + if (!result[1].equals("urn:oasis:names:tc:xacml:1.0:subject:subject-id")) { + LOGGER.info("Attribute id is: " + result[1]); + } + matchValues.put(result[1], match.getAttributeValue().getValue().toString()); + LOGGER.info("Match is : "+ result[1]+ " , " + match.getAttributeValue().getValue().toString()); + } + updated.setMatches(matchValues); + } + } + }else if(newPolicy.getName().contains(".Action_")){ + // Take Configuration copy to PDP Webapps. + // Action policies have .json as extension. + String urlString = "$URL/Action/" + newPolicy.getId().substring(0, newPolicy.getId().lastIndexOf(".")) + ".json"; + callPap(urlString, "Action"); + } + } + + // Adding this for Recording the changes to serve Polling requests.. + private static String record(Notification notification) throws Exception { + // Initialization with updates. + if (record.getRemovedPolicies() == null || record.getLoadedPolicies() == null) { + record.setRemovedPolicies(notification.getRemovedPolicies()); + record.setLoadedPolicies(notification.getLoadedPolicies()); + } else { + // Check if there is anything new and update the record.. + if (record.getLoadedPolicies() != null || record.getRemovedPolicies() != null) { + HashSet removedPolicies = (HashSet) record.getRemovedPolicies(); + HashSet updatedPolicies = (HashSet) record.getLoadedPolicies(); + + // Checking with New updated policies. + if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) { + for (Updated newUpdatedPolicy : notification.getLoadedPolicies()) { + // If it was removed earlier then we need to remove from our record + Iterator oldRemovedPolicy = removedPolicies.iterator(); + while (oldRemovedPolicy.hasNext()) { + Removed policy = oldRemovedPolicy.next(); + if (newUpdatedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if (newUpdatedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldRemovedPolicy.remove(); + } + } + } + // If it was previously updated need to Overwrite it to the record. + Iterator oldUpdatedPolicy = updatedPolicies.iterator(); + while (oldUpdatedPolicy.hasNext()) { + Updated policy = oldUpdatedPolicy.next(); + if (newUpdatedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if (newUpdatedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldUpdatedPolicy.remove(); + } + } + } + updatedPolicies.add(newUpdatedPolicy); + } + } + // Checking with New Removed policies. + if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) { + for (Removed newRemovedPolicy : notification.getRemovedPolicies()) { + // If it was previously removed Overwrite it to the record. + Iterator oldRemovedPolicy = removedPolicies.iterator(); + while (oldRemovedPolicy.hasNext()) { + Removed policy = oldRemovedPolicy.next(); + if (newRemovedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if (newRemovedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldRemovedPolicy.remove(); + } + } + } + // If it was added earlier then we need to remove from our record. + Iterator oldUpdatedPolicy = updatedPolicies.iterator(); + while (oldUpdatedPolicy.hasNext()) { + Updated policy = oldUpdatedPolicy.next(); + if (newRemovedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if (newRemovedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldUpdatedPolicy.remove(); + } + } + } + removedPolicies.add(newRemovedPolicy); + } + } + record.setRemovedPolicies(removedPolicies); + record.setLoadedPolicies(updatedPolicies); + } + } + // Send the Result to the caller. + ObjectWriter om = new ObjectMapper().writer(); + String json = null; + try { + json = om.writeValueAsString(record); + } catch (JsonProcessingException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e); + } + LOGGER.info(json); + return json; + } + + private static Notification setUpdateTypes(boolean updated, boolean removed, Notification notification) { + if(notification!=null){ + if(updated && removed){ + notification.setNotificationType(NotificationType.BOTH); + if(notification.getLoadedPolicies()!=null){ + HashSet updatedPolicies = new HashSet<>(); + for(Updated oldUpdatedPolicy: notification.getLoadedPolicies()){ + Updated updatePolicy = oldUpdatedPolicy; + if(notification.getRemovedPolicies()!=null){ + for(RemovedPolicy removedPolicy: notification.getRemovedPolicies()){ + String regex = ".(\\d)*.xml"; + if(removedPolicy.getPolicyName().replaceAll(regex, "").equals(oldUpdatedPolicy.getPolicyName().replaceAll(regex, ""))){ + updatePolicy.setUpdateType(UpdateType.UPDATE); + break; + } + } + } + updatedPolicies.add(updatePolicy); + } + notification.setLoadedPolicies(updatedPolicies); + } + }else if(updated){ + notification.setNotificationType(NotificationType.UPDATE); + }else if(removed){ + notification.setNotificationType(NotificationType.REMOVE); + } + } + return notification; + } + + private void removeFile(PDPPolicy oldPolicy) { + try{ + Path removedPolicyFile = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_CONFIG)+File.separator+oldPolicy.getId()); + Files.deleteIfExists(removedPolicyFile); + boolean delete=false; + File dir= null; + if(oldPolicy.getName().startsWith("Config")){ + delete = true; + dir = new File(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)+File.separator+"Config"); + }else if(oldPolicy.getName().startsWith("Action")){ + delete = true; + dir = new File(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)+File.separator+"Action"); + } + if(delete){ + FileFilter fileFilter = new WildcardFileFilter(oldPolicy.getId().substring(0, oldPolicy.getId().lastIndexOf("."))+".*"); + File[] configFile = dir.listFiles(fileFilter); + if(configFile.length==1){ + Files.deleteIfExists(configFile[0].toPath()); + } + } + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Couldn't remove the policy/config file " + oldPolicy.getName() + e); + } + } + + private void callPap(String urlString, String type) { + Path configLocation = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_WEBAPPS)+File.separator+type); + if(Files.notExists(configLocation)){ + try { + Files.createDirectories(configLocation); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW +"Failed to create config directory: " + configLocation.toAbsolutePath().toString(), e); + } + } + PapUrlResolver papUrls = PapUrlResolver.getInstance(); + while(papUrls.hasMoreUrls()){ + String papPath = papUrls.getUrl(); + papPath = papPath.substring(0, papPath.lastIndexOf("/pap")); + String papAddress= urlString.replace("$URL", papPath); + String fileName = papAddress.substring(papAddress.lastIndexOf("/")+1); + String fileLocation = configLocation.toString() + File.separator + fileName; + try { + URL papURL = new URL(papAddress); + LOGGER.info("Calling " +papAddress + " for Configuration Copy."); + URLConnection urlConnection = papURL.openConnection(); + File file= new File(fileLocation); + try (InputStream is = urlConnection.getInputStream(); + OutputStream os = new FileOutputStream(file)) { + IOUtils.copy(is, os); + break; + } + } catch (Exception e) { + LOGGER.error(e + e.getMessage()); + } + papUrls.getNext(); + } + } +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationServer.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationServer.java new file mode 100644 index 000000000..690d8c517 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/NotificationServer.java @@ -0,0 +1,224 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.notifications; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.TimeUnit; + +import javax.websocket.OnClose; +import javax.websocket.OnError; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.ServerEndpoint; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pdp.rest.api.services.NotificationService; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.utils.BusPublisher; +import org.onap.policy.xacml.api.XACMLErrorConstants; + +import com.att.nsa.cambria.client.CambriaBatchingPublisher; +import com.att.nsa.cambria.client.CambriaClientBuilders; +import com.att.research.xacml.util.XACMLProperties; + + +/** + * The NotificationServer sends the Server Notifications to the Clients once there is any Event. + * WebSockets is being used as a medium for sending Notifications. + * UEB is being used as a medium for sending Notifications. + * DMAAP is being used as a medium for sending Notifications. + * + * @version 0.2 + * + **/ +@ServerEndpoint(value = "/notifications") +public class NotificationServer { + private static final Logger LOGGER = FlexLogger.getLogger(NotificationServer.class); + private static Queue queue = new ConcurrentLinkedQueue<>(); + private static String update = null; + private static String hosts = null; + private static URL aURL = null; + + @OnOpen + public void openConnection(Session session) { + LOGGER.info("Session Connected: " + session.getId()); + queue.add(session); + } + + @OnClose + public void closeConnection(Session session) { + queue.remove(session); + } + + @OnError + public void error(Session session, Throwable t) { + queue.remove(session); + LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Session Error for : " + session.getId() + " Error: " + t.getMessage()); + + } + + @OnMessage + public void Message(String message, Session session) { + + if(message.equalsIgnoreCase("Manual")) { + try { + session.getBasicRemote().sendText(update); + session.close(); + } catch (IOException e) { + LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "+ e.getMessage() + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending Message update"); + } + } + } + + public static void sendNotification(String notification, String propNotificationType, String pdpURL) throws Exception { + + LOGGER.debug("Notification set to " + propNotificationType); + if (propNotificationType.equals("ueb")){ + + String topic = null; + try { + aURL = new URL(pdpURL); + topic = aURL.getHost() + aURL.getPort(); + } catch (MalformedURLException e1) { + pdpURL = pdpURL.replace("/", ""); + topic = pdpURL.replace(":", ""); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in parsing out pdpURL for UEB notfication "); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e1, "Error in parsing out pdpURL for UEB notfication "); + } + hosts = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); + String apiKey = XACMLProperties.getProperty(XACMLRestProperties.PROP_UEB_API_KEY); + String apiSecret = XACMLProperties.getProperty(XACMLRestProperties.PROP_UEB_API_SECRET); + + LOGGER.debug("Creating Publisher for host: " + hosts + " with topic: " + topic); + CambriaBatchingPublisher pub = null; + try { + if(hosts==null || topic==null || apiKey==null || apiSecret==null){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file "); + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "UEB properties are missing from the property file "); + } + + hosts.trim(); + topic.trim(); + apiKey.trim(); + apiSecret.trim(); + pub = new CambriaClientBuilders.PublisherBuilder () + .usingHosts ( hosts ) + .onTopic ( topic ) + .authenticatedBy ( apiKey, apiSecret ) + .build () + ; + + } catch (MalformedURLException e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error creating the UEB publisher" + e1.getMessage()); + } catch (GeneralSecurityException e1) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error creating the UEB publisher" + e1.getMessage() +e1); + } + if(pub != null){ + try { + pub.send( "MyPartitionKey", notification ); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending notification update" + e.getMessage() + e); + } + // close the publisher. The batching publisher does not send events + // immediately, so you MUST use close to send any remaining messages. + // You provide the amount of time you're willing to wait for the sends + // to succeed before giving up. If any messages are unsent after that time, + // they're returned to your app. You could, for example, persist to disk + // and try again later. + final List stuck = pub.close ( 20, TimeUnit.SECONDS ); + + if (!stuck.isEmpty()){ + LOGGER.error( stuck.size() + " messages unsent" ); + }else{ + LOGGER.info( "Clean exit; all messages sent: " + notification ); + } + } + } else if (propNotificationType.equals("dmaap")) { + + // Setting up the Publisher for DMaaP MR + String dmaapServers = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_SERVERS); + String topic = XACMLProperties.getProperty(XACMLRestProperties.PROP_NOTIFICATION_TOPIC); + String aafLogin = XACMLProperties.getProperty("DMAAP_AAF_LOGIN"); + String aafPassword = XACMLProperties.getProperty("DMAAP_AAF_PASSWORD"); + + try { + if(dmaapServers==null || topic==null){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); + throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "DMaaP properties are missing from the property file "); + } + + dmaapServers.trim(); + topic.trim(); + aafLogin.trim(); + aafPassword.trim(); + + List dmaapList = null; + if(dmaapServers.contains(",")) { + dmaapList = new ArrayList<>(Arrays.asList(dmaapServers.split("\\s*,\\s*"))); + } else { + dmaapList = new ArrayList<>(); + dmaapList.add(dmaapServers); + } + + BusPublisher publisher = + new BusPublisher.DmaapPublisherWrapper(dmaapList, + topic, + aafLogin, + aafPassword); + + // Sending notification through DMaaP Message Router + publisher.send( "MyPartitionKey", notification); + LOGGER.debug("Message Published on DMaaP :" + dmaapList.get(0) + "for Topic: " + topic); + publisher.close(); + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error sending notification update" + e.getMessage() + e); + } + } + + for(Session session: queue) { + try { + session.getBasicRemote().sendText(notification); + } catch (IOException e) { + LOGGER.info(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error in sending the Event Notification: "+ e.getMessage() + e); + } + } + NotificationService.sendNotification(notification); + } + + public static void setUpdate(String update) { + NotificationServer.update = update; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/Removed.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/Removed.java new file mode 100644 index 000000000..f6c9bfaa5 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/Removed.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.notifications; + +import org.onap.policy.api.RemovedPolicy; + + +/** + * Removal is the POJO for removal updates of the Policy. + * It must have the Policy removed and its Version number. + * + * @version 0.2 + * + */ +public class Removed implements RemovedPolicy{ + + private String policyName = null; + private String versionNo = null; + + public String getVersionNo() { + return versionNo; + } + + public void setVersionNo(String versionNo) { + this.versionNo = versionNo; + } + + public String getPolicyName() { + return policyName; + } + + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/Updated.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/Updated.java new file mode 100644 index 000000000..002886de9 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/Updated.java @@ -0,0 +1,74 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.notifications; + +import java.util.HashMap; + +import org.onap.policy.api.LoadedPolicy; +import org.onap.policy.api.UpdateType; + +/** + * Updated is the POJO which consists of any new or Updated Policy information. + * It must hold the Policy Name, version Number, Matches. + * + * @version 0.2 + * + */ +public class Updated implements LoadedPolicy{ + private String policyName = null; + private String versionNo = null; + private HashMap matches = null; + private UpdateType updateType = null; + + public String getPolicyName() { + return policyName; + } + + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + + public String getVersionNo() { + return versionNo; + } + + public void setVersionNo(String versionNo) { + this.versionNo = versionNo; + } + + public HashMap getMatches() { + return matches; + } + + public void setMatches(HashMap matches) { + this.matches = matches; + } + + @Override + public UpdateType getUpdateType() { + return this.updateType; + } + + public void setUpdateType(UpdateType updateType){ + this.updateType = updateType; + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/package-info.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/package-info.java new file mode 100644 index 000000000..5bf894d0a --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/notifications/package-info.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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========================================================= + */ + +/** + * This is the new Addition to the PDP Server added for sending Notifications to the Clients + * about the policy Updates/ Removals. + * + * @version 0.1 + * + */ +package org.onap.policy.pdp.rest.notifications; diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/AuthenticationService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/AuthenticationService.java new file mode 100644 index 000000000..0d066c59c --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/AuthenticationService.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.restAuth; + +import java.util.Base64; +import java.util.StringTokenizer; + +import org.onap.policy.rest.XACMLRestProperties; + +import com.att.research.xacml.util.XACMLProperties; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + +public class AuthenticationService { + private String pdpID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_USERID); + private String pdpPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_PASS); + + public boolean authenticate(String authCredentials) { + + if (null == authCredentials) + return false; + // header value format will be "Basic encodedstring" for Basic authentication. + final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", ""); + String usernameAndPassword = null; + try { + byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword); + usernameAndPassword = new String(decodedBytes, "UTF-8"); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); + return false; + } + try { + final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); + final String username = tokenizer.nextToken(); + final String password = tokenizer.nextToken(); + return pdpID.equals(username) && pdpPass.equals(password); + }catch (Exception e){ + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); + return false; + } + } + +} diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java new file mode 100644 index 000000000..5b01ca9e5 --- /dev/null +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/PDPAuthenticationFilter.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.restAuth; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.policy.pdp.rest.config.PDPApiAuth; + +/** + * Servlet Filter implementation class PDPAuthenticationFilter + */ +@WebFilter("/*") +public class PDPAuthenticationFilter implements Filter { + + public static final String AUTHENTICATION_HEADER = "Authorization"; + public static final String ENVIRONMENT_HEADER = "Environment"; + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain filter) throws IOException, ServletException { + if (request instanceof HttpServletRequest) { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + String environment = httpServletRequest.getHeader(ENVIRONMENT_HEADER); + String authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER); + String path = ((HttpServletRequest) request).getRequestURI(); + // better injected + AuthenticationService authenticationService = new AuthenticationService(); + + boolean authenticationStatus = authenticationService.authenticate(authCredentials); + + if (authenticationStatus) { + if (check(path)) { + // New API request. + path = path.substring(path.substring(1).indexOf("/") + 1); + if (environment == null) { + // Allow Old clients. + if(!path.contains("/api/")){ + request.getRequestDispatcher("/api/" + path).forward(request,response); + }else{ + request.getRequestDispatcher(path).forward(request,response); + } + } else if (environment.equalsIgnoreCase(PDPApiAuth.getEnvironment())) { + // Validated new Clients. + if(!path.contains("/api/")){ + request.getRequestDispatcher("/api/" + path).forward(request,response); + }else{ + request.getRequestDispatcher(path).forward(request,response); + } + } else if(response instanceof HttpServletResponse) { + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + } else { + filter.doFilter(request, response); + } + } else if (path.contains("swagger") || path.contains("api-docs") + || path.contains("configuration") || path.contains("count")) { + path = path.substring(path.substring(1).indexOf("/") + 2); + request.getRequestDispatcher("/api/" + path).forward(request,response); + } else if(path.contains("notifications")){ + filter.doFilter(request, response); + } else { + if (response instanceof HttpServletResponse) { + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + } + } + } + + private boolean check(String path) { + if(path.endsWith("/pdp/")|| path.endsWith("/pdp")|| path.endsWith("/test")){ + return false; + }else{ + return true; + } + } + + @Override + public void destroy() { + // Do nothing. + } + + @Override + public void init(FilterConfig arg0) throws ServletException { + // Do nothing. + } + +} diff --git a/ONAP-PDP-REST/src/main/resources/log4j.properties b/ONAP-PDP-REST/src/main/resources/log4j.properties new file mode 100644 index 000000000..6e5cfac93 --- /dev/null +++ b/ONAP-PDP-REST/src/main/resources/log4j.properties @@ -0,0 +1,71 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP-REST +# ================================================================================ +# 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========================================================= +### + +# +# Use this properties for Deployments. +# +# +# Set root logger level to DEBUG and its only appender to FILE. +#log4j.rootLogger=DEBUG, FILE, CONSOLE +log4j.rootLogger=INFO, FILE + +# FILE appender +log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender +log4j.appender.FILE.File=${catalina.base}/logs/pdp-rest.log +log4j.appender.FILE.ImmediateFlush=true +log4j.appender.FILE.Threshold=debug +log4j.appender.FILE.append=true +log4j.appender.FILE.DatePattern='.'yyyy-MM-dd +log4j.appender.FILE.layout=org.apache.log4j.PatternLayout +log4j.appender.FILE.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss}{GMT+0}+00:00|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%l||%m%n + +# for Developments and Debugging +#log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +#log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +#log4j.appender.CONSOLE.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n + +# +# This is specifically for Xacml request/response logging +# +log4j.logger.xacml.request=INFO, REQUEST_LOG + +log4j.appender.REQUEST_LOG=org.apache.log4j.DailyRollingFileAppender +log4j.appender.REQUEST_LOG.File=${catalina.base}/logs/pdp-rest-reqres.log +log4j.appender.REQUEST_LOG.ImmediateFlush=true +log4j.appender.REQUEST_LOG.Threshold=debug +log4j.appender.REQUEST_LOG.append=true +log4j.appender.REQUEST_LOG.DatePattern='.'yyyy-MM-dd + +log4j.appender.REQUEST_LOG.layout=org.apache.log4j.PatternLayout +log4j.appender.REQUEST_LOG.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} %m%n + +# +# audit (transaction) logging +# +log4j.logger.auditLogger=INFO,AUDIT_LOG +log4j.additivity.auditLogger=false + +log4j.appender.AUDIT_LOG=org.apache.log4j.DailyRollingFileAppender +log4j.appender.AUDIT_LOG.File=${catalina.base}/logs/audit.log +log4j.appender.AUDIT_LOG.Append=true +log4j.appender.AUDIT_LOG.DatePattern='.'yyyy-MM-dd +log4j.appender.AUDIT_LOG.threshold=INFO +log4j.appender.AUDIT_LOG.layout=org.apache.log4j.EnhancedPatternLayout +log4j.appender.AUDIT_LOG.layout.ConversionPattern=%d{yyyy-MM-dd'T'HH:mm:ss}{GMT+0}+00:00|%X{requestId}|%X{serviceInstanceId}|%t|%X{serverName}|%X{serviceName}|%X{instanceUuid}|%p|%X{severity}|%X{serverIpAddress}|%X{server}|%X{clientIpAddress}|%X{className}|%X{timer}|%m%n diff --git a/ONAP-PDP-REST/src/main/resources/logback.xml b/ONAP-PDP-REST/src/main/resources/logback.xml new file mode 100644 index 000000000..70e9f90c7 --- /dev/null +++ b/ONAP-PDP-REST/src/main/resources/logback.xml @@ -0,0 +1,253 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + --> + + + + + + + + + + + + + + + + + + + + ${defaultPattern} + + + + + + + + + + + + + ${logDirectory}/${auditLogName}.log + + ${logDirectory}/${auditLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + ${defaultAuditPattern} + + + + + 256 + + + + + + + + ${logDirectory}/${metricsLogName}.log + + ${logDirectory}/${metricsLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + + ${defaultMetricPattern} + + + + + 256 + + + + + + + + ${logDirectory}/${errorLogName}.log + + ${logDirectory}/${errorLogName}.%i.log.zip + + 1 + 9 + + + ERROR + + + 5MB + + + ${defaultErrorPattern} + + + + + 256 + + + + + + + ${debugLogDirectory}/${debugLogName}.log + + ${debugLogDirectory}/${debugLogName}.%i.log.zip + + 1 + 9 + + + DEBUG + + + 5MB + + + ${debugLoggerPattern} + + + + + 256 + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/PapUrlResolverTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/PapUrlResolverTest.java new file mode 100644 index 000000000..c8716c3bc --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/PapUrlResolverTest.java @@ -0,0 +1,224 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Properties; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.policy.rest.XACMLRestProperties; + +public class PapUrlResolverTest { + + + @Test + public void testPropertyModifications(){ + DateFormat df = new SimpleDateFormat(); + //first sort order + String urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; + String failed = "-1,-1,-1,-1"; + String succeeded = "-1,-1,-1,-1"; + PapUrlResolver rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertEquals(rs.getProperties().getProperty(XACMLRestProperties.PROP_PAP_URLS),urls); + + rs.failed(); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + rs.succeeded(); + Assert.assertFalse(rs.hasMoreUrls()); + Properties prop = rs.getProperties(); + Assert.assertEquals(df.format(new Date())+",-1,-1,-1",prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS)); + Assert.assertEquals("-1,"+df.format(new Date())+",-1,-1",prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS)); + + failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); + succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://two.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://three.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://four.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.succeeded(); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + prop = rs.getProperties(); + Assert.assertEquals("-1,-1,-1,-1",prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS)); + + failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); + succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.succeeded(); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + prop = rs.getProperties(); + failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); + succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.succeeded(); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + prop = rs.getProperties(); + failed = prop.getProperty(XACMLRestProperties.PROP_PAP_FAILED_URLS); + succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.succeeded(); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + + + prop = rs.getProperties(); + succeeded = prop.getProperty(XACMLRestProperties.PROP_PAP_SUCCEEDED_URLS); + } + @SuppressWarnings("unused") + @Test + public void testModifyUrl(){ + String newUrl = PapUrlResolver.modifyUrl("http://mypap1.com/pap?id=987654", "http://mypap2.com:45/pap/"); + int u = 8; + } + + @Test + public void testSorts(){ + long currentTime = new Date().getTime(); + DateFormat df = new SimpleDateFormat(); + //first sort order + String urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; + String failed = df.format(new Date(currentTime-3600000))+",-1,-1,"+df.format(new Date(currentTime-3200000)); + String succeeded = "-1,8/13/15 5:41 PM,8/13/15 4:41 PM,-1"; + PapUrlResolver rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://two.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://three.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://four.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + + urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; + failed = "-1,-1,-1,-1"; + succeeded = "-1,"+df.format(new Date(currentTime-3600000))+","+df.format(new Date(currentTime-6600000))+",-1"; + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://two.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://three.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://four.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + + urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; + failed = "-1,-1,-1,-1"; + succeeded = "-1,-1,-1,-1"; + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://two.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://three.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://four.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + + urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; + failed = df.format(new Date(currentTime-3900000))+","+df.format(new Date(currentTime-5600000))+","+df.format(new Date(currentTime-4600000))+","+df.format(new Date(currentTime-3600000)); + succeeded = "-1,-1,-1,-1"; + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://two.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://three.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://four.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + + urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; + failed = df.format(new Date(currentTime-(3600000*4)))+",-1,-1,-1"; + succeeded = "-1,-1,-1,-1"; + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://two.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://three.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://four.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + + urls = "http://one.localhost.com,http://two.localhost.com,http://three.localhost.com,http://four.localhost.com"; + failed = df.format(new Date(currentTime-(3600000*6)))+",-1,-1,-1"; + succeeded = "-1,-1,-1,-1"; + rs = PapUrlResolver.getInstance(urls, failed, succeeded); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://one.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://two.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://three.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertTrue(rs.hasMoreUrls()); + Assert.assertEquals("http://four.localhost.com", rs.getUrl()); + rs.getNext(); + Assert.assertFalse(rs.hasMoreUrls()); + } +} diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/XACMLPdpServletTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/XACMLPdpServletTest.java new file mode 100644 index 000000000..3e3f584a9 --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/XACMLPdpServletTest.java @@ -0,0 +1,364 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Random; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.policy.common.im.AdministrativeStateException; +import org.onap.policy.common.im.IntegrityMonitor; +import org.onap.policy.common.im.StandbyStatusException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockServletConfig; + +import com.mockrunner.mock.web.MockServletInputStream; + +import junit.framework.TestCase; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(IntegrityMonitor.class) // so PowerMock can mock static method of IntegrityMonitor +public class XACMLPdpServletTest extends TestCase{ + private static Logger LOGGER = FlexLogger.getLogger(XACMLPdpServletTest.class); + + private List headers = new ArrayList<>(); + + private HttpServletRequest httpServletRequest; + private HttpServletResponse httpServletResponse; + private ServletOutputStream mockOutput; + private ServletInputStream mockInput; + private ServletConfig servletConfig; + private XACMLPdpServlet pdpServlet; + private IntegrityMonitor im; + + + + @Before + public void setUp(){ + httpServletRequest = Mockito.mock(HttpServletRequest.class); + Mockito.when(httpServletRequest.getMethod()).thenReturn("POST"); + Mockito.when(httpServletRequest.getHeaderNames()).thenReturn(Collections.enumeration(headers)); + Mockito.when(httpServletRequest.getAttributeNames()).thenReturn(Collections.enumeration(headers)); + + + mockOutput = Mockito.mock(ServletOutputStream.class); + + httpServletResponse = Mockito.mock(MockHttpServletResponse.class); + + try { + Mockito.when(httpServletResponse.getOutputStream()).thenReturn(mockOutput); + } catch (IOException e) { + fail(); + } + + servletConfig = Mockito.mock(MockServletConfig.class); + //servletConfig + Mockito.when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers)); + pdpServlet = new XACMLPdpServlet(); + + Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.pdp.properties"); + + System.setProperty("xacml.properties", "xacml.pdp.properties"); + System.setProperty("xacml.rest.pdp.config", "config_testing"); + System.setProperty("xacml.rest.pdp.webapps", "/webapps"); + System.setProperty("xacml.rootPolicies", "test_PolicyEngine.xml"); + System.setProperty("xacml.referencedPolicies", "test_PolicyEngine.xml"); + System.setProperty("test_PolicyEngine.xml.file", "config_testing\\test_PolicyEngine.xml"); + System.setProperty("xacml.rest.pdp.register", "false"); + System.setProperty("com.sun.management.jmxremote.port", "9999"); + + im = Mockito.mock(IntegrityMonitor.class); + // Need PowerMockito for mocking static method getInstance(...) + PowerMockito.mockStatic(IntegrityMonitor.class); + try { + // when IntegrityMonitor.getInstance is called, return the mock object + PowerMockito.when(IntegrityMonitor.getInstance(Mockito.anyString(), Mockito.any(Properties.class))).thenReturn(im); + } catch (Exception e1) { + LOGGER.error("Exception Occured"+e1); + } + + try { + Mockito.doNothing().when(im).startTransaction(); + } catch (StandbyStatusException | AdministrativeStateException e) { + fail(); + } + Mockito.doNothing().when(im).endTransaction(); + } + + public void testInit(){ + LOGGER.info("XACMLPdpServletTest - testInit"); + try { + pdpServlet.init(servletConfig); + assertTrue(true); + } catch (Exception e) { + LOGGER.error("Exception Occured"+e); + fail(); + + } + + } + + public void testDoGetNoTypeError(){ + LOGGER.info("XACMLPdpServletTest - testDoGetNoTypeError"); + try{ + pdpServlet.init(servletConfig); + pdpServlet.doGet(httpServletRequest, httpServletResponse); + Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_BAD_REQUEST, "type not 'config' or 'hb'"); + assertTrue(true); + }catch(Exception e){ + System.out.println("Unexpected exception in testDoGetNoTypeError"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoGetConfigType(){ + LOGGER.info("XACMLPdpServletTest - testDoGetConfigType"); + Mockito.when(httpServletRequest.getParameter("type")).thenReturn("config"); + + try{ + pdpServlet.init(servletConfig); + pdpServlet.doGet(httpServletRequest, httpServletResponse); + Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoGetConfigType"); + LOGGER.error("Exception Occured"+e); + fail(); + } + + } + + + public void testDoGetTypeHb(){ + LOGGER.info("XACMLPdpServletTest - testDoGetTypeHb"); + try{ + Mockito.when(httpServletRequest.getParameter("type")).thenReturn("hb"); + pdpServlet.init(servletConfig); + pdpServlet.doGet(httpServletRequest, httpServletResponse); + Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_NO_CONTENT); + assertTrue(true); + }catch(Exception e){ + System.out.println("Unexpected exception in testDoGetTypeHb"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + public void testDoGetTypeStatus(){ + LOGGER.info("XACMLPdpServletTest - testDoGetTypeStatus"); + try{ + Mockito.when(httpServletRequest.getParameter("type")).thenReturn("Status"); + pdpServlet.init(servletConfig); + pdpServlet.doGet(httpServletRequest, httpServletResponse); + Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); + assertTrue(true); + }catch(Exception e){ + System.out.println("Unexpected exception in testDoGetTypeStatus"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPost(){ + LOGGER.info("XACMLPdpServletTest - testDoPost"); + try{ + pdpServlet.init(servletConfig); + pdpServlet.doPost(httpServletRequest, httpServletResponse); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPost"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPostToLong(){ + LOGGER.info("XACMLPdpServletTest - testDoPostToLong"); + try{ + Mockito.when(httpServletRequest.getContentType()).thenReturn("stuff"); + Mockito.when(httpServletRequest.getContentLength()).thenReturn(32768); + + pdpServlet.init(servletConfig); + pdpServlet.doPost(httpServletRequest, httpServletResponse); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPostToLong"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPostContentLengthNegative(){ + LOGGER.info("XACMLPdpServletTest - testDoPostToLong"); + try{ + Mockito.when(httpServletRequest.getContentType()).thenReturn("stuff"); + Mockito.when(httpServletRequest.getContentLength()).thenReturn(-1); + + pdpServlet.init(servletConfig); + pdpServlet.doPost(httpServletRequest, httpServletResponse); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPostContentLengthNegative"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPostContentTypeNonValid(){ + LOGGER.info("XACMLPdpServletTest - testDoPostToLong"); + try{ + Mockito.when(httpServletRequest.getContentType()).thenReturn(";"); + Mockito.when(httpServletRequest.getContentLength()).thenReturn(30768); + + pdpServlet.init(servletConfig); + pdpServlet.doPost(httpServletRequest, httpServletResponse); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPostContentTypeNonValid"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPostContentTypeConfigurationError(){ + LOGGER.info("XACMLPdpServletTest - testDoPostToLong"); + try{ + Mockito.when(httpServletRequest.getContentType()).thenReturn("stuff"); + Mockito.when(httpServletRequest.getContentLength()).thenReturn(30768); + + pdpServlet.init(servletConfig); + pdpServlet.doPost(httpServletRequest, httpServletResponse); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPostContentTypeConfigurationError"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPutCacheEmpty(){ + LOGGER.info("XACMLPdpServletTest - testDoPutCacheEmpty"); + mockInput = Mockito.mock(ServletInputStream.class); + + try{ + Mockito.when(httpServletRequest.getParameter("cache")).thenReturn("cache"); + Mockito.when(httpServletRequest.getContentType()).thenReturn("text/x-java-properties"); + Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); + pdpServlet.init(servletConfig); + pdpServlet.doPut(httpServletRequest, httpServletResponse); + Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT must contain at least one property"); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPutCacheEmpty"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPutConfigPolicies(){ + LOGGER.info("XACMLPdpServletTest - testDoPutConfigPolicies"); + byte[] b = new byte[20]; + new Random().nextBytes(b); + + mockInput = new MockServletInputStream(b); + + try{ + Mockito.when(httpServletRequest.getParameter("cache")).thenReturn("policies"); + Mockito.when(httpServletRequest.getContentType()).thenReturn("text/x-java-properties"); + Mockito.when(httpServletRequest.getInputStream()).thenReturn(mockInput); + pdpServlet.init(servletConfig); + pdpServlet.doPut(httpServletRequest, httpServletResponse); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPutConfigPolicies"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPutToLong(){ + LOGGER.info("XACMLPdpServletTest - testDoPutToLong"); + try{ + Mockito.when(httpServletRequest.getParameter("cache")).thenReturn("policies"); + + Mockito.when(httpServletRequest.getContentType()).thenReturn("text/x-java-properties"); + Mockito.when(httpServletRequest.getContentLength()).thenReturn(1000000000); + + pdpServlet.init(servletConfig); + pdpServlet.doPut(httpServletRequest, httpServletResponse); + Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_BAD_REQUEST, "Content-Length larger than server will accept."); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPutToLong"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDoPutInvalidContentType(){ + LOGGER.info("XACMLPdpServletTest - testDoPutToLong"); + try{ + Mockito.when(httpServletRequest.getParameter("cache")).thenReturn("policies"); + + Mockito.when(httpServletRequest.getContentType()).thenReturn("text/json"); + Mockito.when(httpServletRequest.getContentLength()).thenReturn(32768); + + pdpServlet.init(servletConfig); + pdpServlet.doPut(httpServletRequest, httpServletResponse); + Mockito.verify(httpServletResponse).sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid cache: 'policies' or content-type: 'text/json'"); + assertTrue(true); + }catch (Exception e){ + System.out.println("Unexpected exception in testDoPutInvalidContentType"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } + + public void testDestroy(){ + LOGGER.info("XACMLPdpServletTest - testDestroy"); + + try{ + pdpServlet.init(servletConfig); + pdpServlet.destroy(); + }catch(Exception e){ + System.out.println("Unexpected exception in testDestroy"); + LOGGER.error("Exception Occured"+e); + fail(); + } + } +} diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/services/PDPServicesTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/services/PDPServicesTest.java new file mode 100644 index 000000000..e77a8517a --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/services/PDPServicesTest.java @@ -0,0 +1,194 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.services; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.Map.Entry; + +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonObject; +import javax.json.JsonObjectBuilder; + +import org.junit.*; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +import org.onap.policy.api.DecisionRequestParameters; +import org.onap.policy.api.PolicyDecisionException; +import org.onap.policy.pdp.rest.api.models.PDPResponse; +import org.onap.policy.pdp.rest.config.PDPRestConfig; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PDPRestConfig.class}) +@WebAppConfiguration +public class PDPServicesTest { + /** + * Run the PDPServices() constructor test. + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + @Test + public void testPDPServices_1() + throws Exception { + PDPServices result = new PDPServices(); + assertNotNull(result); + // add additional test code here + } + + /** + * Run the Collection generateRequest(String,UUID,boolean,boolean) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + @Test + public void testGenerateRequest_1() + throws Exception { + DecisionRequestParameters pep = new DecisionRequestParameters(); + Map eventAttributes = new HashMap<>(); + eventAttributes.put("TEST", "test"); + pep.setONAPComponentName("te123"); + pep.setDecisionAttributes(eventAttributes); + PDPServices fixture = new PDPServices(); + + //Failure Tests. + String jsonString = getModel(pep).toString(); + UUID requestID = UUID.randomUUID(); + + Collection result = fixture.generateRequest(jsonString, requestID, false, true); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.pdp.rest.api.services.PDPServices + assertNotNull(result); + + } + + private JsonObject getModel(DecisionRequestParameters pep) throws PolicyDecisionException{ + JsonArrayBuilder resourceArray = Json.createArrayBuilder(); + + Map decisionAttributes = pep.getDecisionAttributes(); + for (Entry key : decisionAttributes.entrySet()) { + JsonObjectBuilder resourceBuilder = Json.createObjectBuilder(); + if (key.getValue().matches("[0-9]+")) { + + if ((key.getKey().equals("ErrorCode")) || (key.getKey().equals("WorkStep"))) { + + resourceBuilder.add("Value", key.getValue()); + + } else { + + int val = Integer.parseInt(key.getValue()); + resourceBuilder.add("Value", val); + + } + + } else { + resourceBuilder.add("Value", key.getValue()); + } + resourceBuilder.add("AttributeId", key.getKey()); + resourceArray.add(resourceBuilder); + } + return Json.createObjectBuilder() + .add("Request", Json.createObjectBuilder() + .add("AccessSubject", Json.createObjectBuilder() + .add("Attribute", Json.createObjectBuilder() + .add("Value", pep.getONAPComponentName()) + .add("AttributeId", "ONAPName"))) + .add("Resource", Json.createObjectBuilder() + .add("Attribute", resourceArray)) + .add("Action", Json.createObjectBuilder() + .add("Attribute", Json.createObjectBuilder() + .add("Value", "DECIDE") + .add("AttributeId", "urn:oasis:names:tc:xacml:1.0:action:action-id")))) + .build(); + } + + /** + * Run the Collection generateRequest(String,UUID,boolean,boolean) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + @Test(expected = org.onap.policy.api.PolicyException.class) + public void testGenerateRequest_2() + throws Exception { + PDPServices fixture = new PDPServices(); + fixture.generateRequest("", UUID.randomUUID(), true, true); + String jsonString = ""; + UUID requestID = UUID.randomUUID(); + boolean unique = true; + boolean decide = true; + + Collection result = fixture.generateRequest(jsonString, requestID, unique, decide); + + // add additional test code here + assertNotNull(result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 7/20/17 9:26 AM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PDPServicesTest.class); + } +} \ No newline at end of file diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/NotificationAPITest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/NotificationAPITest.java new file mode 100644 index 000000000..096f7a37a --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/NotificationAPITest.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.test; + +import static org.awaitility.Awaitility.await; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.pdp.rest.api.services.NotificationService; +import org.onap.policy.pdp.rest.api.services.NotificationService.NotificationServiceType; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.springframework.http.HttpStatus; + +import com.att.research.xacml.util.XACMLProperties; + +public class NotificationAPITest { + + @Before + public void setup() throws IOException{ + // Fix properties for next test cases. + XACMLProperties.reloadProperties(); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/pass.xacml.pdp.properties"); + XACMLProperties.getProperties(); + } + + @Test + public void testPropertyFailure() throws IOException{ + // Change properties and fail. + XACMLProperties.reloadProperties(); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/fail.xacml.pdp.properties"); + XACMLProperties.getProperties(); + NotificationService notificationService = new NotificationService(null,null,null); + assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); + setup(); + } + + @Test + public void testFailureTopicName(){ + NotificationService notificationService = new NotificationService(null,null,null); + assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); + assertEquals(XACMLErrorConstants.ERROR_DATA_ISSUE + "org.onap.policy.api.PolicyException: Notification Topic is null", notificationService.getResult()); + notificationService = new NotificationService(" ",null,null); + assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); + assertEquals(XACMLErrorConstants.ERROR_DATA_ISSUE + "org.onap.policy.api.PolicyException: Notification Topic is not valid. ", notificationService.getResult()); + } + + @Test + public void testFailureServiceType(){ + NotificationService notificationService = new NotificationService("test",null,null); + assertEquals(HttpStatus.BAD_REQUEST, notificationService.getResponseCode()); + } + + @Test + public void threadTest() throws InterruptedException{ + NotificationService notificationSerivce = new NotificationService("test",null,NotificationServiceType.ADD); + assertEquals(HttpStatus.OK, notificationSerivce.getResponseCode()); + // Wait for thread to remove the Topic Entry. + await().atMost(Integer.toUnsignedLong(2500),TimeUnit.MILLISECONDS).until(()-> { + // Trying to remove again should fail + NotificationService nService = new NotificationService("test",null,NotificationServiceType.REMOVE); + return HttpStatus.BAD_REQUEST.equals(nService.getResponseCode()); + }); + // Coverage Tests, Call Notification Service. + NotificationService.sendNotification("test"); + } +} diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java new file mode 100644 index 000000000..2a76f581c --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java @@ -0,0 +1,832 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.test; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; +import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.ConfigRequestParameters; +import org.onap.policy.api.DecisionRequestParameters; +import org.onap.policy.api.DeletePolicyCondition; +import org.onap.policy.api.DeletePolicyParameters; +import org.onap.policy.api.DictionaryParameters; +import org.onap.policy.api.DictionaryType; +import org.onap.policy.api.EventRequestParameters; +import org.onap.policy.api.PolicyClass; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.PolicyType; +import org.onap.policy.api.PushPolicyParameters; +import org.onap.policy.pdp.rest.XACMLPdpServlet; +import org.onap.policy.pdp.rest.api.models.ConfigFirewallPolicyAPIRequest; +import org.onap.policy.pdp.rest.api.models.ConfigNameRequest; +import org.onap.policy.pdp.rest.api.models.ConfigPolicyAPIRequest; +import org.onap.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl; +import org.onap.policy.pdp.rest.config.PDPRestConfig; +import org.onap.policy.utils.PolicyUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.web.WebAppConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.context.WebApplicationContext; + +import com.att.research.xacml.util.XACMLProperties; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {PDPRestConfig.class}) +@WebAppConfiguration +public class PolicyEngineServicesTest { + private static final String CLIENTAUTHHEADER = "ClientAuth"; + private static final String UUIDHEADER = "X-ECOMP-RequestID"; + // This value is as per test resource code. Don't change this. + private static final String CLIENTAUTHVALUE = "Basic cHl0aG9uOnRlc3Q="; + private static final String ERRORCLIENTVALUE = "Basic dGVzdDp0ZXN0MTIz"; + + private MockMvc mockMvc; + private HttpHeaders headers; + + @Autowired + private WebApplicationContext webApplicationContext; + + @Before() + public void setup() throws IOException{ + headers = new HttpHeaders(); + headers.add(CLIENTAUTHHEADER, CLIENTAUTHVALUE); + XACMLProperties.reloadProperties(); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/pass.xacml.pdp.properties"); + XACMLProperties.getProperties(); + this.mockMvc = webAppContextSetup(webApplicationContext).build(); + } + + @Test + public void getConfigAPIFailureTest() throws Exception{ + ConfigRequestParameters pep = new ConfigRequestParameters(); + pep.setPolicyName(".*"); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is(400)); + // Authorization tests. + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, ERRORCLIENTVALUE)) + .andExpect(status().isUnauthorized()); + // Set wrong request. + pep.setPolicyName(null); + pep.setConfigName("test"); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, "123").contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + } + + @Test + public void getConfigServiceTest() throws Exception{ + ConfigRequestParameters pep = new ConfigRequestParameters(); + pep.setPolicyName(".*"); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, UUID.randomUUID()).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + // Without policyName and using onapName and other fields. + pep.setPolicyName(null); + pep.setOnapName("test"); + pep.setConfigName("test"); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + // with config attributes. + Map configAttributes = new HashMap<>(); + configAttributes.put("test", "test"); + pep.setConfigAttributes(configAttributes); + pep.makeUnique(true); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + public void getConfigByPolicyNameTest() throws Exception{ + ConfigNameRequest pep = new ConfigNameRequest(); + pep.setPolicyName(".*"); + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is(400)); + // Authorization tests. + mockMvc.perform(post("/getConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/getConfigByPolicyName").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, UUID.randomUUID()).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + public void listConfigTest() throws Exception{ + ConfigRequestParameters pep = new ConfigRequestParameters(); + pep.setPolicyName(".*"); + mockMvc.perform(post("/listConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().is(400)); + // Authorization tests. + mockMvc.perform(post("/listConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "")) + .andExpect(status().isUnauthorized()); + mockMvc.perform(post("/listConfig").content(PolicyUtils.objectToJsonString(pep)).headers(headers).header(UUIDHEADER, UUID.randomUUID()).contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + } + + @Test + public void getMetricsTest() throws Exception{ + //Failure Tests. + mockMvc.perform(get("/getMetrics")).andExpect(status().isBadRequest()); + mockMvc.perform(get("/getMetrics").header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(get("/getMetrics").headers(headers).header(UUIDHEADER, "123")).andExpect(status().isOk()); + mockMvc.perform(get("/getMetrics").headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isOk()); + mockMvc.perform(get("/getMetrics").headers(headers)).andExpect(status().isOk()); + } + + @Test + public void getNotificationAuthFailureTest() throws Exception{ + mockMvc.perform(post("/getNotification").header(CLIENTAUTHHEADER, "").content("test")).andExpect(status().isUnauthorized()); + mockMvc.perform(post("/getNotification").header(CLIENTAUTHHEADER, "Basic test123").content("test")).andExpect(status().isUnauthorized()); + mockMvc.perform(post("/getNotification").header(CLIENTAUTHHEADER, ERRORCLIENTVALUE).content(" ")).andExpect(status().isUnauthorized()); + } + + @Test + public void getNotificationTopicFailureTest() throws Exception{ + mockMvc.perform(post("/getNotification")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/getNotification").headers(headers).content("")).andExpect(status().isBadRequest()); + } + + @Test + public void getNotificationTopicValidFailTest() throws Exception{ + // Check failures. + mockMvc.perform(post("/getNotification").headers(headers).content(" ")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/stopNotification").headers(headers).content(" ")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/sendHeartbeat").headers(headers).content(" ")).andExpect(status().isBadRequest()); + } + + @Test + public void getNotificationTopicValidPassTest() throws Exception{ + // Add a Topic. + mockMvc.perform(post("/getNotification").headers(headers).header(UUIDHEADER, "123").content("test")).andExpect(status().isOk()); + // Try to add same topic should fail. + mockMvc.perform(post("/getNotification").headers(headers).header(UUIDHEADER, UUID.randomUUID()).content("test")).andExpect(status().isBadRequest()); + // do a heart beat. + mockMvc.perform(post("/sendHeartbeat").headers(headers).content("test")).andExpect(status().isOk()); + // remove the added Topic. + mockMvc.perform(post("/stopNotification").headers(headers).content("test")).andExpect(status().isOk()); + // try to remove again should fail. + mockMvc.perform(post("/sendHeartbeat").headers(headers).content("test")).andExpect(status().isBadRequest()); + } + + @Test + public void sendEventTest() throws Exception{ + EventRequestParameters pep = new EventRequestParameters(); + Map eventAttributes = new HashMap<>(); + eventAttributes.put("TEST", "test"); + pep.setEventAttributes(eventAttributes); + //Failure Tests. + mockMvc.perform(post("/sendEvent")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isOk()); + pep.setEventAttributes(null); + mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setEventAttributes(eventAttributes); + mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isOk()); + pep.setEventAttributes(eventAttributes); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(post("/sendEvent").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isOk()); + } + + @Test + public void getDecisionTest() throws Exception{ + DecisionRequestParameters pep = new DecisionRequestParameters(); + Map eventAttributes = new HashMap<>(); + eventAttributes.put("TEST", "test"); + pep.setONAPComponentName("te123"); + pep.setDecisionAttributes(eventAttributes); + //Failure Tests. + mockMvc.perform(post("/getDecision")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isOk()); + pep.setDecisionAttributes(null); + pep.setONAPComponentName(null); + mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setONAPComponentName("testing"); + mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setDecisionAttributes(eventAttributes); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(post("/getDecision").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isOk()); + } + + @Test + public void pushPolicyTest() throws Exception{ + PushPolicyParameters pep = new PushPolicyParameters(); + //Failure Tests. + mockMvc.perform(put("/pushPolicy")).andExpect(status().isBadRequest()); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("scopeless"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyName("testing.test"); + pep.setPolicyType("wrong"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("BRMS_PARAM"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("BRMS_RAW"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("MicroService"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("ClosedLoop_PM"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("ClosedLoop_Fault"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("Base"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("Decision"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("Action"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("Firewall"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPdpGroup("default"); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isBadRequest()); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(put("/pushPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + } + + @Test + public void deletePolicyTest() throws Exception{ + DeletePolicyParameters pep = new DeletePolicyParameters(); + //Failure Tests. + mockMvc.perform(delete("/deletePolicy")).andExpect(status().isBadRequest()); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("testing"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "test123")).andExpect(status().isBadRequest()); + pep.setPolicyName("testscope.name"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyName("testscope.name"); + pep.setPolicyType("wrong"); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("BRMS_PARAM"); + pep.setPolicyComponent("wrong"); + pep.setRequestID(null); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyType("BRMS_RAW"); + pep.setPolicyComponent("PDP"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("MicroService"); + pep.setPolicyComponent("PAP"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("ClosedLoop_PM"); + pep.setPolicyComponent("PDP"); + pep.setDeleteCondition(DeletePolicyCondition.ALL); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("ClosedLoop_Fault"); + pep.setDeleteCondition(DeletePolicyCondition.ONE); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("Base"); + pep.setPolicyComponent("PAP"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("Decision"); + pep.setPolicyComponent("PDP"); + pep.setPolicyName("test.xml"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyType("Action"); + pep.setPolicyName("scope.Config_test.xml"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPdpGroup("default"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyComponent("PAP"); + pep.setPolicyType("Firewall"); + pep.setDeleteCondition(null); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyComponent("PAP"); + pep.setDeleteCondition(DeletePolicyCondition.ONE); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyComponent("fail"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyComponent("PDP"); + pep.setPolicyName("testscope.policyName"); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyComponent(null); + mockMvc.perform(delete("/deletePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + } + + @Test + public void createUpdatePolicyTest() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + //Failure Tests. + mockMvc.perform(put("/createPolicy")).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + setCreateUpdateImpl(); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("failName"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "test 123")).andExpect(status().isBadRequest()); + pep.setPolicyName("test. name"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setPolicyName(" "); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("test. "); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("te st.name"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("testá"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + } + + @Test + public void brmsPolicyCreationTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for BRMS Param Policy. + pep.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + Map> attributes = new HashMap<>(); + Map matching = new HashMap<>(); + matching.put("key", "value"); + attributes.put(AttributeType.MATCHING, matching); + pep.setAttributes(attributes); + pep.setRiskLevel("5"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + // Checks for BRMS Raw Policy + pep.setPolicyConfigType(PolicyConfigType.BRMS_RAW); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel(null); + pep.setConfigBody("package droolsexample\n\n import com.sample.ItemCity;\nimport java.math.BigDecimal;\nrule \"Nagpur Medicine Item\"\n\n when\n item : ItemCity(purchaseCity == ItemCity.City.NAGPUR,\n typeofItem == ItemCity.Type.MEDICINES)\n then\n BigDecimal tax = new BigDecimal(0.0);\n item.setLocalTax(tax.multiply(item.getSellPrice()));\nend"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("5"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void baseConfigTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for Base config Policy. + pep.setPolicyConfigType(PolicyConfigType.Base); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("testbody"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBodyType(PolicyType.OTHER); + pep.setRiskLevel("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("4"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setOnapName("ec nam-e"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setOnapName("onapName"); + pep.setConfigName("tes config"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigName("configName"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + pep.setConfigBody("{'test':'test}"); + pep.setConfigBodyType(PolicyType.JSON); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + Map> attributes = new HashMap<>(); + Map matching = new HashMap<>(); + matching.put("key", "value"); + attributes.put(AttributeType.MATCHING, matching); + pep.setAttributes(attributes); + pep.setConfigBody("testBody"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void closedLoopPolicyTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for Closed loop Policy. + pep.setPolicyConfigType(PolicyConfigType.ClosedLoop_Fault); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("te stá"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("testBody"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"key\":\"value\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"onapname\":\"\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"onapname\":\"test\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + pep.setRiskLevel("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("4"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void closedLoopPMTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for Closed loop Policy. + pep.setPolicyConfigType(PolicyConfigType.ClosedLoop_PM); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("te stá"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("testBody"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"key\":\"value\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"onapname\":\"\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"onapname\":\"test\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"onapname\":\"test\", \"serviceTypePolicyName\":\"value\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + pep.setRiskLevel("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("4"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void firewallPolicyTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for Closed loop Policy. + pep.setPolicyConfigType(PolicyConfigType.Firewall); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("te st"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"test\":\"test\"}"); + pep.setRiskLevel("test"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("4"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"configName\":\"test\"}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void microServicePolicyTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for Closed loop Policy. + pep.setPolicyConfigType(PolicyConfigType.MicroService); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("te st"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{}"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setConfigBody("{\"test\":\"test\"}"); + pep.setOnapName(" "); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setOnapName("testonap"); + pep.setRiskLevel("fail"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setRiskLevel("4"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + pep.setConfigBody("{\"service\":\"test\",\"uuid\":\"test\",\"location\":\"test\",\"configName\":\"test\",\"description\":\"test\",\"priority\":\"test\",\"version\":\"test\"}"); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void actionDecisionPolicyCreationTests() throws Exception{ + PolicyParameters pep = new PolicyParameters(); + pep.setPolicyName("test.name"); + pep.setPolicyDescription("good"); + pep.setTtlDate(new Date()); + pep.setRequestID(UUID.randomUUID()); + setCreateUpdateImpl(); + // Checks for action Policy. + pep.setPolicyClass(PolicyClass.Action); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + Map> attributes = new HashMap<>(); + pep.setAttributes(attributes); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + attributes.put(AttributeType.MATCHING, new HashMap<>()); + pep.setAttributes(attributes); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + Map matching = new HashMap<>(); + matching.put("key", "value"); + attributes.put(AttributeType.MATCHING, matching); + pep.setAttributes(attributes); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setActionAttribute("A1"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setActionPerformer("PEX"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setActionPerformer("PEP"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + // Checks for Decision Policy. + pep.setPolicyClass(PolicyClass.Decision); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setOnapName("xyz"); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + attributes.remove(AttributeType.MATCHING); + attributes.put(AttributeType.SETTINGS, matching); + pep.setAttributes(attributes); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + attributes.put(AttributeType.MATCHING, matching); + pep.setAttributes(attributes); + mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void createUpdateDictionaryTests() throws Exception{ + DictionaryParameters pep = new DictionaryParameters(); + //Failure Tests. + mockMvc.perform(put("/createDictionaryItem")).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + mockMvc.perform(put("/updateDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setDictionaryType(DictionaryType.MicroService); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isBadRequest()); + pep.setDictionary("test dict"); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + pep.setDictionaryJson("{\"test\":\"value\"}"); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID())).andExpect(status().isInternalServerError()); + pep.setDictionaryJson("test123"); + mockMvc.perform(put("/updateDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "123")).andExpect(status().isBadRequest()); + pep.setDictionary("MicroServiceDictionary"); + mockMvc.perform(put("/createDictionaryItem").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isBadRequest()); + } + + @Test + public void getDictionaryTests() throws Exception{ + DictionaryParameters pep = new DictionaryParameters(); + //Failure Tests. + mockMvc.perform(post("/getDictionaryItems")).andExpect(status().isBadRequest()); + mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setDictionaryType(DictionaryType.Common); + mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, UUID.randomUUID().toString())).andExpect(status().isBadRequest()); + pep.setDictionary("OnapName"); + mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + pep.setRequestID(UUID.randomUUID()); + mockMvc.perform(post("/getDictionaryItems").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers)).andExpect(status().isInternalServerError()); + } + + @Test + public void policyEngineImportTests() throws Exception{ + //Failure Tests. + mockMvc.perform(post("/policyEngineImport")).andExpect(status().isBadRequest()); + } + + @Test + public void oldConfigAPITests() throws Exception{ + ConfigPolicyAPIRequest pep = new ConfigPolicyAPIRequest(); + //Failure Tests. + mockMvc.perform(put("/createConfig")).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + mockMvc.perform(put("/updateConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setPolicyScope("test"); + mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setPolicyName("name"); + mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setConfigType("OTHER"); + mockMvc.perform(put("/createConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setTtlDate(new Date().toString()); + mockMvc.perform(put("/updateConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + } + + @Test + public void oldFirewallAPITests() throws Exception{ + ConfigFirewallPolicyAPIRequest pep = new ConfigFirewallPolicyAPIRequest(); + //Failure Tests. + mockMvc.perform(put("/createFirewallConfig")).andExpect(status().isBadRequest()); + mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + mockMvc.perform(put("/updateFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON).header(CLIENTAUTHHEADER, "Basic 123")).andExpect(status().isUnauthorized()); + //Service Tests. + mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setPolicyScope("test"); + mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setPolicyName("name"); + mockMvc.perform(put("/createFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + pep.setTtlDate(new Date().toString()); + mockMvc.perform(put("/updateFirewallConfig").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) + .headers(headers).header(UUIDHEADER, "tes123")).andExpect(status().isBadRequest()); + } + + private void setCreateUpdateImpl() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Method setter = XACMLPdpServlet.class.getDeclaredMethod("setCreateUpdatePolicyConstructor", String.class); + setter.setAccessible(true); + setter.invoke(new XACMLPdpServlet(), CreateUpdatePolicyServiceImpl.class.getName()); + } + + //Health Check Tests + @Test + public void getCountTest() throws Exception { + mockMvc.perform(get("/count")) + .andExpect(status().isOk()); + } +} diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/getConfigTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/getConfigTest.java new file mode 100644 index 000000000..2d79b234a --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/getConfigTest.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.test; + +import static org.junit.Assert.assertEquals; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.junit.Test; +import org.onap.policy.api.ConfigRequestParameters; +import org.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.pdp.rest.api.models.PolicyConfig; +import org.onap.policy.pdp.rest.api.services.GetConfigService; + +public class getConfigTest { + private static final String TEST = "test"; + + @SuppressWarnings("unchecked") + @Test + public void filterMethodTest() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ + ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); + GetConfigService getConfigService= new GetConfigService(configRequestParameters, null); + Method filter = GetConfigService.class.getDeclaredMethod("filterResults", Collection.class,ConfigRequestParameters.class); + filter.setAccessible(true); + List policyConfigs = new LinkedList<>(); + + List filterResults = (List) filter.invoke(getConfigService, policyConfigs,configRequestParameters); + assertEquals(PolicyConfigStatus.CONFIG_NOT_FOUND, filterResults.get(0).getPolicyConfigStatus()); + // Check again with some values + configRequestParameters.setPolicyName(TEST); + configRequestParameters.setOnapName(TEST); + configRequestParameters.setConfigName(TEST); + Map configAttributes = new HashMap<>(); + configAttributes.put(TEST, TEST); + configRequestParameters.setConfigAttributes(configAttributes); + PolicyConfig pConfig = new PolicyConfig(); + pConfig.setPolicyName(TEST); + Map matching = new HashMap<>(); + matching.put("ONAPName", TEST); + matching.put("ConfigName", TEST); + matching.put("TEST", TEST); + pConfig.setMatchingConditions(matching); + policyConfigs.add(pConfig); + filterResults = (List) filter.invoke(getConfigService, policyConfigs,configRequestParameters); + assertEquals(PolicyConfigStatus.CONFIG_NOT_FOUND, filterResults.get(0).getPolicyConfigStatus()); + } +} diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/getDictionaryTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/getDictionaryTest.java new file mode 100644 index 000000000..e18f8bb03 --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/getDictionaryTest.java @@ -0,0 +1,231 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.api.test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.lang.reflect.Method; + +import org.junit.Test; +import org.onap.policy.api.DictionaryParameters; +import org.onap.policy.pdp.rest.api.services.GetDictionaryService; + +public class getDictionaryTest { + + @Test + public void dictionaryJsonTest() throws Exception{ + Method formatDictionary = GetDictionaryService.class.getDeclaredMethod("formatDictionaryJson", String.class); + formatDictionary.setAccessible(true); + String input="{\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\"," + + "\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\"," + + "\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\",\"key\":\"value\"}"; + DictionaryParameters dp = new DictionaryParameters(); + dp.setDictionary("test"); + GetDictionaryService gds = new GetDictionaryService(dp, null); + String result = (String) formatDictionary.invoke(gds, input); + assertNull(result); + // + dp.setDictionary("OnapName"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Attribute"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Action"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("BRMSParamTemplate"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("VSCLAction"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("VNFType"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PEPOptions"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Varbind"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Service"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Site"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Settings"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("DescriptiveScope"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Enforcer"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("ActionList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("ProtocolList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Zone"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("SecurityZone"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PrefixList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("AddressGroup"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("ServiceGroup"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("ServiceList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("TermList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("RuleList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("FirewallRuleList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("Term"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("MicroServiceLocation"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("MicroServiceConfigName"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("DCAEUUID"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("MicroServiceModels"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PolicyScopeService"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PolicyScopeResource"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PolicyScopeType"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("PolicyScopeClosedLoop"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("GroupPolicyScopeList"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("RiskType"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("SafePolicyWarning"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + // + dp.setDictionary("MicroServiceDictionary"); + gds = new GetDictionaryService(dp, null); + result = (String) formatDictionary.invoke(gds, input); + assertNotNull(result); + } +} diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/FilterTests.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/FilterTests.java new file mode 100644 index 000000000..88369850f --- /dev/null +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/auth/test/FilterTests.java @@ -0,0 +1,199 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP-REST + * ================================================================================ + * 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.pdp.rest.auth.test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.pdp.rest.restAuth.PDPAuthenticationFilter; + +import com.att.research.xacml.util.XACMLProperties; +import com.mockrunner.mock.web.MockRequestDispatcher; + +public class FilterTests { + + private PDPAuthenticationFilter authenticationFilter = new PDPAuthenticationFilter(); + private final String VALIDHEADERVALUE = "Basic dGVzdHBkcDphbHBoYTQ1Ng=="; + + @Before + public void setUp() throws Exception{ + authenticationFilter.init(null); + XACMLProperties.reloadProperties(); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/pass.xacml.pdp.properties"); + XACMLProperties.getProperties(); + } + + @Test + public void testDoFilterError() throws IOException, ServletException { + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + when(httpServletRequest.getRequestURI()).thenReturn("error"); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if unauthorized + verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + + @Test + public void testDoFilterNotification() throws IOException, ServletException { + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + when(httpServletRequest.getRequestURI()).thenReturn("notifications"); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + verify(filterChain).doFilter(httpServletRequest,httpServletResponse); + } + + @Test + public void testDoFilterSwagger() throws Exception{ + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/swagger"); + when(httpServletRequest.getRequestDispatcher("/api/swagger")).thenReturn(new MockRequestDispatcher()); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + verify(httpServletRequest).getRequestDispatcher("/api/swagger"); + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api-docs/"); + when(httpServletRequest.getRequestDispatcher("/api/api-docs/")).thenReturn(new MockRequestDispatcher()); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + verify(httpServletRequest).getRequestDispatcher("/api/api-docs/"); + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/configuration"); + when(httpServletRequest.getRequestDispatcher("/api/configuration")).thenReturn(new MockRequestDispatcher()); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + verify(httpServletRequest).getRequestDispatcher("/api/configuration"); + } + + @Test + public void newRequestAuthFailTest() throws Exception{ + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("error"); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if unauthorized + verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + + @Test + public void tokenFailureTest() throws Exception{ + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn("Basic test123"); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if unauthorized + verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + + @Test + public void oldRequestAuthPassTest() throws Exception{ + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // New request no environment header check + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); + when(httpServletRequest.getRequestDispatcher("/api/getConfig")).thenReturn(new MockRequestDispatcher()); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if authorized + verify(httpServletRequest).getRequestDispatcher("/api/getConfig"); + // + // Old Requests Checks + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/getConfig"); + when(httpServletRequest.getRequestDispatcher("/api//getConfig")).thenReturn(new MockRequestDispatcher()); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if authorized + verify(httpServletRequest).getRequestDispatcher("/api//getConfig"); + } + + @Test + public void newRequestAuthPassTest() throws Exception{ + // create the objects to be mocked + HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); + HttpServletResponse httpServletResponse = mock(HttpServletResponse.class); + FilterChain filterChain = mock(FilterChain.class); + // + // Requests with Valid Environment Header values. + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/getConfig"); + when(httpServletRequest.getRequestDispatcher("/api//getConfig")).thenReturn(new MockRequestDispatcher()); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.ENVIRONMENT_HEADER)).thenReturn("DEVL"); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if authorized + verify(httpServletRequest).getRequestDispatcher("/api//getConfig"); + // New request no environment header check + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/api/getConfig"); + when(httpServletRequest.getRequestDispatcher("/api/getConfig")).thenReturn(new MockRequestDispatcher()); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if authorized + verify(httpServletRequest).getRequestDispatcher("/api/getConfig"); + // + // + // Requests with InValid Environment Header + // + when(httpServletRequest.getRequestURI()).thenReturn("/pdp/getConfig"); + when(httpServletRequest.getRequestDispatcher("/api//getConfig")).thenReturn(new MockRequestDispatcher()); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.ENVIRONMENT_HEADER)).thenReturn("TEST"); + when(httpServletRequest.getHeader(PDPAuthenticationFilter.AUTHENTICATION_HEADER)).thenReturn(VALIDHEADERVALUE); + authenticationFilter.doFilter(httpServletRequest, httpServletResponse, + filterChain); + // verify if unauthorized + verify(httpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } +} diff --git a/ECOMP-PDP-REST/src/test/resources/client.properties b/ONAP-PDP-REST/src/test/resources/client.properties similarity index 100% rename from ECOMP-PDP-REST/src/test/resources/client.properties rename to ONAP-PDP-REST/src/test/resources/client.properties diff --git a/ONAP-PDP-REST/src/test/resources/fail.xacml.pdp.properties b/ONAP-PDP-REST/src/test/resources/fail.xacml.pdp.properties new file mode 100644 index 000000000..a16b422bf --- /dev/null +++ b/ONAP-PDP-REST/src/test/resources/fail.xacml.pdp.properties @@ -0,0 +1,171 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP-REST +# ================================================================================ +# 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========================================================= +### + +# Default XACML Properties File for PDP RESTful servlet +# +# Standard API Factories +# +xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory +xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory +xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory +# NOT USED SEE BELOW xacml.pipFinderFactory=org.onap.policy.xacml.std.pip.StdPIPFinderFactory +xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory +# +# AT&T PDP Implementation Factories +# +xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory +xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory +xacml.att.functionDefinitionFactory=org.onap.policy.xacml.custom.OnapFunctionDefinitionFactory +# NOT USED SEE BELOW xacml.att.policyFinderFactory=org.onap.policy.pdp.std.StdPolicyFinderFactory +# creteUpdate Policy Implementation Class details. +createUpdatePolicy.impl.className=org.onap.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl +# AAF Implementation class details +aafClient.impl.className=org.onap.policy.utils.AAFPolicyClientImpl +# +# AT&T RESTful PDP Implementation Factories +# +xacml.pipFinderFactory=org.onap.policy.pdp.rest.impl.XACMLPdpPIPFinderFactory +xacml.att.policyFinderFactory=org.onap.policy.pdp.rest.XACMLPdpPolicyFinderFactory +# +# When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into +# into one PolicySet and use the given Policy Algorithm. +# +xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides +# +# PDP RESTful API properties +# +# Set this to the address where the XACML-PAP-REST servlet is running +xacml.rest.pap.url=http://localhost:8070/pap/ + +#if multiple paps exist, the xacml.rest.pap.url can be removed and they can be defined like this: +#xacml.rest.pap.urls=http://localhost:9090/pap/,http://localhost:9091/pap/ + +# +# Give the running PDP an ID for the PAP. The url that its running as is a good choice. +# The PAP identifies PDP's using the URL of the PDP. +# +xacml.rest.pdp.id=http://localhost:8082/pdp/ + +# Give the port number used for the PDP + +xacml.jmx.port=0 + + +# Notification Properties +# Notifcation type: websocket, ueb or dmaap... if left blank websocket is the default +NOTIFICATION_TYPE=websocket +NOTIFICATION_SERVERS= +NOTIFICATION_TOPIC= +NOTIFICATION_DELAY=500 +UEB_API_KEY= +UEB_API_SECRET= +DMAAP_AAF_LOGIN=test +DMAAP_AAF_PASSWORD=test + +# +# Set the directory where the PDP holds its Policy Cache and PIP Configuration +# +xacml.rest.pdp.config=config + +xacml.rest.pdp.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ +# +# Initialize register with PAP servlet +# +xacml.rest.pdp.register=true +# +# Sleep period in seconds between register attempts +# +xacml.rest.pdp.register.sleep=15 +# +# number of attempts to register. -1 means keep trying forever. +# +xacml.rest.pdp.register.retries=-1 +# +# max number of bytes in a POST of a XML/JSON request +# old value #32767 +xacml.rest.pdp.maxcontent=99999999 +# +# Set UserID here +xacml.rest.pdp.userid=testpdp +# Set Password here +xacml.rest.pdp.password=alpha456 + +# id PAP +xacml.rest.pap.userid=testpap +#if multiple paps have different logins, they can be defined like this: +#http\://localhost\:9090/pap/.xacml.rest.pap.userid=testpap + +# pass PAP +xacml.rest.pap.password=alpha123 +#http\://localhost\:9090/pap/.xacml.rest.pap.password=alpha123 + +# Delay for Notifications Don't change this. Value in milliSec. +xacml.rest.notification.delay=30 +# Buffer Size. +REQUEST_BUFFER_SIZE=15 + +#properties for MySql xacml database: PLEASE DO NOT REMOVE... NEEDED FOR APIs +javax.persistence.jdbc.driver=com.mysql.jdbc.Driver +javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/xacml +javax.persistence.jdbc.user=policy_user +javax.persistence.jdbc.password=policy_user + + +#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java*** + +#The name of the PDP. Must be unique across the system +xacml.rest.pdp.resource.name=site_1.pdp_1 + +#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** + +#Interval between forward progress counter updates in seconds +fp_monitor_interval=30 + +#Number of forward progress counter failures before failover +failed_counter_threshold=3 + +#Interval in seconds between test transactions if there is no other traffic +test_trans_interval=10 + +#Interval in seconds between updates of the forward progress counter in the DB +write_fpc_interval=5 + +#Name of the site +site_name=site_1 + +#Node type +node_type=pdp_xacml + +#Dependency groups are groups of resources upon which a node operational state is dependent upon). +#Each group is a comma-separated list of resource names and groups are separated by a semicolon. +#A group may contain one or more members. Resource names must match the resource names defined +#in the respective servers' properties files +dependency_groups=site_1.pdplp_1;site_1.astragw_1;site_1.brmsgw_1 + +# this can be DEVL, TEST, PROD +ENVIRONMENT=DEVL +xacml.rest.pep.idfile = src/test/resources/client.properties + +#AAF Policy Name space +#Not Mandatory for Open Onap +policy.aaf.namespace = +policy.aaf.resource = +# +DMAAP_AAF_LOGIN = diff --git a/ONAP-PDP-REST/src/test/resources/pass.xacml.pdp.properties b/ONAP-PDP-REST/src/test/resources/pass.xacml.pdp.properties new file mode 100644 index 000000000..c9a111012 --- /dev/null +++ b/ONAP-PDP-REST/src/test/resources/pass.xacml.pdp.properties @@ -0,0 +1,171 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP-REST +# ================================================================================ +# 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========================================================= +### + +# Default XACML Properties File for PDP RESTful servlet +# +# Standard API Factories +# +xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory +xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory +xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory +# NOT USED SEE BELOW xacml.pipFinderFactory=org.onap.policy.xacml.std.pip.StdPIPFinderFactory +xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory +# +# AT&T PDP Implementation Factories +# +xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory +xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory +xacml.att.functionDefinitionFactory=org.onap.policy.xacml.custom.OnapFunctionDefinitionFactory +# NOT USED SEE BELOW xacml.att.policyFinderFactory=org.onap.policy.pdp.std.StdPolicyFinderFactory +# creteUpdate Policy Implementation Class details. +createUpdatePolicy.impl.className=org.onap.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl +# AAF Implementation class details +aafClient.impl.className=org.onap.policy.utils.AAFPolicyClientImpl +# +# AT&T RESTful PDP Implementation Factories +# +xacml.pipFinderFactory=org.onap.policy.pdp.rest.impl.XACMLPdpPIPFinderFactory +xacml.att.policyFinderFactory=org.onap.policy.pdp.rest.XACMLPdpPolicyFinderFactory +# +# When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into +# into one PolicySet and use the given Policy Algorithm. +# +xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides +# +# PDP RESTful API properties +# +# Set this to the address where the XACML-PAP-REST servlet is running +xacml.rest.pap.url=http://localhost:8070/pap/ + +#if multiple paps exist, the xacml.rest.pap.url can be removed and they can be defined like this: +#xacml.rest.pap.urls=http://localhost:9090/pap/,http://localhost:9091/pap/ + +# +# Give the running PDP an ID for the PAP. The url that its running as is a good choice. +# The PAP identifies PDP's using the URL of the PDP. +# +xacml.rest.pdp.id=http://localhost:8082/pdp/ + +# Give the port number used for the PDP + +xacml.jmx.port=0 + + +# Notification Properties +# Notifcation type: websocket, ueb or dmaap... if left blank websocket is the default +NOTIFICATION_TYPE=websocket +NOTIFICATION_SERVERS=test +NOTIFICATION_TOPIC=test +NOTIFICATION_DELAY=500 +UEB_API_KEY= +UEB_API_SECRET= +DMAAP_AAF_LOGIN=test +DMAAP_AAF_PASSWORD=test + +# +# Set the directory where the PDP holds its Policy Cache and PIP Configuration +# +xacml.rest.pdp.config=config + +xacml.rest.pdp.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ +# +# Initialize register with PAP servlet +# +xacml.rest.pdp.register=true +# +# Sleep period in seconds between register attempts +# +xacml.rest.pdp.register.sleep=15 +# +# number of attempts to register. -1 means keep trying forever. +# +xacml.rest.pdp.register.retries=-1 +# +# max number of bytes in a POST of a XML/JSON request +# old value #32767 +xacml.rest.pdp.maxcontent=99999999 +# +# Set UserID here +xacml.rest.pdp.userid=testpdp +# Set Password here +xacml.rest.pdp.password=alpha456 + +# id PAP +xacml.rest.pap.userid=testpap +#if multiple paps have different logins, they can be defined like this: +#http\://localhost\:9090/pap/.xacml.rest.pap.userid=testpap + +# pass PAP +xacml.rest.pap.password=alpha123 +#http\://localhost\:9090/pap/.xacml.rest.pap.password=alpha123 + +# Delay for Notifications Don't change this. Value in milliSec. +xacml.rest.notification.delay=30 +# Buffer Size. +REQUEST_BUFFER_SIZE=15 + +#properties for MySql xacml database: PLEASE DO NOT REMOVE... NEEDED FOR APIs +javax.persistence.jdbc.driver=com.mysql.jdbc.Driver +javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/xacml +javax.persistence.jdbc.user=policy_user +javax.persistence.jdbc.password=policy_user + + +#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java*** + +#The name of the PDP. Must be unique across the system +xacml.rest.pdp.resource.name=site_1.pdp_1 + +#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** + +#Interval between forward progress counter updates in seconds +fp_monitor_interval=30 + +#Number of forward progress counter failures before failover +failed_counter_threshold=3 + +#Interval in seconds between test transactions if there is no other traffic +test_trans_interval=10 + +#Interval in seconds between updates of the forward progress counter in the DB +write_fpc_interval=5 + +#Name of the site +site_name=site_1 + +#Node type +node_type=pdp_xacml + +#Dependency groups are groups of resources upon which a node operational state is dependent upon). +#Each group is a comma-separated list of resource names and groups are separated by a semicolon. +#A group may contain one or more members. Resource names must match the resource names defined +#in the respective servers' properties files +dependency_groups=site_1.pdplp_1;site_1.astragw_1;site_1.brmsgw_1 + +# this can be DEVL, TEST, PROD +ENVIRONMENT=DEVL +xacml.rest.pep.idfile = src/test/resources/client.properties + +#AAF Policy Name space +#Not Mandatory for Open Onap +policy.aaf.namespace = +policy.aaf.resource = +# +DMAAP_AAF_LOGIN = diff --git a/ONAP-PDP-REST/src/test/resources/test.drl b/ONAP-PDP-REST/src/test/resources/test.drl new file mode 100644 index 000000000..7accc63ae --- /dev/null +++ b/ONAP-PDP-REST/src/test/resources/test.drl @@ -0,0 +1,1121 @@ +/*- + * ============LICENSE_START======================================================= + * archetype-closed-loop-demo-rules + * ================================================================================ + * 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.controlloop; + +import java.util.List; +import java.util.LinkedList; +import java.util.Map; +import java.util.HashMap; +import java.util.UUID; + +import org.onap.policy.controlloop.VirtualControlLoopEvent; +import org.onap.policy.controlloop.ControlLoopEventStatus; +import org.onap.policy.controlloop.VirtualControlLoopNotification; +import org.onap.policy.controlloop.ControlLoopNotificationType; +import org.onap.policy.controlloop.ControlLoopOperation; +import org.onap.policy.controlloop.ControlLoopOperationWrapper; +import org.onap.policy.template.demo.ControlLoopException; + +import org.onap.policy.aai.AAINQF199.AAINQF199CloudRegion; +import org.onap.policy.aai.AAINQF199.AAINQF199ExtraProperties; +import org.onap.policy.aai.AAINQF199.AAINQF199ExtraProperty; +import org.onap.policy.aai.AAINQF199.AAINQF199GenericVNF; +import org.onap.policy.aai.AAINQF199.AAINQF199InstanceFilters; +import org.onap.policy.aai.AAINQF199.AAINQF199InventoryResponseItem; +import org.onap.policy.aai.AAINQF199.AAINQF199InventoryResponseItems; +import org.onap.policy.aai.AAINQF199.AAINQF199Manager; +import org.onap.policy.aai.AAINQF199.AAINQF199NamedQuery; +import org.onap.policy.aai.AAINQF199.AAINQF199QueryParameters; +import org.onap.policy.aai.AAINQF199.AAINQF199Request; +import org.onap.policy.aai.AAINQF199.AAINQF199RequestWrapper; +import org.onap.policy.aai.AAINQF199.AAINQF199Response; +import org.onap.policy.aai.AAINQF199.AAINQF199ResponseWrapper; +import org.onap.policy.aai.AAINQF199.AAINQF199ServiceInstance; +import org.onap.policy.aai.AAINQF199.AAINQF199Tenant; +import org.onap.policy.aai.AAINQF199.AAINQF199VfModule; +import org.onap.policy.aai.AAINQF199.AAINQF199VServer; +import org.onap.policy.aai.util.Serialization; + +import org.onap.policy.appc.CommonHeader; +import org.onap.policy.appc.Request; +import org.onap.policy.appc.Response; +import org.onap.policy.appc.ResponseCode; +import org.onap.policy.appc.ResponseStatus; +import org.onap.policy.appc.ResponseValue; + +import org.onap.policy.template.demo.EventManager; +import org.onap.policy.vnf.trafficgenerator.PGRequest; +import org.onap.policy.vnf.trafficgenerator.PGStream; +import org.onap.policy.vnf.trafficgenerator.PGStreams; + +import org.onap.policy.mso.MSOManager; +import org.onap.policy.mso.MSORequest; +import org.onap.policy.mso.MSORequestStatus; +import org.onap.policy.mso.MSORequestDetails; +import org.onap.policy.mso.MSOModelInfo; +import org.onap.policy.mso.MSOCloudConfiguration; +import org.onap.policy.mso.MSORequestInfo; +import org.onap.policy.mso.MSORequestParameters; +import org.onap.policy.mso.MSORelatedInstanceListElement; +import org.onap.policy.mso.MSORelatedInstance; +import org.onap.policy.mso.MSOResponse; + +import org.onap.policy.drools.system.PolicyEngine; + +// +// These parameters are required to build the runtime policy +// +declare Params + closedLoopControlName : String + actor : String + aaiURL : String + aaiUsername : String + aaiPassword : String + msoURL : String + msoUsername : String + msoPassword : String + aaiNamedQueryUUID : String + aaiPatternMatch : int + notificationTopic : String + appcTopic : String +end + +/* +* +* Called once and only once to insert the parameters into working memory for this Closed Loop policy. +* (Comment SETUP rule out for the first ONAP opensource release since policy BRMS_GW already puts a Params fact in there) +* +* +*rule "${policyName}.SETUP" +* when +* then +* System.out.println("rule SETUP is triggered."); +* Params params = new Params(); +* params.setClosedLoopControlName("${closedLoopControlName}"); +* params.setActor("${actor}"); +* params.setAaiURL("${aaiURL}"); +* params.setAaiUsername("${aaiUsername}"); +* params.setAaiPassword("${aaiPassword}"); +* params.setMsoURL("${msoURL}"); +* params.setMsoUsername("${msoUsername}"); +* params.setMsoPassword("${msoPassword}"); +* params.setAaiNamedQueryUUID("${aaiNamedQueryUUID}"); +* params.setAaiPatternMatch(${aaiPatternMatch}); +* params.setNotificationTopic("${notificationTopic}"); +* params.setAppcTopic("${appcTopic}"); +* // +* // This stays in memory as long as the rule is alive and running +* // +* insert(params); +*end +*/ +/* +* +* This rule responds to DCAE Events +* +*/ +rule "${policyName}.EVENT" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + not ( EventManager( closedLoopControlName == $event.closedLoopControlName )) + then + System.out.println("rule EVENT is triggered."); + try { + // + // Check the requestID in the event to make sure it is not null before we create the EventManager. + // The EventManager will do extra syntax checking as well check if the closed loop is disabled/ + // + if ($event.requestID == null) { + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.from = "policy"; + notification.message = "Missing requestID from DCAE event"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver notification: " + notification); + } + // + // Retract it from memory + // + retract($event); + System.out.println("Event with requestID=null has been retracted."); + } else { + // + // Create an EventManager + // + EventManager manager = new EventManager($params.getClosedLoopControlName(), $event.requestID, $event.target); + // + // Determine if EventManager can actively process the event (i.e. syntax) + // + VirtualControlLoopNotification notification = manager.activate($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // Are we actively pursuing this event? + // + if (notification.notification == ControlLoopNotificationType.ACTIVE) { + // + // Insert Event Manager into memory, this will now kick off processing. + // + insert(manager); + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver notification: " + notification); + } + } else { + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver notification: " + notification); + } + // + // Retract it from memory + // + retract($event); + } + // + // Now that the manager is inserted into Drools working memory, we'll wait for + // another rule to fire in order to continue processing. This way we can also + // then screen for additional ONSET and ABATED events for this same RequestIDs + // and for different RequestIDs but with the same closedLoopControlName and target. + // + } + // + } catch (Exception e) { + e.printStackTrace(); + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + // + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e1) { + System.out.println("Can't deliver notification: " + notification); + e1.printStackTrace(); + } + // + // Retract the event + // + retract($event); + } +end + +/* +* +* This rule happens when we got a valid ONSET, closed loop is enabled and an Event Manager +* is created. We can start the operations for this closed loop. +* +*/ +rule "${policyName}.EVENT.MANAGER" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : EventManager( closedLoopControlName == $event.closedLoopControlName, controlLoopResult == null) + then + System.out.println("rule EVENT.MANAGER is triggered."); + // + // Check which event this is. + // + EventManager.NEW_EVENT_STATUS eventStatus = $manager.onNewEvent($event); + // + // We only want the initial ONSET event in memory, + // all the other events need to be retracted to support + // cleanup and avoid the other rules being fired for this event. + // + if (eventStatus != EventManager.NEW_EVENT_STATUS.FIRST_ONSET) { + System.out.println("Retracting "+eventStatus+" Event."); + retract($event); + return; + } + // + // Now the event in memory is first onset event + // + try { + // + // Pull the known AAI field from the Event + // + // generic-vnf is needed for vFirewall case + // vserver-name is needed for vLoadBalancer case + // + String genericVNF = $event.AAI.get("generic-vnf.vnf-id"); + String vserver = $event.AAI.get("vserver.vserver-name"); + // + // Check if we are implementing a simple pattern match. + // + if ($params.getAaiPatternMatch() == 1) { + // + // Yes + // + //Basic naming characteristics: + //VF Name (9 char)+VM name (13 char total)+VFC (19 char total) + //Example: + //VF Name (9 characters): cscf0001v + //VM Name(13 characters): cscf0001vm001 + //VFC name(19 characters): cscf0001vm001cfg001 + // + // zdfw1fwl01fwl02 or zdfw1fwl01fwl01 + // replaced with + // zdfw1fwl01pgn02 or zdfw1fwl01pgn01 + // + int index = genericVNF.lastIndexOf("fwl"); + if (index == -1) { + System.err.println("The generic-vnf.vnf-id from DCAE Event is not valid."); + } else { + genericVNF = genericVNF.substring(0, index) + "pgn" + genericVNF.substring(index+"fwl".length()); + } + // + // Construct an APPC request + // + ControlLoopOperation operation = new ControlLoopOperation(); + operation.actor = $params.getActor(); + operation.operation = "ModifyConfig"; + operation.target = $event.target; + // + // Create operationWrapper + // + ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); + // + // insert operationWrapper into memory + // + insert(operationWrapper); + // + Request request = new Request(); + request.CommonHeader = new CommonHeader(); + request.CommonHeader.RequestID = $event.requestID; + request.Action = operation.operation; + request.Payload = new HashMap(); + // + // Fill in the payload + // + request.Payload.put("generic-vnf.vnf-id", genericVNF); + // + PGRequest pgRequest = new PGRequest(); + pgRequest.pgStreams = new PGStreams(); + + PGStream pgStream; + for(int i = 0; i < 5; i++){ + pgStream = new PGStream(); + pgStream.streamId = "fw_udp"+(i+1); + pgStream.isEnabled = "true"; + pgRequest.pgStreams.pgStream.add(pgStream); + } + request.Payload.put("pg-streams", pgRequest.pgStreams); + + if (request != null) { + // + // Insert request into memory + // + insert(request); + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + // message and history ?? + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Now send the operation request + // + if (request instanceof Request) { + try { + System.out.println("APPC request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + PolicyEngine.manager.deliver($params.getAppcTopic(), request); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver request: " + request); + } + } + } else { + // + // what happens if it is null + // + } + // + } else { + // + // create AAI named-query request with UUID started with "F199" + // + AAINQF199Request aainqf199request = new AAINQF199Request(); + AAINQF199QueryParameters aainqf199queryparam = new AAINQF199QueryParameters(); + AAINQF199NamedQuery aainqf199namedquery = new AAINQF199NamedQuery(); + AAINQF199InstanceFilters aainqf199instancefilter = new AAINQF199InstanceFilters(); + // + // queryParameters + // + aainqf199namedquery.namedQueryUUID = UUID.fromString($params.getAaiNamedQueryUUID()); + aainqf199queryparam.namedQuery = aainqf199namedquery; + aainqf199request.queryParameters = aainqf199queryparam; + // + // instanceFilters + // + Map aainqf199instancefiltermap = new HashMap(); + Map aainqf199instancefiltermapitem = new HashMap(); + aainqf199instancefiltermapitem.put("vserver-name", vserver); + aainqf199instancefiltermap.put("vserver", aainqf199instancefiltermapitem); + aainqf199instancefilter.instanceFilter.add(aainqf199instancefiltermap); + aainqf199request.instanceFilters = aainqf199instancefilter; + // + // print aainqf199request for debug + // + System.out.println("AAI Request sent:"); + System.out.println(Serialization.gsonPretty.toJson(aainqf199request)); + // + // Create AAINQF199RequestWrapper + // + AAINQF199RequestWrapper aainqf199RequestWrapper = new AAINQF199RequestWrapper($event.requestID, aainqf199request); + // + // insert aainqf199request into memory + // + insert(aainqf199RequestWrapper); + } + // + } catch (Exception e) { + e.printStackTrace(); + } +end + +/* +* +* This rule happens when we got a valid ONSET, closed loop is enabled, an Event Manager +* is created, AAI Manager and AAI Request are ready in memory. We can start sending query to AAI and then wait for response. +* +*/ +rule "${policyName}.EVENT.MANAGER.AAINQF199REQUEST" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) + $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID) + then + System.out.println("rule EVENT.MANAGER.AAINQF199REQUEST is triggered."); + // + // send the request + // + AAINQF199Response aainqf199response = AAINQF199Manager.postQuery($params.getAaiURL(), $params.getAaiUsername(), $params.getAaiPassword(), + $aainqf199RequestWrapper.aainqf199request, $event.requestID); + // + // Check AAI response + // + if (aainqf199response == null) { + System.err.println("Failed to get AAI response"); + // + // Fail and retract everything + // + retract($event); + retract($manager); + retract($aainqf199RequestWrapper); + } else { + // + // Create AAINQF199ResponseWrapper + // + AAINQF199ResponseWrapper aainqf199ResponseWrapper = new AAINQF199ResponseWrapper($event.requestID, aainqf199response); + // + // insert aainqf199ResponseWrapper to memeory + // + insert(aainqf199ResponseWrapper); + } +end + +/* +* +* This rule happens when we got a valid AAI response. We can start sending request to APPC or MSO now. +* +*/ +rule "${policyName}.EVENT.MANAGER.AAINQF199RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) + $aainqf199RequestWrapper : AAINQF199RequestWrapper(requestID == $event.requestID) + $aainqf199ResponseWrapper : AAINQF199ResponseWrapper(requestID == $event.requestID) + then + System.out.println("rule EVENT.MANAGER.AAINQF199RESPONSE is triggered."); + // + // Extract related fields out of AAINQF199RESPONSE + // + String vnfItemVnfId, vnfItemVnfType, vnfItemPersonaModelId, vnfItemPersonaModelVersion, vnfItemModelName, + vnfItemModelVersion, vnfItemModelNameVersionId, serviceItemServiceInstanceId, serviceItemPersonaModelId, + serviceItemModelName, serviceItemModelType, serviceItemModelVersion, serviceItemModelNameVersionId, + vfModuleItemVfModuleName, vfModuleItemPersonaModelId, vfModuleItemPersonaModelVersion, vfModuleItemModelName, + vfModuleItemModelNameVersionId, tenantItemTenantId, cloudRegionItemCloudRegionId; + try { + // + // vnfItem + // + vnfItemVnfId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfID; + vnfItemVnfType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.vnfType; + vnfItemVnfType = vnfItemVnfType.substring(vnfItemVnfType.lastIndexOf("/")+1); + vnfItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelId; + vnfItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).genericVNF.personaModelVersion; + vnfItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue; + vnfItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(2).propertyValue; + vnfItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue; + // + // serviceItem + // + serviceItemServiceInstanceId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.serviceInstanceID; + serviceItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelId; + serviceItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(0).propertyValue; + serviceItemModelType = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(1).propertyValue; + serviceItemModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).serviceInstance.personaModelVersion; + serviceItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).extraProperties.extraProperty.get(4).propertyValue; + // + // Find the index for base vf module and non-base vf module + // + int baseIndex = -1; + int nonBaseIndex = -1; + List inventoryItems = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems; + for (AAINQF199InventoryResponseItem m : inventoryItems) { + if (m.vfModule != null && m.vfModule.isBaseVfModule == true) { + baseIndex = inventoryItems.indexOf(m); + } else if (m.vfModule != null && m.vfModule.isBaseVfModule == false && m.vfModule.orchestrationStatus == null) { + nonBaseIndex = inventoryItems.indexOf(m); + } + // + if (baseIndex != -1 && nonBaseIndex != -1) { + break; + } + } + // + // Report the error if either base vf module or non-base vf module is not found + // + if (baseIndex == -1 || nonBaseIndex == -1) { + System.err.println("Either base or non-base vf module is not found from AAI response."); + retract($aainqf199RequestWrapper); + retract($aainqf199ResponseWrapper); + retract($manager); + retract($event); + return; + } + // + // This comes from the base module + // + vfModuleItemVfModuleName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(baseIndex).vfModule.vfModuleName; + vfModuleItemVfModuleName = vfModuleItemVfModuleName.replace("Vfmodule", "vDNS"); + // + // vfModuleItem - NOT the base module + // + vfModuleItemPersonaModelId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelId; + vfModuleItemPersonaModelVersion = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).vfModule.personaModelVersion; + vfModuleItemModelName = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(0).propertyValue; + vfModuleItemModelNameVersionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(0).items.inventoryResponseItems.get(nonBaseIndex).extraProperties.extraProperty.get(4).propertyValue; + // + // tenantItem + // + tenantItemTenantId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).tenant.tenantId; + // + // cloudRegionItem + // + cloudRegionItemCloudRegionId = $aainqf199ResponseWrapper.aainqf199response.inventoryResponseItems.get(0).items.inventoryResponseItems.get(1).items.inventoryResponseItems.get(0).cloudRegion.cloudRegionId; + // + } catch (Exception e) { + e.printStackTrace(); + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.REJECTED; + notification.message = "Exception occurred " + e.getMessage(); + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e1) { + System.out.println("Can't deliver notification: " + notification); + e1.printStackTrace(); + } + // + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + notification.message = "Invalid named-query response from AAI"; + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e1) { + System.out.println("Can't deliver notification: " + notification); + e1.printStackTrace(); + } + // + // Retract everything + // + retract($aainqf199RequestWrapper); + retract($aainqf199ResponseWrapper); + retract($manager); + retract($event); + return; + } + // + // Extracted fields should not be null + // + if ((vnfItemVnfId == null) || (vnfItemVnfType == null) || + (vnfItemPersonaModelId == null) || (vnfItemModelName == null) || + (vnfItemModelVersion == null) || (vnfItemModelNameVersionId == null) || + (serviceItemServiceInstanceId == null) || (serviceItemModelName == null) || + (serviceItemModelType == null) || (serviceItemModelVersion == null) || + (serviceItemModelNameVersionId == null) || (vfModuleItemVfModuleName == null) || + (vfModuleItemPersonaModelId == null) || (vfModuleItemPersonaModelVersion == null) || + (vfModuleItemModelName == null) || (vfModuleItemModelNameVersionId == null) || + (tenantItemTenantId == null) || (cloudRegionItemCloudRegionId == null)) { + // + System.err.println("some fields are missing from AAI response."); + // + // Fail and retract everything + // + retract($aainqf199RequestWrapper); + retract($aainqf199ResponseWrapper); + retract($manager); + retract($event); + return; + } + // + // We don't need them any more + // + retract($aainqf199ResponseWrapper); + retract($aainqf199RequestWrapper); + // + // check the actor of this closed loop + // + switch ($params.getActor()) { + case "APPC": + { + // + // Construct an APPC request + // + ControlLoopOperation operation = new ControlLoopOperation(); + operation.actor = $params.getActor(); + operation.operation = "ModifyConfig"; + operation.target = $event.target; + // + // Create operationWrapper + // + ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); + // + // insert operationWrapper into memory + // + insert(operationWrapper); + // + Request request = new Request(); + request.CommonHeader = new CommonHeader(); + request.CommonHeader.RequestID = $event.requestID; + request.Action = operation.operation; + request.Payload = new HashMap(); + // + // Fill in the payload + // Hardcode genericVNF for now since AAI has not been ready for vFirewall demo case + // + String genericVNF = "zdfw1fwl01pgn02"; + request.Payload.put("generic-vnf.vnf-id", genericVNF); + // + PGRequest pgRequest = new PGRequest(); + pgRequest.pgStreams = new PGStreams(); + + PGStream pgStream; + for(int i = 0; i < 5; i++){ + pgStream = new PGStream(); + pgStream.streamId = "fw_udp"+(i+1); + pgStream.isEnabled = "true"; + pgRequest.pgStreams.pgStream.add(pgStream); + } + request.Payload.put("pg-streams", pgRequest.pgStreams); + + if (request != null) { + // + // Insert request into memory + // + insert(request); + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + // message and history ?? + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Now send the operation request + // + if (request instanceof Request) { + try { + System.out.println("APPC request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + PolicyEngine.manager.deliver($params.getAppcTopic(), request); + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Can't deliver request: " + request); + } + } + } else { + // + // what happens if it is null + // + } + } + break; + case "MSO": + { + // + // Construct an operation + // + ControlLoopOperation operation = new ControlLoopOperation(); + operation.actor = $params.getActor(); + operation.operation = "createModuleInstance"; + operation.target = $event.target; + // + // Create operationWrapper + // + ControlLoopOperationWrapper operationWrapper = new ControlLoopOperationWrapper($event.requestID, operation); + // + // Construct an MSO request + // + MSORequest request = new MSORequest(); + request.requestDetails = new MSORequestDetails(); + request.requestDetails.modelInfo = new MSOModelInfo(); + request.requestDetails.cloudConfiguration = new MSOCloudConfiguration(); + request.requestDetails.requestInfo = new MSORequestInfo(); + request.requestDetails.requestParameters = new MSORequestParameters(); + request.requestDetails.requestParameters.userParams = null; + // + // cloudConfiguration + // + request.requestDetails.cloudConfiguration.lcpCloudRegionId = cloudRegionItemCloudRegionId; + request.requestDetails.cloudConfiguration.tenantId = tenantItemTenantId; + // + // modelInfo + // + request.requestDetails.modelInfo.modelType = "vfModule"; + request.requestDetails.modelInfo.modelInvariantId = vfModuleItemPersonaModelId; + request.requestDetails.modelInfo.modelNameVersionId = vfModuleItemModelNameVersionId; + request.requestDetails.modelInfo.modelName = vfModuleItemModelName; + request.requestDetails.modelInfo.modelVersion = vfModuleItemPersonaModelVersion; + // + // requestInfo + // + request.requestDetails.requestInfo.instanceName = vfModuleItemVfModuleName; + request.requestDetails.requestInfo.source = "POLICY"; + request.requestDetails.requestInfo.suppressRollback = false; + // + // relatedInstanceList + // + MSORelatedInstanceListElement relatedInstanceListElement1 = new MSORelatedInstanceListElement(); + MSORelatedInstanceListElement relatedInstanceListElement2 = new MSORelatedInstanceListElement(); + relatedInstanceListElement1.relatedInstance = new MSORelatedInstance(); + relatedInstanceListElement2.relatedInstance = new MSORelatedInstance(); + // + relatedInstanceListElement1.relatedInstance.instanceId = serviceItemServiceInstanceId; + relatedInstanceListElement1.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement1.relatedInstance.modelInfo.modelType = "service"; + relatedInstanceListElement1.relatedInstance.modelInfo.modelInvariantId = serviceItemPersonaModelId; + relatedInstanceListElement1.relatedInstance.modelInfo.modelNameVersionId = serviceItemModelNameVersionId; + relatedInstanceListElement1.relatedInstance.modelInfo.modelName = serviceItemModelName; + relatedInstanceListElement1.relatedInstance.modelInfo.modelVersion = serviceItemModelVersion; + // + relatedInstanceListElement2.relatedInstance.instanceId = vnfItemVnfId; + relatedInstanceListElement2.relatedInstance.modelInfo = new MSOModelInfo(); + relatedInstanceListElement2.relatedInstance.modelInfo.modelType = "vnf"; + relatedInstanceListElement2.relatedInstance.modelInfo.modelInvariantId = vnfItemPersonaModelId; + relatedInstanceListElement2.relatedInstance.modelInfo.modelNameVersionId = vnfItemModelNameVersionId; + relatedInstanceListElement2.relatedInstance.modelInfo.modelName = vnfItemModelName; + relatedInstanceListElement2.relatedInstance.modelInfo.modelVersion = vnfItemModelVersion; + relatedInstanceListElement2.relatedInstance.modelInfo.modelCustomizationName = vnfItemVnfType; + // + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement1); + request.requestDetails.relatedInstanceList.add(relatedInstanceListElement2); + // + // print MSO request for debug + // + System.out.println("MSO request sent:"); + System.out.println(Serialization.gsonPretty.toJson(request)); + // + // + // + if (request != null) { + // + // Tell interested parties we are performing this Operation + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.notification = ControlLoopNotificationType.OPERATION; + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Concatenate serviceItemServiceInstanceId and vnfItemVnfId to msoURL + // + String MSOUrl = $params.getMsoURL() + "/serviceInstances/v2/" + serviceItemServiceInstanceId + "/vnfs/" + vnfItemVnfId + "/vfModules"; + // + // Call MSO + // + MSOResponse response = MSOManager.createModuleInstance(MSOUrl, $params.getMsoURL(), $params.getMsoUsername(), $params.getMsoPassword(), request); + // + if (response != null) { + // + // Assign requestId + // + request.requestId = $event.requestID.toString(); + response.request.requestId = $event.requestID.toString(); + // + // Insert facts + // + insert(operationWrapper); + insert(request); + insert(response); + } else { + // + // MSO request not even accepted + // + notification.message = operationWrapper.operation.toMessage(); + operationWrapper.operation.message = operationWrapper.operation.toMessage(); + operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + notification.history.add(operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // Retract everything + // + retract($event); + retract($manager); + } + } else { + System.err.println("constructed MSO request is invalid."); + } + } + break; + } +end + +/* +* +* This rule responds to APPC Response Events +* +*/ +rule "${policyName}.APPC.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) + $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID ) + $request : Request( getCommonHeader().RequestID == $event.requestID ) + $response : Response( getCommonHeader().RequestID == $event.requestID ) + then + System.out.println("rule APPC.RESPONSE is triggered."); + if ($response.Status == null) { + $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + } + // + // Get the Response Code + // + ResponseCode code = ResponseCode.toResponseCode($response.Status.Code); + if (code == null) { + $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + } + // + // Construct notification + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.message = $operationWrapper.operation.toMessage(); + $operationWrapper.operation.message = $operationWrapper.operation.toMessage(); + // + // Ok, let's figure out what APP-C's response is + // + switch (code) { + case ACCEPT: + $operationWrapper.operation.outcome = "PROCESSING"; + break; + case ERROR: + case REJECT: + $operationWrapper.operation.outcome = "FAILURE_EXCEPTION"; + $manager.setControlLoopResult("FAILURE_EXCEPTION"); + break; + case SUCCESS: + $operationWrapper.operation.outcome = "SUCCESS"; + $manager.setControlLoopResult("SUCCESS"); + break; + case FAILURE: + $operationWrapper.operation.outcome = "FAILURE"; + $manager.setControlLoopResult("FAILURE"); + break; + } + if ($operationWrapper.operation.outcome.equals("SUCCESS")) { + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_SUCCESS; + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } else if ($operationWrapper.operation.outcome.equals("PROCESSING")) { + retract($response); + } else { + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } + +end + +/* +* +* This rule is used to clean up APPC response +* +*/ +rule "${policyName}.APPC.RESPONSE.CLEANUP" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $response : Response($id : getCommonHeader().RequestID ) + not ( VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), requestID == $id, closedLoopEventStatus == ControlLoopEventStatus.ONSET ) ) + then + System.out.println("rule APPC.RESPONSE.CLEANUP is triggered."); + retract($response); +end + +/* +* +* This rule responds to MSO Response Events +* +*/ +rule "${policyName}.MSO.RESPONSE" + when + $params : Params( getClosedLoopControlName() == "${closedLoopControlName}" ) + $event : VirtualControlLoopEvent( closedLoopControlName == $params.getClosedLoopControlName(), closedLoopEventStatus == ControlLoopEventStatus.ONSET ) + $manager : EventManager( closedLoopControlName == $event.closedLoopControlName ) + $operationWrapper : ControlLoopOperationWrapper( requestID == $event.requestID ) + $request : MSORequest( requestId == $event.requestID.toString() ) + $response : MSOResponse( request.requestId == $event.requestID.toString() ) + then + System.out.println("rule MSO.RESPONSE is triggered."); + // + // Construct notification + // + VirtualControlLoopNotification notification = new VirtualControlLoopNotification($event); + notification.from = "policy"; + notification.policyName = drools.getRule().getName(); + notification.policyScope = "${policyScope}"; + notification.policyVersion = "${policyVersion}"; + notification.message = $operationWrapper.operation.toMessage(); + $operationWrapper.operation.message = $operationWrapper.operation.toMessage(); + // + // The operation can either be succeeded or failed + // + if($response.request.requestStatus.requestState.equals("Completed")) { + $operationWrapper.operation.outcome = "SUCCESS"; + $manager.setControlLoopResult("SUCCESS"); + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_SUCCESS; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_SUCCESS; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } else { + $operationWrapper.operation.outcome = "FAILURE"; + $manager.setControlLoopResult("FAILURE"); + notification.history.add($operationWrapper.operation); + notification.notification = ControlLoopNotificationType.OPERATION_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + notification.notification = ControlLoopNotificationType.FINAL_FAILURE; + // + // Let interested parties know + // + try { + System.out.println(Serialization.gsonPretty.toJson(notification)); + PolicyEngine.manager.deliver($params.getNotificationTopic(), notification); + } catch (Exception e) { + System.out.println("Can't deliver notification: " + notification); + e.printStackTrace(); + } + // + // We are going to retract these objects from memory + // + System.out.println("Retracting everything"); + retract($operationWrapper); + retract($request); + retract($response); + retract($event); + retract($manager); + } + +end diff --git a/ONAP-PDP-REST/xacml.pdp.properties b/ONAP-PDP-REST/xacml.pdp.properties new file mode 100644 index 000000000..b88c93543 --- /dev/null +++ b/ONAP-PDP-REST/xacml.pdp.properties @@ -0,0 +1,172 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP-REST +# ================================================================================ +# 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========================================================= +### + +# Default XACML Properties File for PDP RESTful servlet +# +# Standard API Factories +# +xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory +xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory +xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory +# NOT USED SEE BELOW xacml.pipFinderFactory=org.onap.policy.xacml.std.pip.StdPIPFinderFactory +xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory +# +# AT&T PDP Implementation Factories +# +xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory +xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory +xacml.att.functionDefinitionFactory=org.onap.policy.xacml.custom.OnapFunctionDefinitionFactory +# NOT USED SEE BELOW xacml.att.policyFinderFactory=org.onap.policy.pdp.std.StdPolicyFinderFactory +# creteUpdate Policy Implementation Class details. +createUpdatePolicy.impl.className=org.onap.policy.pdp.rest.api.services.CreateUpdatePolicyServiceImpl +# AAF Implementation class details +aafClient.impl.className=org.onap.policy.utils.AAFPolicyClientImpl +# +# AT&T RESTful PDP Implementation Factories +# +xacml.pipFinderFactory=org.onap.policy.pdp.rest.impl.XACMLPdpPIPFinderFactory +xacml.att.policyFinderFactory=org.onap.policy.pdp.rest.XACMLPdpPolicyFinderFactory +# +# When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into +# into one PolicySet and use the given Policy Algorithm. +# +xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-permit-overrides +# +# PDP RESTful API properties +# +# Set this to the address where the XACML-PAP-REST servlet is running +xacml.rest.pap.url=http://localhost:8070/pap/ + +#if multiple paps exist, the xacml.rest.pap.url can be removed and they can be defined like this: +#xacml.rest.pap.urls=http://localhost:9090/pap/,http://localhost:9091/pap/ + +# +# Give the running PDP an ID for the PAP. The url that its running as is a good choice. +# The PAP identifies PDP's using the URL of the PDP. +# +xacml.rest.pdp.id=http://localhost:8082/pdp/ + +# Give the port number used for the PDP + +xacml.jmx.port=0 + + +# Notification Properties +# Notifcation type: websocket, ueb or dmaap... if left blank websocket is the default +NOTIFICATION_TYPE=websocket +NOTIFICATION_SERVERS= +NOTIFICATION_TOPIC= +NOTIFICATION_DELAY= +UEB_API_KEY= +UEB_API_SECRET= +DMAAP_AAF_LOGIN= +DMAAP_AAF_PASSWORD= + +# +# Set the directory where the PDP holds its Policy Cache and PIP Configuration +# +xacml.rest.pdp.config=config + +xacml.rest.pdp.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ +# +# Initialize register with PAP servlet +# +xacml.rest.pdp.register=true +# +# Sleep period in seconds between register attempts +# +xacml.rest.pdp.register.sleep=15 +# +# number of attempts to register. -1 means keep trying forever. +# +xacml.rest.pdp.register.retries=-1 +# +# max number of bytes in a POST of a XML/JSON request +# old value #32767 +xacml.rest.pdp.maxcontent=99999999 +# +# Set UserID here +xacml.rest.pdp.userid=testpdp +# Set Password here +xacml.rest.pdp.password=alpha456 + +# id PAP +xacml.rest.pap.userid=testpap +#if multiple paps have different logins, they can be defined like this: +#http\://localhost\:9090/pap/.xacml.rest.pap.userid=testpap + +# pass PAP +xacml.rest.pap.password=alpha123 +#http\://localhost\:9090/pap/.xacml.rest.pap.password=alpha123 + +# Delay for Notifications Don't change this. Value in milliSec. +xacml.rest.notification.delay=30 +# Buffer Size. +REQUEST_BUFFER_SIZE=15 + +#properties for MySql xacml database: PLEASE DO NOT REMOVE... NEEDED FOR APIs +javax.persistence.jdbc.driver=com.mysql.jdbc.Driver +javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/onap_sdk +javax.persistence.jdbc.user=policy_user +javax.persistence.jdbc.password=policy_user + + +#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java*** + +#The name of the PDP. Must be unique across the system +xacml.rest.pdp.resource.name=site_1.pdp_1 + +#***Properties for IntegrityMonitor integration defined in IntegrityMonitorProperties.java*** + +#Interval between forward progress counter updates in seconds +fp_monitor_interval=30 + +#Number of forward progress counter failures before failover +failed_counter_threshold=3 + +#Interval in seconds between test transactions if there is no other traffic +test_trans_interval=10 + +#Interval in seconds between updates of the forward progress counter in the DB +write_fpc_interval=5 + +#Name of the site +site_name=site_1 + +#Node type +node_type=pdp_xacml + +#Dependency groups are groups of resources upon which a node operational state is dependent upon). +#Each group is a comma-separated list of resource names and groups are separated by a semicolon. +#A group may contain one or more members. Resource names must match the resource names defined +#in the respective servers' properties files +dependency_groups=site_1.pdplp_1;site_1.astragw_1;site_1.brmsgw_1 + +# this can be DEVL, TEST, PROD +ENVIRONMENT=DEVL +xacml.rest.pep.idfile = client.properties + +#AAF Policy Name space +#Not Mandatory for Open Onap +policy.aaf.namespace = +policy.aaf.resource = +# Decision Response settings. +# can be either PERMIT or DENY. +decision.indeterminate.response=PERMIT \ No newline at end of file diff --git a/ECOMP-PDP/.gitignore b/ONAP-PDP/.gitignore similarity index 100% rename from ECOMP-PDP/.gitignore rename to ONAP-PDP/.gitignore diff --git a/ONAP-PDP/config_testing/test_PolicyEngine.xml b/ONAP-PDP/config_testing/test_PolicyEngine.xml new file mode 100644 index 000000000..13c126364 --- /dev/null +++ b/ONAP-PDP/config_testing/test_PolicyEngine.xml @@ -0,0 +1,595 @@ + + + + + Test Policies for the ProtoType PolicyEngineAPI + + + + Check if the CPU Utilization or Memory reach the threshold values. + + CPU + + + + 95 + + + Memory + + + + 95 + + + + + + Spinoff if the VM if CPU or memory value reaches the threshold + + CPU + + + + 90 + + + Memory + + + + 90 + + + + + Json Test + + + + + JSON + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_json.json + + + + + + Json + Config test + + + + + JSON + + + + JSONconfig + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_json.json + + + + + + XML test + + + + + XML + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_xml.xml + + + + + + XML + Config test + + + + + XML + + + + XMLConfig + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_xml.xml + + + + + + Properties Test + + + + + Properties + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_prop.properties + + + + + + Properties + Config Test + + + + + Properties + + + + PropConfig + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_prop.properties + + + + + + Other Test + + + + + Other + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_other.txt + + + + + + Other + Config Test + + + + + Other + + + + OtherConfig + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_other.txt + + + + + + JSON + Attributes + + + + + JSON + + + + JSONconfig + + + + TestSubject + + + + ACCESS + + + + TestJSON + + + + Config + + + + Test + + + + + + + + + Configuration + + + http://localhost:5443/config/test_json.json + + + + + + XML + Attributes + + + + + XML + + + + XMLConfig + + + + TestSubject + + + + ACCESS + + + + TestJSON + + + + Config + + + + Test + + + + + + + + + Configuration + + + http://localhost:5443/config/test_xml.xml + + + + + + Prop + Attributes + + + + + Properties + + + + PropConfig + + + + TestSubject + + + + ACCESS + + + + TestJSON + + + + Config + + + + Test + + + + + + + + + Configuration + + + http://localhost:5443/config/test_prop.properties + + + + + + Other + Attributes + + + + + Other + + + + Otherconfig + + + + TestSubject + + + + ACCESS + + + + TestJSON + + + + Config + + + + Test + + + + + + + + + Configuration + + + http://localhost:5443/config/test_other.txt + + + + + + + Permit to RESET VM if the values reach the threshold settings. + + + + + Restart + + + + + + + + Restart VM if this condition is met + + true + + + + + + Restart + + + + + + + + + Permit to SpinOff VM if the values reach the threshold settings. + + + + + SpinOff + + + + + + + + SpinOff VM if this condition is met + + true + + + + + + SpinOff + + + PDPAction + + + REST + + + + + + GET + + + http://localhost:8635/RESTjson/PDP/VM/$com.att.labs.onap.obligation.spinoff/$com.att.labs.onap.obligation.server + + + + + + Deny all the other requests. + + + diff --git a/ONAP-PDP/config_testing/xacml.pip.properties b/ONAP-PDP/config_testing/xacml.pip.properties new file mode 100644 index 000000000..e5974f481 --- /dev/null +++ b/ONAP-PDP/config_testing/xacml.pip.properties @@ -0,0 +1,19 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP +# ================================================================================ +# 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========================================================= +### diff --git a/ONAP-PDP/config_testing/xacml.policy.properties b/ONAP-PDP/config_testing/xacml.policy.properties new file mode 100644 index 000000000..0fbaef976 --- /dev/null +++ b/ONAP-PDP/config_testing/xacml.policy.properties @@ -0,0 +1,23 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP +# ================================================================================ +# 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========================================================= +### + +xacml.referencedPolicies=test_PolicyEngine.xml +xacml.rootPolicies=test_PolicyEngine.xml +test_PolicyEngine.xml.file=config_testing\\test_PolicyEngine.xml diff --git a/ONAP-PDP/logging.properties b/ONAP-PDP/logging.properties new file mode 100644 index 000000000..d25697ea8 --- /dev/null +++ b/ONAP-PDP/logging.properties @@ -0,0 +1,29 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP +# ================================================================================ +# 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========================================================= +### + +handlers = java.util.logging.ConsoleHandler, java.util.logging.FileHandler + +.level = ALL + +java.util.logging.ConsoleHandler.level = INFO +java.util.logging.FileHandler.level = INFO +java.util.logging.FileHandler.pattern=%h/xacml_log%u.log +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter +java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter diff --git a/ONAP-PDP/policyLogger.properties b/ONAP-PDP/policyLogger.properties new file mode 100644 index 000000000..35c893b3e --- /dev/null +++ b/ONAP-PDP/policyLogger.properties @@ -0,0 +1,44 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP +# ================================================================================ +# 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========================================================= +### + +################################### Set concurrentHashMap and timer info ####################### +#Timer initial delay and the delay between in milliseconds before task is to be execute. +timer.delay.time=1000 +#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. +check.interval= 30000 +#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. +event.expired.time=86400 +#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed +#to remove all expired records from this concurrentHashMap. +concurrentHashMap.limit=5000 +#Size of the concurrentHashMap - when its size drops to this point, stop the Timer +stop.check.point=2500 +################################### Set logging format ############################################# +# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println +logger.type=EELF +#################################### Set level for EELF or SYSTEMOUT logging ################################## +# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all +debugLogger.level=INFO +# Set level for metrics file. Set OFF to disable; set ON to enable +metricsLogger.level=ON +# Set level for error file. Set OFF to disable; set ON to enable +error.level=ON +# Set level for audit file. Set OFF to disable; set ON to enable +audit.level=ON diff --git a/ONAP-PDP/pom.xml b/ONAP-PDP/pom.xml new file mode 100644 index 000000000..b82e22346 --- /dev/null +++ b/ONAP-PDP/pom.xml @@ -0,0 +1,88 @@ + + + + + + + 4.0.0 + ONAP-PDP + ONAP-PDP + jar + + org.onap.policy.engine + PolicyEngineSuite + 1.1.0-SNAPSHOT + + + + org.onap.policy.engine + ${project.version} + ONAP-REST + + + org.apache.httpcomponents + httpclient + 4.4.1 + + + org.apache.httpcomponents + httpcore + 4.4.4 + + + org.glassfish + javax.json + 1.0.4 + + + commons-codec + commons-codec + 1.10 + + + commons-logging + commons-logging + 1.2 + + + javax.servlet + servlet-api + + + + + com.google.guava + guava + 19.0 + + + com.att.research.xacml + xacml-pdp + 1.0.0 + + + junit + junit + 4.11 + + + diff --git a/ECOMP-PDP/sql/xacmlTest.mv.db b/ONAP-PDP/sql/xacmlTest.mv.db similarity index 100% rename from ECOMP-PDP/sql/xacmlTest.mv.db rename to ONAP-PDP/sql/xacmlTest.mv.db diff --git a/ONAP-PDP/src/main/java/org/onap/policy/xacml/action/FindAction.java b/ONAP-PDP/src/main/java/org/onap/policy/xacml/action/FindAction.java new file mode 100644 index 000000000..c6a889821 --- /dev/null +++ b/ONAP-PDP/src/main/java/org/onap/policy/xacml/action/FindAction.java @@ -0,0 +1,356 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.xacml.action; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.json.Json; +import javax.json.JsonReader; + +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.DefaultHttpClient; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.XACMLRestProperties; + +import com.att.research.xacml.api.Advice; +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeAssignment; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.Obligation; +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.RequestAttributes; +import com.att.research.xacml.api.Result; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdAdvice; +import com.att.research.xacml.std.StdAttributeAssignment; +import com.att.research.xacml.std.StdAttributeValue; +import com.att.research.xacml.std.StdMutableResponse; +import com.att.research.xacml.std.StdMutableResult; +import com.att.research.xacml.std.StdObligation; +import com.att.research.xacml.util.XACMLProperties; + +@SuppressWarnings("deprecation") +public class FindAction { + private Logger LOGGER = FlexLogger.getLogger(this.getClass()); + private Boolean changeIt = false; + private String configURL = null; + private StdMutableResponse newResponse = new StdMutableResponse(); + private StdMutableResult addResult = new StdMutableResult(); + + public StdMutableResponse run(StdMutableResponse stdResponse, Request pepRequest) { + int count = 0; + boolean config = false; + boolean decide = false; + Collection requestAttributes = pepRequest.getRequestAttributes(); + for(RequestAttributes requestAttribute : requestAttributes){ + Collection attributes = requestAttribute.getAttributes(); + for(Attribute attribute : attributes){ + if(attribute.getAttributeId().stringValue().equals("urn:oasis:names:tc:xacml:1.0:action:action-id")){ + for(AttributeValue attributeValue : attribute.getValues()){ + if(attributeValue.getValue().toString().equalsIgnoreCase("ACCESS")){ + count++; + } + if(attributeValue.getValue().toString().equalsIgnoreCase("DECIDE")){ + decide = true; + } + } + } + if(attribute.getAttributeId().stringValue().equals("urn:oasis:names:tc:xacml:1.0:resource:resource-id")){ + for(AttributeValue attributeValue : attribute.getValues()){ + if(attributeValue.getValue().toString().equalsIgnoreCase("Config")){ + count++; + } + } + } + } + } + if(count==2){ + config = true; + } + if(!config){ + search(stdResponse); + } + addResults(stdResponse, config , decide); + LOGGER.info("Original Result is " + stdResponse.toString()); + LOGGER.info("Generated Result is " + addResult.toString()); + return newResponse; + } + + private Collection obligations = new ArrayList<>(); + private Map matchValues = new HashMap<>(); + private Map headers = new HashMap<>(); + private boolean header = false; + + private void search(StdMutableResponse stdResponse) { + for (Result result : stdResponse.getResults()) { + if (!result.getObligations().isEmpty()) { + System.out.println("Obligation Received"); + // Is there any action that PDP needs to take + for (Obligation obligation : result.getObligations()) { + int count = 0, uri = 0, PEP = 0; + header = false; + changeIt = false; + Collection afterRemoveAssignments = new ArrayList<>(); + Identifier oblId = new IdentifierImpl(obligation.getId().stringValue()); + StdAttributeAssignment attributeURI = null; + for (AttributeAssignment attribute : obligation.getAttributeAssignments()) { + matchValues.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString()); + if (attribute.getAttributeId().stringValue().equalsIgnoreCase("performer")) { + if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("PEPACTION")) { + PEP++; + } else if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("PDPACTION")) { + count++; + } + } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("URL")) { + uri++; + if (uri == 1) { + configURL = attribute.getAttributeValue().getValue().toString(); + attributeURI = new StdAttributeAssignment(attribute); + } + } else if (attribute.getAttributeId().stringValue().startsWith("headers")) { + LOGGER.info("Headers are : "+ attribute.getAttributeValue().getValue().toString()); + header = true; + headers.put(attribute.getAttributeId().stringValue().replaceFirst("(headers).", ""), + attribute.getAttributeValue().getValue().toString()); + afterRemoveAssignments.add(attribute); + } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("body")) { + String papPath = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + papPath= papPath.replace("/pap", ""); + matchValues.put("body",attribute.getAttributeValue().getValue().toString().replace("$URL", papPath)); + }else { + StdAttributeAssignment attributeObligation = new StdAttributeAssignment(attribute); + afterRemoveAssignments.add(attributeObligation); + } + } + if (count == 1 && uri == 1 && PEP == 0) { + // Remove Obligation and add Advice + changeIt = true; + takeAction(stdResponse, oblId, afterRemoveAssignments); + } else if (PEP == 1 && count == 0) { + // Strip the PEPACTION if available + if (uri == 1) { + afterRemoveAssignments.add(attributeURI); + } + Obligation afterRemoveObligation = new StdObligation( + oblId, afterRemoveAssignments); + obligations.add(afterRemoveObligation); + } else { + obligations.add(obligation); + } + } + } + } + } + + private void takeAction(StdMutableResponse stdResponse, Identifier advId, + Collection afterRemoveAssignments) { + if (changeIt) { + LOGGER.info("the URL is :" + configURL); + // Calling Rest URL.. + callRest(); + // Including the Results in an Advice + Identifier id = new IdentifierImpl( + "org.onap.policy:pdp:reply"); + Identifier statId = new IdentifierImpl( + "org:onap:onap:policy:pdp:reply:status"); + Identifier statCategory = new IdentifierImpl( + "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject"); + Identifier strId = new IdentifierImpl( + "http://www.w3.org/2001/XMLSchema#string"); + Identifier resId = new IdentifierImpl( + "org:onap:onap:policy:pdp:reply:resource"); + Identifier resCategory = new IdentifierImpl( + "urn:oasis:names:tc:xacml:3.0:attribute-category:resource"); + Identifier urlId = new IdentifierImpl( + "http://www.w3.org/2001/XMLSchema#anyURI"); + AttributeValue attributeStatusValue = new StdAttributeValue<>( + strId, status + response); + AttributeValue attributeResourceValue = new StdAttributeValue<>( + urlId, configURL); + StdAttributeAssignment attributeStatus = new StdAttributeAssignment( + statCategory, statId, "PDP", attributeStatusValue); + StdAttributeAssignment attributeResouce = new StdAttributeAssignment( + resCategory, resId, "PDP", attributeResourceValue); + afterRemoveAssignments.add(attributeStatus); + afterRemoveAssignments.add(attributeResouce); + Advice advice = new StdAdvice(id, afterRemoveAssignments); + addResult.addAdvice(advice); + } + } + + private void addResults(StdMutableResponse stdResponse, boolean config, boolean decide) { + if(decide){ + newResponse = stdResponse; + return; + } + for (Result result : stdResponse.getResults()) { + if(config){ + addResult.addAdvice(result.getAssociatedAdvice()); + } + addResult.addAttributeCategories(result.getAttributes()); + addResult.addPolicyIdentifiers(result.getPolicyIdentifiers()); + addResult.addPolicySetIdentifiers(result.getPolicySetIdentifiers()); + addResult.setStatus(result.getStatus()); + addResult.setDecision(result.getDecision()); + if(!config){ + addResult.addObligations(obligations); + } + } + newResponse.add(addResult); + } + + private int status; + private String response; + private DefaultHttpClient httpClient; + + private void callRest() { + // Finding the Macros in the URL.. + Pattern pattern = Pattern.compile("\\$([a-zA-Z0-9.:]*)"); + Matcher match = pattern.matcher(configURL); + StringBuffer sb = new StringBuffer(); + while (match.find()) { + LOGGER.info("Found Macro : " + match.group(1)); + String replaceValue = matchValues.get(match.group(1)); + LOGGER.info("Replacing with :" + replaceValue); + match.appendReplacement(sb, replaceValue); + } + match.appendTail(sb); + LOGGER.info("URL is : " + sb.toString()); + configURL = sb.toString(); + // Calling the Requested service. + if (matchValues.get("method").equalsIgnoreCase("GET")) { + httpClient = new DefaultHttpClient(); + try { + HttpGet getRequest = new HttpGet(configURL); + // Adding Headers here + if (header) { + for (String key : headers.keySet()) { + getRequest.addHeader(key, headers.get(key)); + } + } + HttpResponse result = httpClient.execute(getRequest); + status = result.getStatusLine().getStatusCode(); + BufferedReader br = new BufferedReader(new InputStreamReader( + (result.getEntity().getContent()))); + String output = " "; + String out; + while ((out = br.readLine()) != null) { + output = output + out; + } + response = output; + } catch (Exception e) { + LOGGER.error(e.getMessage()+e); + response = e.getMessage(); + } finally { + httpClient.getConnectionManager().shutdown(); + } + } else if(matchValues.get("method").equalsIgnoreCase("POST")) { + httpClient = new DefaultHttpClient(); + try { + HttpPost postRequest = new HttpPost(configURL); + // Adding Headers here + if (header) { + for (String key : headers.keySet()) { + postRequest.addHeader(key, headers.get(key)); + } + } + // Adding the Body. + URL configURL = new URL(matchValues.get("body")); + URLConnection connection = null; + connection = configURL.openConnection(); + // InputStream in = connection.getInputStrem(); + // LOGGER.info("The Body Content is : " + IOUtils.toString(in)); + JsonReader jsonReader = Json.createReader(connection.getInputStream()); + StringEntity input = new StringEntity(jsonReader.readObject().toString()); + input.setContentType("application/json"); + postRequest.setEntity(input); + // Executing the Request. + HttpResponse result = httpClient.execute(postRequest); + LOGGER.info("Result Headers are : " + result.getAllHeaders()); + status = result.getStatusLine().getStatusCode(); + BufferedReader br = new BufferedReader(new InputStreamReader( + (result.getEntity().getContent()))); + String output = " "; + String out; + while ((out = br.readLine()) != null) { + output = output + out; + } + response = output; + }catch (Exception e) { + LOGGER.error(e.getMessage() +e); + response = e.getMessage(); + } finally { + httpClient.getConnectionManager().shutdown(); + } + } else if(matchValues.get("method").equalsIgnoreCase("PUT")) { + httpClient = new DefaultHttpClient(); + try { + HttpPut putRequest = new HttpPut(configURL); + // Adding Headers here + if (header) { + for (String key : headers.keySet()) { + putRequest.addHeader(key, headers.get(key)); + } + } + // Adding the Body. + URL configURL = new URL(matchValues.get("body")); + URLConnection connection = null; + connection = configURL.openConnection(); + //InputStream in = connection.getInputStream(); + //LOGGER.info("The Body Content is : " + IOUtils.toString(in)); + JsonReader jsonReader = Json.createReader(connection.getInputStream()); + StringEntity input = new StringEntity(jsonReader.readObject().toString()); + input.setContentType("application/json"); + putRequest.setEntity(input); + // Executing the Request. + HttpResponse result = httpClient.execute(putRequest); + status = result.getStatusLine().getStatusCode(); + BufferedReader br = new BufferedReader(new InputStreamReader( + (result.getEntity().getContent()))); + String output = " "; + String out; + while ((out = br.readLine()) != null) { + output = output + out; + } + response = output; + } catch (Exception e) { + LOGGER.error(e.getMessage() +e); + response = e.getMessage(); + }finally { + httpClient.getConnectionManager().shutdown(); + } + } + } +} \ No newline at end of file diff --git a/ONAP-PDP/src/main/java/org/onap/policy/xacml/action/package-info.java b/ONAP-PDP/src/main/java/org/onap/policy/xacml/action/package-info.java new file mode 100644 index 000000000..82c6182b9 --- /dev/null +++ b/ONAP-PDP/src/main/java/org/onap/policy/xacml/action/package-info.java @@ -0,0 +1,30 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.xacml.action; + +/** + * org.onap.policy.xacml.action contains the implementation of the PDP Actions. + * Changes: + * Now PDP supports actions based on PUT, GET, POST methods + * + * @version 0.2 + * + */ diff --git a/ONAP-PDP/src/main/java/org/onap/policy/xacml/custom/OnapFunctionDefinitionFactory.java b/ONAP-PDP/src/main/java/org/onap/policy/xacml/custom/OnapFunctionDefinitionFactory.java new file mode 100644 index 000000000..87075f9bb --- /dev/null +++ b/ONAP-PDP/src/main/java/org/onap/policy/xacml/custom/OnapFunctionDefinitionFactory.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.xacml.custom; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.HashMap; +import java.util.Map; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.xacml.pdp.std.functions.FunctionDefinitionCustomRegexpMatch; + +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.FunctionDefinition; +import com.att.research.xacmlatt.pdp.policy.FunctionDefinitionFactory; +import com.att.research.xacmlatt.pdp.std.StdFunctions; + +public class OnapFunctionDefinitionFactory extends FunctionDefinitionFactory { + private static Logger logger = FlexLogger.getLogger(OnapFunctionDefinitionFactory.class); + private static Map mapFunctionDefinitions = new HashMap<>(); + private static boolean needMapInit = true; + + public static final Identifier ID_FUNCTION_CUSTOM_REGEXP_MATCH = new IdentifierImpl("org.onap.function.regex-match"); + + private static final FunctionDefinition FD_CUSTOM_REGEXP_MATCH = new FunctionDefinitionCustomRegexpMatch<>(ID_FUNCTION_CUSTOM_REGEXP_MATCH, DataTypes.DT_STRING); + + private static void register(FunctionDefinition functionDefinition) { + mapFunctionDefinitions.put(functionDefinition.getId(), functionDefinition); + } + + private static void initMap() { + if (needMapInit) { + synchronized(mapFunctionDefinitions) { + if (needMapInit) { + needMapInit = false; + Field[] declaredFields = StdFunctions.class.getDeclaredFields(); + for (Field field : declaredFields) { + if (Modifier.isStatic(field.getModifiers()) && + field.getName().startsWith(StdFunctions.FD_PREFIX) && + FunctionDefinition.class.isAssignableFrom(field.getType()) && + Modifier.isPublic(field.getModifiers()) + ) { + try { + register((FunctionDefinition)(field.get(null))); + } catch (IllegalAccessException ex) { + logger.error(ex.getMessage() +ex); + } + } + } + // + // Our custom function + // + //register(FunctionDefinitionCustomRegexpMatch); + register(FD_CUSTOM_REGEXP_MATCH); + } + } + } + } + + public OnapFunctionDefinitionFactory() { + initMap(); + } + + @Override + public FunctionDefinition getFunctionDefinition(Identifier functionId) { + return mapFunctionDefinitions.get(functionId); + } +} diff --git a/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/ONAPPDPEngine.java b/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/ONAPPDPEngine.java new file mode 100644 index 000000000..fb90d0a2e --- /dev/null +++ b/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/ONAPPDPEngine.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.xacml.pdp; + +import java.util.Properties; + +import org.onap.policy.xacml.action.FindAction; + +import com.att.research.xacml.api.Decision; +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.Response; +import com.att.research.xacml.api.pdp.PDPException; +import com.att.research.xacml.api.pdp.ScopeResolver; +import com.att.research.xacml.std.StdMutableResponse; +import com.att.research.xacmlatt.pdp.ATTPDPEngine; +import com.att.research.xacmlatt.pdp.eval.EvaluationContextFactory; + +public class ONAPPDPEngine extends ATTPDPEngine { + + public ONAPPDPEngine(EvaluationContextFactory evaluationContextFactoryIn, Decision defaultDecisionIn, + ScopeResolver scopeResolverIn, Properties properties) { + super(evaluationContextFactoryIn, defaultDecisionIn, scopeResolverIn, properties); + } + + public ONAPPDPEngine(EvaluationContextFactory evaluationContextFactoryIn, Decision defaultDecisionIn, + ScopeResolver scopeResolverIn) { + super(evaluationContextFactoryIn, defaultDecisionIn, scopeResolverIn); + } + + public ONAPPDPEngine(EvaluationContextFactory evaluationContextFactoryIn, ScopeResolver scopeResolverIn) { + super(evaluationContextFactoryIn, scopeResolverIn); + } + + @Override + public Response decide(Request pepRequest) throws PDPException { + Response response = super.decide(pepRequest); + + FindAction findAction = new FindAction(); + return findAction.run((StdMutableResponse) response, pepRequest); + } + + +} diff --git a/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/ONAPPDPEngineFactory.java b/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/ONAPPDPEngineFactory.java new file mode 100644 index 000000000..2e796bf68 --- /dev/null +++ b/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/ONAPPDPEngineFactory.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.xacml.pdp; + +import java.util.Properties; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.api.pdp.PDPEngineFactory; +import com.att.research.xacml.util.FactoryException; +import com.att.research.xacmlatt.pdp.eval.EvaluationContextFactory; + +public class ONAPPDPEngineFactory extends PDPEngineFactory { + private Logger logger = FlexLogger.getLogger(this.getClass()); + + @Override + public PDPEngine newEngine() throws FactoryException { + EvaluationContextFactory evaluationContextFactory = EvaluationContextFactory.newInstance(); + if (evaluationContextFactory == null) { + this.logger.error("Null EvaluationContextFactory"); + throw new FactoryException("Null EvaluationContextFactory"); + } + return new ONAPPDPEngine(evaluationContextFactory, this.getDefaultBehavior(), this.getScopeResolver()); + } + + @Override + public PDPEngine newEngine(Properties properties) throws FactoryException { + EvaluationContextFactory evaluationContextFactory = EvaluationContextFactory.newInstance(properties); + if (evaluationContextFactory == null) { + this.logger.error("Null EvaluationContextFactory"); + throw new FactoryException("Null EvaluationContextFactory"); + } + return new ONAPPDPEngine(evaluationContextFactory, this.getDefaultBehavior(), this.getScopeResolver(), properties); + } + +} diff --git a/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatch.java b/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatch.java new file mode 100644 index 000000000..590d519cc --- /dev/null +++ b/ONAP-PDP/src/main/java/org/onap/policy/xacml/pdp/std/functions/FunctionDefinitionCustomRegexpMatch.java @@ -0,0 +1,130 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.xacml.pdp.std.functions; + + +import java.util.List; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +import com.att.research.xacml.api.DataType; +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.std.StdStatus; +import com.att.research.xacml.std.StdStatusCode; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.eval.EvaluationContext; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.std.functions.ConvertedArgument; +import com.att.research.xacmlatt.pdp.std.functions.FunctionDefinitionBase; + +/** + * FunctionDefinitionCustomRegexMatch implements {@link com.att.research.xacmlatt.pdp.policy.FunctionDefinition} to + * implement the custom 'type'-regex-match predicates as functions taking two arguments, the first of String, + * and the second of the type for that specific predicate as a regular expression, + * and returning a Boolean for whether the regular expression matches the string representation of the first argument. + * + * + * @version $Revision: 0.2 $ + * + * @param the java class for the data type of the function Input arguments + */ +public class FunctionDefinitionCustomRegexpMatch extends FunctionDefinitionBase { + private static Logger logger = FlexLogger.getLogger(FunctionDefinitionCustomRegexpMatch.class); + + /** + * Constructor - need dataTypeArgs input because of java Generic type-erasure during compilation. + * + * @param idIn + * @param dataTypeArgsIn + */ + public FunctionDefinitionCustomRegexpMatch(Identifier idIn, DataType dataTypeArgsIn) { + super(idIn, DataTypes.DT_BOOLEAN, dataTypeArgsIn, false); + } + + + @Override + public ExpressionResult evaluate(EvaluationContext evaluationContext, List arguments) { + + if (arguments == null || arguments.size() != 2) { + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, this.getShortFunctionId() + " Expected 2 arguments, got " + + ((arguments == null) ? "null" : arguments.size()) )); + } + + // get the regular expression + FunctionArgument regexpArgument = arguments.get(0); + + ConvertedArgument convertedArgument = new ConvertedArgument<>(regexpArgument, DataTypes.DT_STRING, false); + if ( ! convertedArgument.isOk()) { + return ExpressionResult.newError(getFunctionStatus(convertedArgument.getStatus())); + } + + // String regexpValue = (String)regexpArgument.getValue().getValue(); + String regexpValue = convertedArgument.getValue(); + + + // now get the element to match + FunctionArgument elementArgument = arguments.get(1); + + ConvertedArgument convertedElement = new ConvertedArgument<>(elementArgument, this.getDataTypeArgs(), false); + if ( ! convertedElement.isOk()) { + return ExpressionResult.newError(getFunctionStatus(convertedElement.getStatus())); + } + + I elementValueObject = convertedElement.getValue(); + + String elementValueString; + try { + elementValueString = this.getDataTypeArgs().toStringValue(elementValueObject); + } catch (DataTypeException e) { + logger.error(e.getMessage() +e); + String message = e.getMessage(); + if (e.getCause() != null) { + message = e.getCause().getMessage(); + } + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, this.getShortFunctionId() + " " + message)); + } + + // ConvertedArgument checks for null value, so do not need to do again here + + // Adding this code will Change the Functionality which allows to retrieve Multiple-policy using single request. + elementValueString = elementValueString + regexpValue ; + regexpValue = elementValueString.substring(0,(elementValueString.length()- regexpValue.length())); + elementValueString = elementValueString.substring(regexpValue.length(),(elementValueString.length())); + // + // Supporting multiple values in the element and be able to query them. + if(elementValueString.contains(",")){ + String[] elements = elementValueString.split(","); + for(int i=0; i policyList = new ArrayList<>(); + + + public static List getpolicyList(){ + return policyList; + } + + public static void addPolicyID(String policyID){ + if (!policyList.contains(policyID)){ + policyList.add(policyID); + } + } + + public static void clearPolicyList(){ + if (!policyList.isEmpty()){ + policyList.clear(); + } + } +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionAccessPermittedTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionAccessPermittedTest.java new file mode 100644 index 000000000..4abfd99dc --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionAccessPermittedTest.java @@ -0,0 +1,521 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.xml.namespace.NamespaceContext; + +import org.junit.Ignore; + +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.StdMutableRequest; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacml.std.dom.DOMRequest; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.std.StdEvaluationContext; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.FunctionDefinitionAccessPermitted; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * NOT IMPLEMENTED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + * This function is not yet implemented so these tests intentionally fail. + * + * + */ +public class FunctionDefinitionAccessPermittedTest { + + // + // Strings for the Request contents + // + + String reqStrMainStart = "" + + "" + + " " + + " " + + " Julius Hibbert" + + " " + + " " + + " This is IT! " + + " " + + " " + + " This is IT! " + + " " + + ""; + + String reqStrResourceStart = ""; + + String reqStrMdRecordSimpson = + "" + + "" + + "ABC Hospital" + + "Surgery" + + "" + + "" + + "Bart Simpson" + + "60" + + "male" + + "123456" + + "" + + "" + + "" + + "Gastric Cancer" + + "Hyper tension" + + "" + + "" + + "" + + "Well differentiated adeno carcinoma" + + "" + + "2000-10-05" + + "" + + "" + + "" + + " "; + String reqStrContentMdRecordSimpson = "" + reqStrMdRecordSimpson + ""; + String reqStrMalformedContent = + " " + + "" + + "" + + "ABC Hospital" + + "" + + ""; + String reqStrMdRecordSpringer = + "" + + "" + + "XYZ Hospital" + + "Surgery" + + "" + + "" + + "Jerry Springer" + + "65" + + "male" + + "765432" + + "" + + "" + + "" + + "Hyatal Hernia" + + "Diabetes" + + "Neuronal Collapse" + + "" + + "" + + "" + + "We have no idea" + + "" + + "2012-07-22" + + "" + + "" + + "" + + " "; + String reqStrContentMdRecordSpringer = + "" + reqStrMdRecordSpringer + ""; + + String reqStrResourceEnd = " " + + " http://medico.com/record/patient/BartSimpson" + + " " + + " "; + String reqStrActionStart = ""; + + String reqStrActionEnd = "" + + "read" + + "" + + " "; + String reqStrEnvironmentStartEnd = " "; + String reqStrMainEnd = " "; + + + // combined strings for convenience + String reqStrMainResourceStart = reqStrMainStart + reqStrResourceStart; + String reqStrResourceAllEnd = reqStrResourceEnd + reqStrActionStart + reqStrActionEnd + reqStrEnvironmentStartEnd + reqStrMainEnd; + + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + + + // Name Spaces used in the XML as part of these examples - needed for compiling XPaths + NamespaceContext nameSpaceContext = new NamespaceContext() { + @Override + public Iterator getPrefixes(String arg0) { return null;} + + @Override + public String getPrefix(String arg0) {return null;} + + @Override + public String getNamespaceURI(String arg0) { + if("md".equals(arg0)) { + return "http://www.medico.com/schemas/record"; + } else if ("xacml-context".equals(arg0)) { + return "urn:oasis:names:tc:xacml:3.0:context:schema:os"; + } else if ("xsi".equals(arg0)) { + return "http://www.w3.org/2001/XMLSchema-instance"; + } + return null; + } + }; + + + + // + // URIs for attribute categroies + // + + FunctionArgumentAttributeValue attrUriNull = null; + FunctionArgumentAttributeValue attrUriEmpty = null; + FunctionArgumentAttributeValue attrUriResources = null; + FunctionArgumentAttributeValue attrUriAction = null; + FunctionArgumentAttributeValue attrUriNotInRequest = null; + FunctionArgumentAttributeValue attrUriNotCategory = null; + + + + // + // XML Contents + // + + FunctionArgumentAttributeValue attrXnull = null; + FunctionArgumentAttributeValue attrXEmpty = null; + FunctionArgumentAttributeValue attrXSimpson = null; + FunctionArgumentAttributeValue attrXSpringer = null; + FunctionArgumentAttributeValue attrXContentSimpson = null; + FunctionArgumentAttributeValue attrXContentSpringer = null; + FunctionArgumentAttributeValue attrXBadXML = null; + + + + + + + // + // REQUEST objects available for use in tests + // + Request requestEmpty = new StdMutableRequest(); + Request requestMdRecord = null; + Request requestDoubleResources = null; + Request requestDoubleContent = null; + Request requestResourceActionContent = null; + Request requestContentInAction = null; + + + + + /** + * Set up all variables in one place because it is complicated (lots of steps needed for each attribute) + */ + public FunctionDefinitionAccessPermittedTest() { + try { + + + // create Function Attributes for URIs + attrUriNull = null; + attrUriEmpty = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("")); + attrUriResources = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("urn:oasis:names:tc:xacml:3.0:attribute-category:resource")); + attrUriAction = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("urn:oasis:names:tc:xacml:3.0:attribute-category:action")); + attrUriNotInRequest = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("NoSuchURI")); + attrUriNotCategory = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("urn:oasis:names:tc:xacml:1.0:resource:resource-id")); + + // create Function Attributes for XML Strings + attrXnull = new FunctionArgumentAttributeValue(null); + attrXEmpty = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); + attrXSimpson = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(reqStrMdRecordSimpson)); + attrXSpringer = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(reqStrMdRecordSpringer)); + attrXContentSimpson = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(reqStrContentMdRecordSimpson)); + attrXContentSpringer = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(reqStrContentMdRecordSpringer)); + attrXBadXML = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(reqStrMalformedContent)); + + + + // Request objects + // to create a Request object the easiest way is to put the xml into a file and use the DOMRequest to load it. + + // single Content in the Resources section (normal valid request) + String reqString = reqStrMainResourceStart + reqStrContentMdRecordSimpson + reqStrResourceAllEnd; + File tFile = File.createTempFile("functionJunit", "request"); + BufferedWriter bw = new BufferedWriter(new FileWriter(tFile)); + bw.append(reqString); + bw.flush(); + bw.close(); + requestMdRecord = DOMRequest.load(tFile); + tFile.delete(); + + // Resources included twice + reqString = reqStrMainResourceStart + reqStrContentMdRecordSimpson + reqStrResourceEnd + reqStrResourceStart + reqStrContentMdRecordSimpson +reqStrResourceAllEnd; + tFile = File.createTempFile("functionJunit", "request"); + bw = new BufferedWriter(new FileWriter(tFile)); + bw.append(reqString); + bw.flush(); + bw.close(); + requestDoubleResources = DOMRequest.load(tFile); + tFile.delete(); + + // Content included twice - error + reqString = reqStrMainResourceStart + reqStrContentMdRecordSimpson + reqStrContentMdRecordSimpson +reqStrResourceAllEnd; + tFile = File.createTempFile("functionJunit", "request"); + bw = new BufferedWriter(new FileWriter(tFile)); + bw.append(reqString); + bw.flush(); + bw.close(); + try { + requestDoubleContent = DOMRequest.load(tFile); + tFile.delete(); + } catch (com.att.research.xacml.std.dom.DOMStructureException e) { + // this is what it should do, so just continue + } catch (Exception e) { + fail("Unexpected exception for bad XML, e="+e); + } + + // content included in both Resource and Action - ok + reqString = reqStrMainResourceStart + reqStrContentMdRecordSimpson + reqStrResourceEnd + reqStrActionStart + reqStrContentMdRecordSimpson + reqStrActionEnd + reqStrMainEnd; + tFile = File.createTempFile("functionJunit", "request"); + bw = new BufferedWriter(new FileWriter(tFile)); + bw.append(reqString); + bw.flush(); + bw.close(); + requestResourceActionContent = DOMRequest.load(tFile); + tFile.delete(); + + // Content included only in Action - missing content produces non-error result according to spec + reqString = reqStrMainResourceStart + reqStrResourceEnd + reqStrActionStart + reqStrContentMdRecordSimpson + reqStrActionEnd + reqStrMainEnd; + tFile = File.createTempFile("functionJunit", "request"); + bw = new BufferedWriter(new FileWriter(tFile)); + bw.append(reqString); + bw.flush(); + bw.close(); + requestContentInAction = DOMRequest.load(tFile); + tFile.delete(); + + + + // Test that Bad XML is caught + @SuppressWarnings("unused") + Request requestContentMisplaced = null; + @SuppressWarnings("unused") + Request requestMalformedContent = null; + + + // Bad XML - Content not under a Category + reqString = reqStrMainStart + reqStrContentMdRecordSimpson + reqStrResourceStart + reqStrResourceEnd + reqStrActionStart + reqStrActionEnd + reqStrMainEnd; + tFile = File.createTempFile("functionJunit", "request"); + bw = new BufferedWriter(new FileWriter(tFile)); + bw.append(reqString); + bw.flush(); + bw.close(); + try { + requestContentMisplaced = DOMRequest.load(tFile); + tFile.delete(); + } catch (com.att.research.xacml.std.dom.DOMStructureException e) { + // this is what it should do, so just continue + } catch (Exception e) { + fail("Unexpected exception for bad XML, e="+e); + } + + // Bad XML - Content is not valid XML + reqString = reqStrMainResourceStart + reqStrMalformedContent + reqStrResourceAllEnd; + tFile = File.createTempFile("functionJunit", "request"); + bw = new BufferedWriter(new FileWriter(tFile)); + bw.append(reqString); + bw.flush(); + bw.close(); + try { + requestMalformedContent = DOMRequest.load(tFile); + tFile.delete(); + } catch (com.att.research.xacml.std.dom.DOMStructureException e) { + // this is what it should do, so just continue + } catch (Exception e) { + fail("Unexpected exception for bad XML, e="+e); + } + + } catch (Exception e) { + fail("Constructor initializing variables, e="+ e + " cause="+e.getCause()); + } + + } + + + + + + + + + @Ignore //@Test + public void testAccess_permitted() { + + ExpressionResult res = null; + Boolean resValue = null; + + FunctionDefinitionAccessPermitted fd = (FunctionDefinitionAccessPermitted) StdFunctions.FD_ACCESS_PERMITTED; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_ACCESS_PERMITTED, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + + // successful invoke returns true + arguments.clear(); + arguments.add(attrUriResources); + arguments.add(attrXEmpty); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + + + // successful invoke returns false + + + // URI not in Request (ok - evaluate anyway) + + // test for infinite loop + + // second arg ok both with and without tag + arguments.clear(); + arguments.add(attrUriResources); + arguments.add(attrXContentSpringer); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + arguments.clear(); + arguments.add(attrUriResources); + arguments.add(attrXSpringer); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // second arg not valid XML + arguments.clear(); + arguments.add(attrUriResources); + arguments.add(attrXBadXML); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:access-permitted Parsing of XML string failed. Cause='The element type \"md:hospital_info\" must be terminated by the matching end-tag \"\".'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null Evaluation Context + arguments.clear(); + arguments.add(attrUriNotCategory); + arguments.add(attrXContentSimpson); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:access-permitted First argument must be a urn for an attribute-category, not 'urn:oasis:names:tc:xacml:1.0:resource:resource-id", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null Request + arguments.clear(); + arguments.add(attrUriAction); + arguments.add(attrXContentSimpson); + res = fd.evaluate(new StdEvaluationContext(null, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:access-permitted Got null Request in EvaluationContext", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // first arg not uri + arguments.clear(); + arguments.add(attrUriNotCategory); + arguments.add(attrXContentSimpson); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:access-permitted First argument must be a urn for an attribute-category, not 'urn:oasis:names:tc:xacml:1.0:resource:resource-id", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // first arg not attribute-category urn + arguments.clear(); + arguments.add(attrXContentSimpson); + arguments.add(attrXContentSimpson); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:access-permitted Expected data type 'anyURI' saw 'string'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second arg not string + arguments.clear(); + arguments.add(attrUriAction); + arguments.add(attrUriAction); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:access-permitted Expected data type 'string' saw 'anyURI'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // too few args + arguments.clear(); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:access-permitted Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrXContentSimpson); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:access-permitted Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // too many args + arguments.clear(); + arguments.add(attrUriEmpty); + arguments.add(attrXContentSimpson); + arguments.add(attrXContentSimpson); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:access-permitted Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionArithmeticTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionArithmeticTest.java new file mode 100644 index 000000000..56e79cf29 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionArithmeticTest.java @@ -0,0 +1,717 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionArithmeticTest { + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + @Test + public void testInteger_add() { + + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + FunctionArgumentAttributeValue attrBadType = null; + try { + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); + attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.1)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_INTEGER_ADD; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_INTEGER_ADD, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + + // test normal add + arguments.add(attr1); + arguments.add(attr2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + BigInteger resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("2"), resValue); + + arguments.clear(); + arguments.add(attr1); + arguments.add(attrBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:integer-add Expected data type 'integer' saw 'double' at arg index 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + @Test + public void testDouble_add() { + + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + + try { + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.5)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(2.5)); + } catch (Exception e) { + fail("creating attributes e="+e); + } + + FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_DOUBLE_ADD; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DOUBLE_ADD, fd.getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + + // test normal add + arguments.add(attr1); + arguments.add(attr2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Double resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(4.0), resValue); + + } + + + @Test + public void testInteger_subtract() { + + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + try { + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(6)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_INTEGER_SUBTRACT; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_INTEGER_SUBTRACT, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + + // test normal + arguments.add(attr1); + arguments.add(attr2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + BigInteger resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("5"), resValue); + + } + + + @Test + public void testDouble_subtract() { + + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + + try { + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(8.5)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(2.3)); + } catch (Exception e) { + fail("creating attributes e="+e); + } + + FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_DOUBLE_SUBTRACT; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DOUBLE_SUBTRACT, fd.getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + + // test normal + arguments.add(attr1); + arguments.add(attr2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Double resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(6.2), resValue); + + } + + + @Test + public void testInteger_multiply() { + + FunctionArgumentAttributeValue attr0 = null; + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + try { + attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(5)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(2)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_INTEGER_MULTIPLY; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_INTEGER_MULTIPLY, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + + // test normal + arguments.add(attr1); + arguments.add(attr2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + BigInteger resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("10"), resValue); + + + // test 0 + arguments.clear(); + arguments.add(attr1); + arguments.add(attr0); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("0"), resValue); + } + + + @Test + public void testDouble_multiply() { + + FunctionArgumentAttributeValue attr0 = null; + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + + try { + attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(0)); + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.5)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(2.5)); + } catch (Exception e) { + fail("creating attributes e="+e); + } + + FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_DOUBLE_MULTIPLY; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DOUBLE_MULTIPLY, fd.getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + + // test normal add + arguments.add(attr1); + arguments.add(attr2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Double resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(3.75), resValue); + + // test multiply by 0 + arguments.clear(); + arguments.add(attr1); + arguments.add(attr0); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(0), resValue); + } + + + @Test + public void testInteger_divide() { + + FunctionArgumentAttributeValue attr0 = null; + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + try { + attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(5)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(2)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_INTEGER_DIVIDE; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_INTEGER_DIVIDE, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + + // test normal + arguments.add(attr1); + arguments.add(attr2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + BigInteger resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("2"), resValue); + + + // test 0 + arguments.clear(); + arguments.add(attr1); + arguments.add(attr0); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:integer-divide Divide by 0 error: 5, 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + @Test + public void testDouble_divide() { + + FunctionArgumentAttributeValue attr0 = null; + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + + try { + attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(0)); + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.5)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(2.5)); + + } catch (Exception e) { + fail("creating attributes e="+e); + } + FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_DOUBLE_DIVIDE; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DOUBLE_DIVIDE, fd.getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + + // test normal + arguments.add(attr1); + arguments.add(attr2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Double resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(0.6), resValue); + + // test multiply by 0 + arguments.clear(); + arguments.add(attr1); + arguments.add(attr0); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:double-divide Divide by 0 error: 1.5, 0.0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + + + @Test + public void testInteger_mod() { + + FunctionArgumentAttributeValue attr0 = null; + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + try { + attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(28)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(5)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_INTEGER_MOD; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_INTEGER_MOD, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + + // test normal + arguments.add(attr1); + arguments.add(attr2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + BigInteger resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("3"), resValue); + + + // test 0 + arguments.clear(); + arguments.add(attr1); + arguments.add(attr0); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:integer-mod Divide by 0 error: 28, 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + @Test + public void testInteger_abs() { + + FunctionArgumentAttributeValue attr0 = null; + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attrM1 = null; + try { + attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(5)); + attrM1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(-7)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_INTEGER_ABS; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_INTEGER_ABS, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + + // test normal + arguments.add(attr1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + BigInteger resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("5"), resValue); + + arguments.clear(); + arguments.add(attrM1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("7"), resValue); + + arguments.clear(); + arguments.add(attr0); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("0"), resValue); + } + + + @Test + public void testDouble_abs() { + + FunctionArgumentAttributeValue attr0 = null; + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + + try { + attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(0)); + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.5)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-2.5)); + + } catch (Exception e) { + fail("creating attributes e="+e); + } + + FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_DOUBLE_ABS; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DOUBLE_ABS, fd.getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + + // test normal + arguments.add(attr1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Double resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(1.5), resValue); + + arguments.clear(); + arguments.add(attr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(2.5), resValue); + + arguments.clear(); + arguments.add(attr0); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(0), resValue); + + } + + + @Test + public void testDouble_round() { + + FunctionArgumentAttributeValue attr0 = null; + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + FunctionArgumentAttributeValue attr3 = null; + FunctionArgumentAttributeValue attr4 = null; + FunctionArgumentAttributeValue attr5 = null; + FunctionArgumentAttributeValue attr6 = null; + try { + attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(0)); + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.5)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.49)); + attr3 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.51)); + attr4 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-2.5)); + attr5 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-2.49)); + attr6 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-2.51)); + } catch (Exception e) { + fail("creating attributes e="+e); + } + + + + FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_ROUND; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_ROUND, fd.getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + + // test normal + arguments.add(attr0); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Double resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(0), resValue); + + arguments.clear(); + arguments.add(attr1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(2), resValue); + + arguments.clear(); + arguments.add(attr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(1), resValue); + + arguments.clear(); + arguments.add(attr3); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(2), resValue); + + arguments.clear(); + arguments.add(attr4); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(-2), resValue); + + arguments.clear(); + arguments.add(attr5); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(-2), resValue); + + arguments.clear(); + arguments.add(attr6); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(-3), resValue); + } + + + @Test + public void testDouble_floor() { + FunctionArgumentAttributeValue attr0 = null; + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + FunctionArgumentAttributeValue attr3 = null; + FunctionArgumentAttributeValue attr4 = null; + FunctionArgumentAttributeValue attr5 = null; + FunctionArgumentAttributeValue attr6 = null; + try { + attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(0)); + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.5)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.49)); + attr3 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.51)); + attr4 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-2.5)); + attr5 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-2.49)); + attr6 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-2.51)); + } catch (Exception e) { + fail("creating attributes e="+e); + } + + FunctionDefinitionArithmetic fd = (FunctionDefinitionArithmetic) StdFunctions.FD_FLOOR; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_FLOOR, fd.getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + + // test normal + arguments.add(attr0); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Double resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(0), resValue); + + arguments.clear(); + arguments.add(attr1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(1), resValue); + + arguments.clear(); + arguments.add(attr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(1), resValue); + + arguments.clear(); + arguments.add(attr3); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(1), resValue); + + arguments.clear(); + arguments.add(attr4); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(-3), resValue); + + arguments.clear(); + arguments.add(attr5); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(-3), resValue); + + arguments.clear(); + arguments.add(attr6); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(-3), resValue); + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagIsInTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagIsInTest.java new file mode 100644 index 000000000..09fd95f05 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagIsInTest.java @@ -0,0 +1,221 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.StdAttributeValue; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.Bag; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentBag; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionBagIsInTest { + + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + + @Test + public void testString() { + String v1 = new String("abc"); + String v2 = new String("def"); + String notInBag = new String("lmnop"); + String sameValueV1 = new String("abc"); + Integer vOtherType = new Integer(11); + + + FunctionArgumentAttributeValue attrV1 = null; + FunctionArgumentAttributeValue attrV2 = null; + FunctionArgumentAttributeValue attrNotInBag = null; + FunctionArgumentAttributeValue attrSameValueV1 = null; + FunctionArgumentAttributeValue attrOtherType = null; + try { + attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); + attrV2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v2)); + attrNotInBag = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(notInBag)); + attrSameValueV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(sameValueV1)); + attrOtherType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(vOtherType)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + Bag bag0 = new Bag(); + Bag bag1 = new Bag(); + bag1.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v1)); + Bag bag2 = new Bag(); + bag2.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v1)); + bag2.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v2));; + + + + FunctionArgumentBag attrBag0 = new FunctionArgumentBag(bag0); + FunctionArgumentBag attrBag1 = new FunctionArgumentBag(bag1); + FunctionArgumentBag attrBag2 = new FunctionArgumentBag(bag2); + + + + FunctionDefinitionBagIsIn fd = (FunctionDefinitionBagIsIn) StdFunctions.FD_STRING_IS_IN; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_IS_IN, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // element is in bag + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBag2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // element not in bag + arguments.clear(); + arguments.add(attrNotInBag); + arguments.add(attrBag2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // different element with the same value is in bag + arguments.clear(); + arguments.add(attrSameValueV1); + arguments.add(attrBag2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // empty bag + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBag0); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // missing arg + arguments.clear(); + arguments.add(attrSameValueV1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-is-in Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // 1st arg is bag + arguments.clear(); + arguments.add(attrBag1); + arguments.add(attrBag2); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-is-in Expected a simple value, saw a bag", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // 2nd arg not bag + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrV2); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-is-in Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // first arg null + arguments.clear(); + arguments.add(null); + arguments.add(attrBag2); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-is-in Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // 2nd arg null + arguments.clear(); + arguments.add(attrV1); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-is-in Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // first arg type does not match bag elements + arguments.clear(); + arguments.add(attrOtherType); + arguments.add(attrBag2); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-is-in Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bag has mixed element types +// behavior not specified for this case in spec. It ASSUMES that all elements in bag are same type. + + } + + + + + // + // + // REST OF DATA TYPES OMITTED + // because they "should" all work the same + // + // + + + + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagOneAndOnlyTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagOneAndOnlyTest.java new file mode 100644 index 000000000..192747aec --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagOneAndOnlyTest.java @@ -0,0 +1,224 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; +import java.math.BigInteger; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.StdAttributeValue; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.Bag; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentBag; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionBagOneAndOnlyTest { + + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + + @Test + public void testString() { + String v1 = new String("abc"); + String v2 = new String("def"); + BigInteger vOtherType = BigInteger.valueOf(11); + + Bag bag0 = new Bag(); + Bag bag1 = new Bag(); + bag1.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v1)); + Bag bag2 = new Bag(); + bag2.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v1)); + bag2.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v2)); + Bag bagOtherType = new Bag(); + bagOtherType.add(new StdAttributeValue(DataTypes.DT_INTEGER.getId(), vOtherType)); + + FunctionArgumentBag attrBag0 = new FunctionArgumentBag(bag0); + FunctionArgumentBag attrBag1 = new FunctionArgumentBag(bag1); + FunctionArgumentBag attrBag2 = new FunctionArgumentBag(bag2); + FunctionArgumentBag attrBagOtherType = new FunctionArgumentBag(bagOtherType); + + + FunctionDefinitionBagOneAndOnly fd = (FunctionDefinitionBagOneAndOnly) StdFunctions.FD_STRING_ONE_AND_ONLY; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_ONE_AND_ONLY, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + + + // bag with only one + arguments.clear(); + arguments.add(attrBag1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + String resValue = (String)res.getValue().getValue(); + assertEquals(v1, resValue); + + // null bag + arguments.clear(); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-one-and-only Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bag with exactly one but of other type in it + arguments.clear(); + arguments.add(attrBagOtherType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-one-and-only Element in bag of wrong type. Expected string got integer", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bag with none + arguments.clear(); + arguments.add(attrBag0); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-one-and-only Expected 1 but Bag has 0 elements", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bag with multiple + arguments.clear(); + arguments.add(attrBag2); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-one-and-only Expected 1 but Bag has 2 elements", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + @Test + public void testBoolean() { + Boolean v1 = new Boolean(true); + Boolean v2 = new Boolean(false); + BigInteger vOtherType = BigInteger.valueOf(11); + + Bag bag0 = new Bag(); + Bag bag1 = new Bag(); + bag1.add(new StdAttributeValue(DataTypes.DT_BOOLEAN.getId(), v1)); + Bag bag2 = new Bag(); + bag2.add(new StdAttributeValue(DataTypes.DT_BOOLEAN.getId(), v1)); + bag2.add(new StdAttributeValue(DataTypes.DT_BOOLEAN.getId(), v2)); + Bag bagOtherType = new Bag(); + bagOtherType.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), vOtherType)); + + + FunctionArgumentBag attrBag0 = new FunctionArgumentBag(bag0); + FunctionArgumentBag attrBag1 = new FunctionArgumentBag(bag1); + FunctionArgumentBag attrBag2 = new FunctionArgumentBag(bag2); + FunctionArgumentBag attrBagOtherType = new FunctionArgumentBag(bagOtherType); + + + FunctionDefinitionBagOneAndOnly fd = (FunctionDefinitionBagOneAndOnly) StdFunctions.FD_BOOLEAN_ONE_AND_ONLY; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_BOOLEAN_ONE_AND_ONLY, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + + + // bag with only one + arguments.clear(); + arguments.add(attrBag1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(true), resValue); + + // null bag + arguments.clear(); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:boolean-one-and-only Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bag with exactly one but of other type in it + arguments.clear(); + arguments.add(attrBagOtherType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:boolean-one-and-only Element in bag of wrong type. Expected boolean got string", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bag with none + arguments.clear(); + arguments.add(attrBag0); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:boolean-one-and-only Expected 1 but Bag has 0 elements", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bag with multiple + arguments.clear(); + arguments.add(attrBag2); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:boolean-one-and-only Expected 1 but Bag has 2 elements", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + // + // + // REST OF DATA TYPES OMITTED + // because they "should" all work the same + // + // + + + + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagSizeTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagSizeTest.java new file mode 100644 index 000000000..f2bcbc5c2 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagSizeTest.java @@ -0,0 +1,158 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.StdAttributeValue; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.Bag; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentBag; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionBagSizeTest { + + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + + @Test + public void testString() { + String v1 = new String("abc"); + String v2 = new String("def"); + Integer vOtherType = new Integer(11); + + + + Bag bag0 = new Bag(); + Bag bag1 = new Bag(); + bag1.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v1)); + Bag bag2 = new Bag(); + bag2.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v1)); + bag2.add(new StdAttributeValue(DataTypes.DT_STRING.getId(), v2)); + Bag bagOtherType = new Bag(); + bagOtherType.add(new StdAttributeValue(DataTypes.DT_INTEGER.getId(), vOtherType)); + + + FunctionArgumentBag attrBag0 = new FunctionArgumentBag(bag0); + FunctionArgumentBag attrBag1 = new FunctionArgumentBag(bag1); + FunctionArgumentBag attrBag2 = new FunctionArgumentBag(bag2); + FunctionArgumentBag attrBagOtherType = new FunctionArgumentBag(bagOtherType); + + + FunctionDefinitionBagSize fd = (FunctionDefinitionBagSize) StdFunctions.FD_STRING_BAG_SIZE; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_BAG_SIZE, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + + + // bag with only one + arguments.clear(); + arguments.add(attrBag1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.math.BigInteger.class, res.getValue().getValue().getClass()); + BigInteger resValue = (BigInteger)res.getValue().getValue(); + assertEquals(BigInteger.valueOf(1), resValue); + + // null bag + arguments.clear(); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-bag-size Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bag with exactly one but of other type in it + arguments.clear(); + arguments.add(attrBagOtherType); + res = fd.evaluate(null, arguments); + // NOTE: Size does not care about content type! + assertTrue(res.isOk()); + assertEquals(java.math.BigInteger.class, res.getValue().getValue().getClass()); + resValue = (BigInteger)res.getValue().getValue(); + assertEquals(BigInteger.valueOf(1), resValue); + + // bag with none + arguments.clear(); + arguments.add(attrBag0); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.math.BigInteger.class, res.getValue().getValue().getClass()); + resValue = (BigInteger)res.getValue().getValue(); + assertEquals(BigInteger.valueOf(0), resValue); + + // bag with multiple + arguments.clear(); + arguments.add(attrBag2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.math.BigInteger.class, res.getValue().getValue().getClass()); + resValue = (BigInteger)res.getValue().getValue(); + assertEquals(BigInteger.valueOf(2), resValue); + } + + + + + + + + // + // + // REST OF DATA TYPES OMITTED + // because they "should" all work the same + // + // + + + + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagTest.java new file mode 100644 index 000000000..d96bd273f --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBagTest.java @@ -0,0 +1,547 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.junit.Test; + +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.Bag; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionBagTest { + + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + + FunctionArgumentAttributeValue attrInteger = null; + FunctionArgumentAttributeValue attrString = null; + + public FunctionDefinitionBagTest() { + try { + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1111111111)); + attrString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("a string value")); + } catch (Exception e) { + fail("creating attributes e="+e); + } + } + + @Test + public void testString() { + + String s1 = "abc"; + String s2 = "def"; + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + try { + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(s1)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(s2)); + } catch (Exception e) { + fail("creating attributes e="+e); + } + + FunctionDefinitionBag fd = (FunctionDefinitionBag) StdFunctions.FD_STRING_BAG; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_BAG, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertTrue(fd.returnsBag()); + + // bag with only one + arguments.clear(); + arguments.add(attr1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Bag bag = res.getBag(); + assertNotNull(bag); + Iterator> it = bag.getAttributeValues(); + assertEquals(1, bag.size()); + AttributeValue attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + + // zero args => empty bag + arguments.clear(); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + assertEquals(0, bag.size()); + + + // null argument + arguments.clear(); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-bag Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // argument of other type + arguments.clear(); + arguments.add(attrInteger); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-bag Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // 2 args (check response is correct) + arguments.clear(); + arguments.add(attr1); + arguments.add(attr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(2, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(s2, attrValueObject.getValue()); + + // duplicate args (verify return) + arguments.clear(); + arguments.add(attr1); + arguments.add(attr2); + arguments.add(attr1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(3, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(s2, attrValueObject.getValue()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + + // lots of args + arguments.clear(); + for (int i = 0; i < 1000; i++) { + arguments.add(attr1); + } + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(1000, bag.size()); + + } + + + @Test + public void testBoolean() { + + Boolean s1 = true; + Boolean s2 = false; + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + try { + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(s1)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(s2)); + } catch (Exception e) { + fail("creating attributes e="+e); + } + + FunctionDefinitionBag fd = (FunctionDefinitionBag) StdFunctions.FD_BOOLEAN_BAG; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_BOOLEAN_BAG, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertTrue(fd.returnsBag()); + + // bag with only one + arguments.clear(); + arguments.add(attr1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Bag bag = res.getBag(); + assertNotNull(bag); + Iterator> it = bag.getAttributeValues(); + assertEquals(1, bag.size()); + AttributeValue attrValueObject = it.next(); + assertEquals(DataTypes.DT_BOOLEAN.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + + // zero args => empty bag + arguments.clear(); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + assertEquals(0, bag.size()); + + + // null argument + arguments.clear(); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:boolean-bag Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // argument of other type + arguments.clear(); + arguments.add(attrInteger); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:boolean-bag Expected data type 'boolean' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // 2 args (check response is correct) + arguments.clear(); + arguments.add(attr1); + arguments.add(attr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(2, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_BOOLEAN.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_BOOLEAN.getId(), attrValueObject.getDataTypeId()); + assertEquals(s2, attrValueObject.getValue()); + + // duplicate args (verify return) + arguments.clear(); + arguments.add(attr1); + arguments.add(attr2); + arguments.add(attr1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(3, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_BOOLEAN.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_BOOLEAN.getId(), attrValueObject.getDataTypeId()); + assertEquals(s2, attrValueObject.getValue()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_BOOLEAN.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + + // lots of args + arguments.clear(); + for (int i = 0; i < 1000; i++) { + arguments.add(attr1); + } + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(1000, bag.size()); + + } + + + + @Test + public void testInteger() { + + BigInteger s1 = new BigInteger("123"); + BigInteger s2 = new BigInteger("456"); + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + try { + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(s1)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(s2)); + } catch (Exception e) { + fail("creating attributes e="+e); + } + + FunctionDefinitionBag fd = (FunctionDefinitionBag) StdFunctions.FD_INTEGER_BAG; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_INTEGER_BAG, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertTrue(fd.returnsBag()); + + // bag with only one + arguments.clear(); + arguments.add(attr1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Bag bag = res.getBag(); + assertNotNull(bag); + Iterator> it = bag.getAttributeValues(); + assertEquals(1, bag.size()); + AttributeValue attrValueObject = it.next(); + assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + + // zero args => empty bag + arguments.clear(); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + assertEquals(0, bag.size()); + + + // null argument + arguments.clear(); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:integer-bag Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // argument of other type + arguments.clear(); + arguments.add(attrString); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:integer-bag Expected data type 'integer' saw 'string'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // 2 args (check response is correct) + arguments.clear(); + arguments.add(attr1); + arguments.add(attr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(2, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); + assertEquals(s2, attrValueObject.getValue()); + + // duplicate args (verify return) + arguments.clear(); + arguments.add(attr1); + arguments.add(attr2); + arguments.add(attr1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(3, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); + assertEquals(s2, attrValueObject.getValue()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + + // lots of args + arguments.clear(); + for (int i = 0; i < 1000; i++) { + arguments.add(attr1); + } + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(1000, bag.size()); + + } + + + + + @Test + public void testDouble() { + + Double s1 = 123.45; + Double s2 = 678.901; + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr2 = null; + try { + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(s1)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(s2)); + } catch (Exception e) { + fail("creating attributes e="+e); + } + + FunctionDefinitionBag fd = (FunctionDefinitionBag) StdFunctions.FD_DOUBLE_BAG; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DOUBLE_BAG, fd.getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertTrue(fd.returnsBag()); + + // bag with only one + arguments.clear(); + arguments.add(attr1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Bag bag = res.getBag(); + assertNotNull(bag); + Iterator> it = bag.getAttributeValues(); + assertEquals(1, bag.size()); + AttributeValue attrValueObject = it.next(); + assertEquals(DataTypes.DT_DOUBLE.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + + // zero args => empty bag + arguments.clear(); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + assertEquals(0, bag.size()); + + + // null argument + arguments.clear(); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:double-bag Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // argument of other type + arguments.clear(); + arguments.add(attrInteger); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:double-bag Expected data type 'double' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // 2 args (check response is correct) + arguments.clear(); + arguments.add(attr1); + arguments.add(attr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(2, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_DOUBLE.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_DOUBLE.getId(), attrValueObject.getDataTypeId()); + assertEquals(s2, attrValueObject.getValue()); + + // duplicate args (verify return) + arguments.clear(); + arguments.add(attr1); + arguments.add(attr2); + arguments.add(attr1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(3, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_DOUBLE.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_DOUBLE.getId(), attrValueObject.getDataTypeId()); + assertEquals(s2, attrValueObject.getValue()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_DOUBLE.getId(), attrValueObject.getDataTypeId()); + assertEquals(s1, attrValueObject.getValue()); + + // lots of args + arguments.clear(); + for (int i = 0; i < 1000; i++) { + arguments.add(attr1); + } + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(1000, bag.size()); + + } + + + + + + // + // + // REST OF DATA TYPES OMITTED + // because they "should" all work the same + // + // + + + + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBaseTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBaseTest.java new file mode 100644 index 000000000..334226c84 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionBaseTest.java @@ -0,0 +1,131 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacmlatt.pdp.policy.FunctionDefinition; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test functions in the abstract FunctionDefinitionSimpleTest class. + * Functions are tested by creating instances of other classes that should have appropriate properties to verify all variations of the responses expected. + * + * Note: we do not test getDataTypeId() because all it does is get the String out of the Identity object and we assume that the Data Type Identity objects + * are tested enough in everything else that any errors in them will be found and fixed quickly. + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionBaseTest { + /** + * getId() is pretty trivial, so verifying one should be enough to check that the mechanism is working ok + */ + @Test + public void testGetId() { + FunctionDefinition fd = StdFunctions.FD_STRING_EQUAL; + Identifier id = fd.getId(); + assertTrue(XACML3.ID_FUNCTION_STRING_EQUAL.stringValue().equals(id.stringValue()) ); + } + + /** + * check an instance of every result type that we can deal with + */ + @Test + public void testGetDataType() { + +//?? Need functions that return each of these data types except for Boolean which is returned by any of the EQUAL functions + FunctionDefinition fdstring = StdFunctions.FD_STRING_NORMALIZE_SPACE; + assertEquals(XACML3.ID_DATATYPE_STRING, fdstring.getDataTypeId()); + + FunctionDefinition fdboolean = StdFunctions.FD_STRING_EQUAL; + assertEquals(XACML3.ID_DATATYPE_BOOLEAN, fdboolean.getDataTypeId()); + + FunctionDefinition fdinteger = StdFunctions.FD_INTEGER_ADD; + assertEquals(XACML3.ID_DATATYPE_INTEGER, fdinteger.getDataTypeId()); + + FunctionDefinition fddouble = StdFunctions.FD_DOUBLE_ADD; + assertEquals(XACML3.ID_DATATYPE_DOUBLE, fddouble.getDataTypeId()); + + FunctionDefinition fddate = StdFunctions.FD_DATE_BAG; + assertEquals(XACML3.ID_DATATYPE_DATE, fddate.getDataTypeId()); + + FunctionDefinition fdtime = StdFunctions.FD_TIME_BAG; + assertEquals(XACML3.ID_DATATYPE_TIME, fdtime.getDataTypeId()); + + FunctionDefinition fddateTime = StdFunctions.FD_DATETIME_BAG; + assertEquals(XACML3.ID_DATATYPE_DATETIME, fddateTime.getDataTypeId()); + + FunctionDefinition fddayTimeDuration = StdFunctions.FD_DAYTIMEDURATION_FROM_STRING; + assertEquals(XACML3.ID_DATATYPE_DAYTIMEDURATION, fddayTimeDuration.getDataTypeId()); + + FunctionDefinition fdyearMonthDuration = StdFunctions.FD_YEARMONTHDURATION_FROM_STRING; + assertEquals(XACML3.ID_DATATYPE_YEARMONTHDURATION, fdyearMonthDuration.getDataTypeId()); + + FunctionDefinition fdanyURI = StdFunctions.FD_ANYURI_FROM_STRING; + assertEquals(XACML3.ID_DATATYPE_ANYURI, fdanyURI.getDataTypeId()); + + FunctionDefinition fdhexBinary = StdFunctions.FD_HEXBINARY_UNION; + assertEquals(XACML3.ID_DATATYPE_HEXBINARY, fdhexBinary.getDataTypeId()); + + FunctionDefinition fdbase64Binary = StdFunctions.FD_BASE64BINARY_UNION; + assertEquals(XACML3.ID_DATATYPE_BASE64BINARY, fdbase64Binary.getDataTypeId()); + + FunctionDefinition fdrfc822Name = StdFunctions.FD_RFC822NAME_FROM_STRING; + assertEquals(XACML3.ID_DATATYPE_RFC822NAME, fdrfc822Name.getDataTypeId()); + + FunctionDefinition fdx500Name = StdFunctions.FD_X500NAME_FROM_STRING; + assertEquals(XACML3.ID_DATATYPE_X500NAME, fdx500Name.getDataTypeId()); + +//TODO - There are currently no functions that return XPathExpression objects +// FunctionDefinition fdxpathExpression = StdFunctions.FD_XPATHEXPRESSION_FROM_STRING; +// assertEquals(XACML3.ID_DATATYPE_XPATHEXPRESSION, fdxpathExpression.getDataTypeId()); + + FunctionDefinition fdipAddress = StdFunctions.FD_IPADDRESS_FROM_STRING; + assertEquals(XACML3.ID_DATATYPE_IPADDRESS, fdipAddress.getDataTypeId()); + + FunctionDefinition fddnsName = StdFunctions.FD_DNSNAME_FROM_STRING; + assertEquals(XACML3.ID_DATATYPE_DNSNAME, fddnsName.getDataTypeId()); + } + + /** + * check the type of return, single vs multiple values + */ + @Test + public void testReturnsBag() { + FunctionDefinition fdNotBag = StdFunctions.FD_BOOLEAN_EQUAL; + assertFalse(fdNotBag.returnsBag()); + + FunctionDefinitionBag fdBag = (FunctionDefinitionBag) StdFunctions.FD_STRING_BAG; + assertTrue(fdBag.returnsBag()); + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionComparisonTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionComparisonTest.java new file mode 100644 index 000000000..4cd558536 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionComparisonTest.java @@ -0,0 +1,1366 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacml.std.datatypes.ISO8601Date; +import com.att.research.xacml.std.datatypes.ISO8601DateTime; +import com.att.research.xacml.std.datatypes.ISO8601Time; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test FunctionDefinitionComparison + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionComparisonTest { + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + FunctionArgumentAttributeValue stringAttr1 = null; + FunctionArgumentAttributeValue stringAttr1a = null; + FunctionArgumentAttributeValue stringAttr2 = null; + FunctionArgumentAttributeValue stringAttrNeg1 = null; + + + FunctionArgumentAttributeValue intAttr1 = null; + FunctionArgumentAttributeValue intAttr1a = null; + FunctionArgumentAttributeValue intAttr2 = null; + FunctionArgumentAttributeValue intAttr0 = null; + FunctionArgumentAttributeValue intAttrNeg1 = null; + + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr1a = null; + FunctionArgumentAttributeValue attr2 = null; + FunctionArgumentAttributeValue attrNeg1 = null; + + FunctionArgumentAttributeValue attrDateToday = null; + FunctionArgumentAttributeValue attrDateSameDay = null; + FunctionArgumentAttributeValue attrDateTommorrow = null; + FunctionArgumentAttributeValue attrDateYesterday = null; + FunctionArgumentAttributeValue attrDateWithTimeZone = null; + FunctionArgumentAttributeValue attrDateNoTimeZone = null; + + + FunctionArgumentAttributeValue attrTimeToday = null; + FunctionArgumentAttributeValue attrTimeSameDay = null; + FunctionArgumentAttributeValue attrTimeTommorrow = null; + FunctionArgumentAttributeValue attrTimeYesterday = null; + FunctionArgumentAttributeValue attrTimeWithTimeZone = null; + FunctionArgumentAttributeValue attrTimeNoTimeZone = null; + + FunctionArgumentAttributeValue attrDateTimeToday = null; + FunctionArgumentAttributeValue attrDateTimeSameDay = null; + FunctionArgumentAttributeValue attrDateTimeTommorrow = null; + FunctionArgumentAttributeValue attrDateTimeYesterday = null; + FunctionArgumentAttributeValue attrDateTimeWithTimeZone = null; + FunctionArgumentAttributeValue attrDateTimeNoTimeZone = null; + + /** + * Set up some common variables on startup + */ + public FunctionDefinitionComparisonTest() { + try { + stringAttr1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc")); + stringAttr1a = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc")); + stringAttr2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("def")); + stringAttrNeg1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("AAA")); + + + intAttr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); + intAttr1a = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); + intAttr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(2)); + intAttr0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); + intAttrNeg1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(-1)); + + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.0)); + attr1a = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.0)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(2.4)); + attrNeg1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-1.0)); + + // create dates + Calendar calendar = Calendar.getInstance(); + Date today = calendar.getTime(); + Date longAgo = new Date(1234); + // create a date that is different than "today" but within the same day (i.e. has a different hour) + if (calendar.get(Calendar.HOUR_OF_DAY) > 3) { + calendar.set(Calendar.HOUR_OF_DAY, 3); + } else { + calendar.set(Calendar.HOUR_OF_DAY, 5); + } + Date todayPlus = calendar.getTime(); + calendar.add(Calendar.DATE, 1); + Date tommorrow = calendar.getTime(); + attrDateToday = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(today)); + attrDateSameDay = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(todayPlus)); + attrDateTommorrow = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(tommorrow)); + attrDateYesterday = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(longAgo)); + ISO8601Date isoDate = new ISO8601Date(1920, 5, 8); + attrDateNoTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(isoDate)); + isoDate = new ISO8601Date("GMT+00:02", 1920, 5, 8); + attrDateWithTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(isoDate)); + + // create Times + ISO8601Time isoTime = new ISO8601Time(14, 43, 12, 145); + attrTimeToday = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(isoTime)); + attrTimeSameDay = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(isoTime)); + isoTime = new ISO8601Time(18, 53, 34, 423); + attrTimeTommorrow = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(isoTime)); + isoTime = new ISO8601Time(7, 34, 6,543); + attrTimeYesterday = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(isoTime)); + isoTime = new ISO8601Time(12, 12, 12, 12); + attrTimeNoTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(isoTime)); + isoTime = new ISO8601Time("GMT:+00:03", 12, 12, 12, 12); + attrTimeWithTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(isoTime)); + + // create DateTimes + isoDate = new ISO8601Date(1920, 5, 8); + isoTime = new ISO8601Time( 18, 53, 34, 423); + ISO8601DateTime isoDateTime = new ISO8601DateTime((String)null, 1920, 5, 8, 18, 53, 34, 423); + attrDateTimeToday = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(isoDateTime)); + attrDateTimeSameDay = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(isoDateTime)); + isoTime = new ISO8601Time(20, 53, 34, 423); + isoDateTime = new ISO8601DateTime((String)null, 1920, 5, 8, 20, 53, 34, 423); + attrDateTimeTommorrow = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(isoDateTime)); + isoTime = new ISO8601Time(7, 34, 6,543); + isoDateTime = new ISO8601DateTime((String)null, 1920, 5, 8, 7, 34, 6, 543); + attrDateTimeYesterday = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(isoDateTime)); + isoTime = new ISO8601Time(12, 12, 12, 12); + isoDateTime = new ISO8601DateTime((String)null, 1920, 5, 8, 12, 12, 12, 12); + attrDateTimeNoTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(isoDateTime)); + isoTime = new ISO8601Time("GMT:+00:03", 12, 12, 12, 12); + isoDate = new ISO8601Date("GMT:+00:03", 1920, 5, 8); + isoDateTime = new ISO8601DateTime("GMT:+00:03", 1920, 5, 8, 12, 12, 12, 12); + attrDateTimeWithTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(isoDateTime)); + + + + + } catch (Exception e) { + fail("Error creating values e="+ e); + } + } + + /** + * String + */ + @Test + public void testString_GT() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_STRING_GREATER_THAN; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_GREATER_THAN, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(stringAttr1); + arguments.add(stringAttr1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // check first < second + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(stringAttr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first > second + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(stringAttrNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(intAttr1); + arguments.add(stringAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + } + + @Test + public void testString_GTE() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_STRING_GREATER_THAN_OR_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_GREATER_THAN_OR_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(stringAttr1); + arguments.add(stringAttr1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check first < second + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(stringAttr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first > second + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(stringAttrNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + } + + @Test + public void testString_LT() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_STRING_LESS_THAN; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_LESS_THAN, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(stringAttr1); + arguments.add(stringAttr1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // check first < second + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(stringAttr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first > second + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(stringAttrNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + } + + @Test + public void testString_LTE() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_STRING_LESS_THAN_OR_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_LESS_THAN_OR_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(stringAttr1); + arguments.add(stringAttr1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check first < second + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(stringAttr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first > second + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(stringAttrNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + } + + + + /** + * Integer + */ + @Test + public void testInteger_GT() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_INTEGER_GREATER_THAN; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_INTEGER_GREATER_THAN, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(intAttr1); + arguments.add(intAttr1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // check first < second + arguments.clear(); + arguments.add(intAttr1); + arguments.add(intAttr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first > second + arguments.clear(); + arguments.add(intAttr1); + arguments.add(intAttrNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + } + + @Test + public void testInteger_GTE() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_INTEGER_GREATER_THAN_OR_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_INTEGER_GREATER_THAN_OR_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(intAttr1); + arguments.add(intAttr1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check first < second + arguments.clear(); + arguments.add(intAttr1); + arguments.add(intAttr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first > second + arguments.clear(); + arguments.add(intAttr1); + arguments.add(intAttrNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + } + + @Test + public void testInteger_LT() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_INTEGER_LESS_THAN; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_INTEGER_LESS_THAN, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(intAttr1); + arguments.add(intAttr1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // check first < second + arguments.clear(); + arguments.add(intAttr1); + arguments.add(intAttr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first > second + arguments.clear(); + arguments.add(intAttr1); + arguments.add(intAttrNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + } + + @Test + public void testInteger_LTE() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_INTEGER_LESS_THAN_OR_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_INTEGER_LESS_THAN_OR_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(intAttr1); + arguments.add(intAttr1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check first < second + arguments.clear(); + arguments.add(intAttr1); + arguments.add(intAttr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first > second + arguments.clear(); + arguments.add(intAttr1); + arguments.add(intAttrNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + } + + + + + /** + * Double + */ + @Test + public void testDouble_GT() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DOUBLE_GREATER_THAN; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DOUBLE_GREATER_THAN, fd.getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attr1); + arguments.add(attr1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first < second + arguments.clear(); + arguments.add(attr1); + arguments.add(attr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first > second + arguments.clear(); + arguments.add(attr1); + arguments.add(attrNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + @Test + public void testDouble_GTE() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DOUBLE_GREATER_THAN_OR_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DOUBLE_GREATER_THAN_OR_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attr1); + arguments.add(attr1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first < second + arguments.clear(); + arguments.add(attr1); + arguments.add(attr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first > second + arguments.clear(); + arguments.add(attr1); + arguments.add(attrNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + } + + @Test + public void testDouble_LT() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DOUBLE_LESS_THAN; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DOUBLE_LESS_THAN, fd.getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attr1); + arguments.add(attr1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first < second + arguments.clear(); + arguments.add(attr1); + arguments.add(attr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first > second + arguments.clear(); + arguments.add(attr1); + arguments.add(attrNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + } + + @Test + public void testDouble_LTE() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DOUBLE_LESS_THAN_OR_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DOUBLE_LESS_THAN_OR_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attr1); + arguments.add(attr1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first < second + arguments.clear(); + arguments.add(attr1); + arguments.add(attr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first > second + arguments.clear(); + arguments.add(attr1); + arguments.add(attrNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + } + + + + /** + * Date + */ + + @Test + public void testDate_GT() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATE_GREATER_THAN; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATE_GREATER_THAN, fd.getId()); + assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attrDateToday); + arguments.add(attrDateSameDay); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first < second + arguments.clear(); + arguments.add(attrDateToday); + arguments.add(attrDateTommorrow); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first > second + arguments.clear(); + arguments.add(attrDateToday); + arguments.add(attrDateYesterday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // test bad args data types? One with TimeZone and one without + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + // test with TimeZone vs without + arguments.clear(); + arguments.add(attrDateWithTimeZone); + arguments.add(attrDateNoTimeZone); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-greater-than Cannot compare this ISO8601DateTime with non-time-zoned ISO8601DateTime", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + } + + @Test + public void testDate_GTE() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATE_GREATER_THAN_OR_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATE_GREATER_THAN_OR_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attrDateToday); + arguments.add(attrDateSameDay); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first < second + arguments.clear(); + arguments.add(attrDateToday); + arguments.add(attrDateTommorrow); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first > second + arguments.clear(); + arguments.add(attrDateToday); + arguments.add(attrDateYesterday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + } + + @Test + public void testDate_LT() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATE_LESS_THAN; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATE_LESS_THAN, fd.getId()); + assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attrDateToday); + arguments.add(attrDateSameDay); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first < second + arguments.clear(); + arguments.add(attrDateToday); + arguments.add(attrDateTommorrow); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first > second + arguments.clear(); + arguments.add(attrDateToday); + arguments.add(attrDateYesterday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + } + + @Test + public void testDate_LTE() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATE_LESS_THAN_OR_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATE_LESS_THAN_OR_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attrDateToday); + arguments.add(attrDateSameDay); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first < second + arguments.clear(); + arguments.add(attrDateToday); + arguments.add(attrDateTommorrow); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first > second + arguments.clear(); + arguments.add(attrDateToday); + arguments.add(attrDateYesterday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + } + + + + + + + + /** + * Time + */ + + @Test + public void testTime_GT() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_TIME_GREATER_THAN; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_TIME_GREATER_THAN, fd.getId()); + assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attrTimeToday); + arguments.add(attrTimeSameDay); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first < second + arguments.clear(); + arguments.add(attrTimeToday); + arguments.add(attrTimeTommorrow); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first > second + arguments.clear(); + arguments.add(attrTimeToday); + arguments.add(attrTimeYesterday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // test bad args data types? One with TimeZone and one without + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + // test with TimeZone vs without + arguments.clear(); + arguments.add(attrTimeWithTimeZone); + arguments.add(attrTimeNoTimeZone); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:time-greater-than Cannot compare this ISO8601DateTime with non-time-zoned ISO8601DateTime", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + } + + @Test + public void testTime_GTE() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_TIME_GREATER_THAN_OR_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_TIME_GREATER_THAN_OR_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attrTimeToday); + arguments.add(attrTimeSameDay); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first < second + arguments.clear(); + arguments.add(attrTimeToday); + arguments.add(attrTimeTommorrow); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first > second + arguments.clear(); + arguments.add(attrTimeToday); + arguments.add(attrTimeYesterday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + } + + @Test + public void testTime_LT() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_TIME_LESS_THAN; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_TIME_LESS_THAN, fd.getId()); + assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attrTimeToday); + arguments.add(attrTimeSameDay); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first < second + arguments.clear(); + arguments.add(attrTimeToday); + arguments.add(attrTimeTommorrow); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first > second + arguments.clear(); + arguments.add(attrTimeToday); + arguments.add(attrTimeYesterday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + } + + @Test + public void testTime_LTE() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_TIME_LESS_THAN_OR_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_TIME_LESS_THAN_OR_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attrTimeToday); + arguments.add(attrTimeSameDay); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first < second + arguments.clear(); + arguments.add(attrTimeToday); + arguments.add(attrTimeTommorrow); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first > second + arguments.clear(); + arguments.add(attrTimeToday); + arguments.add(attrTimeYesterday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + } + + + + + + /** + * Time-in-range + */ + @Test + public void testTime_in_range() { + + FunctionDefinitionTimeInRange fd = (FunctionDefinitionTimeInRange) StdFunctions.FD_TIME_IN_RANGE; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_TIME_IN_RANGE, fd.getId()); + assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(3), fd.getNumArgs()); + + // arg 0 in range of others + arguments.add(attrTimeToday); + arguments.add(attrTimeYesterday); + arguments.add(attrTimeTommorrow); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // below range + arguments.clear(); + arguments.add(attrTimeYesterday); + arguments.add(attrTimeToday); + arguments.add(attrTimeTommorrow); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // above range + arguments.clear(); + arguments.add(attrTimeTommorrow); + arguments.add(attrTimeYesterday); + arguments.add(attrTimeToday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // range bad + arguments.clear(); + arguments.add(attrTimeToday); + arguments.add(attrTimeTommorrow); + arguments.add(attrTimeYesterday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // bad types + arguments.clear(); + arguments.add(attrDateTimeWithTimeZone); + arguments.add(attrDateTimeNoTimeZone); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:time-in-range Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrDateTimeWithTimeZone); + arguments.add(attrDateTimeNoTimeZone); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:time-in-range Expected data type 'time' saw 'dateTime' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + + + /** + * DateTime + */ + + @Test + public void testDateTime_GT() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATETIME_GREATER_THAN; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATETIME_GREATER_THAN, fd.getId()); + assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attrDateTimeToday); + arguments.add(attrDateTimeSameDay); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first < second + arguments.clear(); + arguments.add(attrDateTimeToday); + arguments.add(attrDateTimeTommorrow); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first > second + arguments.clear(); + arguments.add(attrDateTimeToday); + arguments.add(attrDateTimeYesterday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // test bad args data types? One with TimeZone and one without + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + // test with TimeZone vs without + arguments.clear(); + arguments.add(attrDateTimeWithTimeZone); + arguments.add(attrDateTimeNoTimeZone); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-greater-than Cannot compare this ISO8601DateTime with non-time-zoned ISO8601DateTime", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + } + + @Test + public void testDateTime_GTE() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATETIME_GREATER_THAN_OR_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATETIME_GREATER_THAN_OR_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attrDateTimeToday); + arguments.add(attrDateTimeSameDay); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first < second + arguments.clear(); + arguments.add(attrDateTimeToday); + arguments.add(attrDateTimeTommorrow); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first > second + arguments.clear(); + arguments.add(attrDateTimeToday); + arguments.add(attrDateTimeYesterday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + } + + @Test + public void testDateTime_LT() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATETIME_LESS_THAN; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATETIME_LESS_THAN, fd.getId()); + assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attrDateTimeToday); + arguments.add(attrDateTimeSameDay); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first < second + arguments.clear(); + arguments.add(attrDateTimeToday); + arguments.add(attrDateTimeTommorrow); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first > second + arguments.clear(); + arguments.add(attrDateTimeToday); + arguments.add(attrDateTimeYesterday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + } + + @Test + public void testDateTime_LTE() { + + FunctionDefinitionComparison fd = (FunctionDefinitionComparison) StdFunctions.FD_DATETIME_LESS_THAN_OR_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATETIME_LESS_THAN_OR_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // first == second + arguments.add(attrDateTimeToday); + arguments.add(attrDateTimeSameDay); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first < second + arguments.clear(); + arguments.add(attrDateTimeToday); + arguments.add(attrDateTimeTommorrow); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first > second + arguments.clear(); + arguments.add(attrDateTimeToday); + arguments.add(attrDateTimeYesterday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + } + + + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionDateTimeArithmeticTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionDateTimeArithmeticTest.java new file mode 100644 index 000000000..809733ea8 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionDateTimeArithmeticTest.java @@ -0,0 +1,1602 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacml.std.datatypes.ISO8601Date; +import com.att.research.xacml.std.datatypes.ISO8601DateTime; +import com.att.research.xacml.std.datatypes.ISO8601Time; +import com.att.research.xacml.std.datatypes.ISO8601TimeZone; +import com.att.research.xacml.std.datatypes.XPathDayTimeDuration; +import com.att.research.xacml.std.datatypes.XPathYearMonthDuration; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionDateTimeArithmeticTest { + + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + ExpressionResult res; + + + @Test + public void testDateTime_add_dayTimeDuration() { + // Date objects to be adjusted + ISO8601DateTime dateTimeStdExample1 = new ISO8601DateTime(null, + new ISO8601Date(2000, 1, 12), + new ISO8601Time(12, 13, 14, 0)); + ISO8601DateTime dateTimeMsecs = new ISO8601DateTime(null, + new ISO8601Date(2000, 1, 12), + new ISO8601Time(12, 13, 14, 777)); + ISO8601DateTime dateTimeCrossover = new ISO8601DateTime(null, + new ISO8601Date(2000, 12, 31), + new ISO8601Time(23, 59, 30, 1)); + ISO8601DateTime dateTimeBC = new ISO8601DateTime(null, + new ISO8601Date(-2000, 1, 12), + new ISO8601Time(12, 13, 14, 0)); + ISO8601TimeZone timeZone0 = new ISO8601TimeZone(0); + ISO8601TimeZone timeZone5 = new ISO8601TimeZone(5 * 60); + ISO8601DateTime dateTimeTimeZone0 = new ISO8601DateTime(timeZone0, + new ISO8601Date(timeZone0, 2000, 1, 12), + new ISO8601Time(timeZone0, 12, 13, 14, 0)); + ISO8601DateTime dateTimeTimeZone5 = new ISO8601DateTime(timeZone5, + new ISO8601Date(timeZone5, 2000, 1, 12), + new ISO8601Time(timeZone5, 12, 13, 14, 0)); + ISO8601DateTime dateTimeIIC102Result = null; + + // Durations + XPathDayTimeDuration duration0 = new XPathDayTimeDuration(1, 0, 0, 0, 0); + XPathDayTimeDuration durationStdExample1 = new XPathDayTimeDuration(1, 5, 7, 10, 3.3); + XPathDayTimeDuration durationNStdExample1 = new XPathDayTimeDuration(-1, 5, 7, 10, 3.3); + XPathDayTimeDuration durationMsecs = new XPathDayTimeDuration(1, 5, 7, 10, 3.223); + XPathDayTimeDuration durationCrossover = new XPathDayTimeDuration(1, 0, 0, 0, 29.999); + + // ARGS declarations + // Dates + FunctionArgumentAttributeValue attrDateTimeStdExample1 = null; + FunctionArgumentAttributeValue attrDateTimeMsecs = null; + FunctionArgumentAttributeValue attrDateTimeCrossover = null; + FunctionArgumentAttributeValue attrDateTimeBC = null; + FunctionArgumentAttributeValue attrDateTimeTimeZone0 = null; + FunctionArgumentAttributeValue attrDateTimeTimeZone5 = null; + FunctionArgumentAttributeValue attrDateTimeIIC102 = null; + + // Durations + FunctionArgumentAttributeValue attrDuration0 = null; + FunctionArgumentAttributeValue attrDurationStdExample1 = null; + FunctionArgumentAttributeValue attrDurationNStdExample1 = null; + FunctionArgumentAttributeValue attrDurationMsecs = null; + FunctionArgumentAttributeValue attrDurationCrossover = null; + FunctionArgumentAttributeValue attrDurationIIC102 = null; + + // misc bad + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrBlank = null; + FunctionArgumentAttributeValue attrInteger = null; + // set values + try { + // Date attrs + attrDateTimeStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeStdExample1)); + attrDateTimeMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeMsecs)); + attrDateTimeCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeCrossover)); + attrDateTimeBC = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeBC)); + attrDateTimeTimeZone0 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone0)); + attrDateTimeTimeZone5 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone5)); + attrDateTimeIIC102 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(DataTypes.DT_DATETIME.convert("2002-03-22T08:23:47-05:00"))); + + dateTimeIIC102Result = DataTypes.DT_DATETIME.convert("2002-03-27T10:23:47-05:00"); + + // Duration attrs + attrDuration0 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(duration0)); + attrDurationStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationStdExample1)); + attrDurationNStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationNStdExample1)); + attrDurationMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationMsecs)); + attrDurationCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationCrossover)); + attrDurationIIC102 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue("P5DT2H0M0S")); + + // misc bad + attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue("")); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(null)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionDateTimeArithmetic fd = (FunctionDefinitionDateTimeArithmetic) StdFunctions.FD_DATETIME_ADD_DAYTIMEDURATION; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATETIME_ADD_DAYTIMEDURATION, fd.getId()); + assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + // Duration = 0 => same as original + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDuration0); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + ISO8601DateTime resValue = (ISO8601DateTime)res.getValue().getValue(); + assertEquals(dateTimeStdExample1, resValue); + + + // simple positive operation + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + ISO8601DateTime testResponse = new ISO8601DateTime( + null, + new ISO8601Date(2000, 1, 17), + new ISO8601Time(19, 23, 17, 300) ); + assertEquals(testResponse, resValue); + + // negative operation + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDurationNStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(2000, 1, 7), + new ISO8601Time(5, 3, 10, 700) ); + assertEquals(testResponse, resValue); + + // millisecs work correctly + arguments.clear(); + arguments.add(attrDateTimeMsecs); + arguments.add(attrDurationMsecs); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(2000, 1, 17), + new ISO8601Time(19, 23, 18, 0) ); + assertEquals(testResponse, resValue); + + // cross minute => cross day => cross month => cross year + arguments.clear(); + arguments.add(attrDateTimeCrossover); + arguments.add(attrDurationCrossover); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(2001, 1, 1), + new ISO8601Time(0, 0, 0, 0) ); + assertEquals(testResponse, resValue); + + // negative (BC) original date add goes the right direction + arguments.clear(); + arguments.add(attrDateTimeBC); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(-2000, 1, 17), + new ISO8601Time(19, 23, 17, 300) ); + assertEquals(testResponse, resValue); + + // non-null timezone not changed + // original has timezone offset = 0 + arguments.clear(); + arguments.add(attrDateTimeTimeZone0); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + timeZone0, + new ISO8601Date(timeZone0, 2000, 1, 17), + new ISO8601Time(timeZone0, 19, 23, 17, 300) ); + assertEquals(testResponse, resValue); + + // original has timezone offset not 0 + arguments.clear(); + arguments.add(attrDateTimeTimeZone5); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + timeZone5, + new ISO8601Date(timeZone5, 2000, 1, 17), + new ISO8601Time(timeZone5, 19, 23, 17, 300) ); + assertEquals(testResponse, resValue); + + // conformance test IIC102 + arguments.clear(); + arguments.add(attrDateTimeIIC102); + arguments.add(attrDurationIIC102); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + assertEquals(dateTimeIIC102Result, resValue); + + // empty non-null first arg + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-add-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // empty non-null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-add-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // two blanks + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-add-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null firat arg + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-add-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-add-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrInteger); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-add-dayTimeDuration Expected data type 'dateTime' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-add-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + @Test + public void testDateTime_subtract_dayTimeDuration() { + // Date objects to be adjusted + ISO8601DateTime dateTimeStdExample1 = new ISO8601DateTime(null, + new ISO8601Date(2000, 1, 12), + new ISO8601Time(12, 13, 14, 0)); + ISO8601DateTime dateTimeMsecs = new ISO8601DateTime(null, + new ISO8601Date(2000, 1, 12), + new ISO8601Time(12, 13, 14, 777)); + ISO8601DateTime dateTimeCrossover = new ISO8601DateTime(null, + new ISO8601Date(2001, 1, 1), + new ISO8601Time(0, 0, 0, 0) ); + ISO8601DateTime dateTimeBC = new ISO8601DateTime(null, + new ISO8601Date(-2000, 1, 12), + new ISO8601Time(12, 13, 14, 0)); + ISO8601TimeZone timeZone0 = new ISO8601TimeZone(0); + ISO8601TimeZone timeZone5 = new ISO8601TimeZone(5 * 60); + ISO8601DateTime dateTimeTimeZone0 = new ISO8601DateTime(timeZone0, + new ISO8601Date(timeZone0, 2000, 1, 12), + new ISO8601Time(timeZone0, 12, 13, 14, 0)); + ISO8601DateTime dateTimeTimeZone5 = new ISO8601DateTime(timeZone5, + new ISO8601Date(timeZone5, 2000, 1, 12), + new ISO8601Time(timeZone5, 12, 13, 14, 0)); + + // Durations + XPathDayTimeDuration duration0 = new XPathDayTimeDuration(1, 0, 0, 0, 0); + XPathDayTimeDuration durationStdExample1 = new XPathDayTimeDuration(1, 5, 7, 10, 3.3); + XPathDayTimeDuration durationNStdExample1 = new XPathDayTimeDuration(-1, 5, 7, 10, 3.3); + XPathDayTimeDuration durationMsecs = new XPathDayTimeDuration(1, 5, 7, 10, 14.778); + XPathDayTimeDuration durationCrossover = new XPathDayTimeDuration(1, 0, 0, 0, 29.999); + + // ARGS declarations + // Dates + FunctionArgumentAttributeValue attrDateTimeStdExample1 = null; + FunctionArgumentAttributeValue attrDateTimeMsecs = null; + FunctionArgumentAttributeValue attrDateTimeCrossover = null; + FunctionArgumentAttributeValue attrDateTimeBC = null; + FunctionArgumentAttributeValue attrDateTimeTimeZone0 = null; + FunctionArgumentAttributeValue attrDateTimeTimeZone5 = null; + + // Durations + FunctionArgumentAttributeValue attrDuration0 = null; + FunctionArgumentAttributeValue attrDurationStdExample1 = null; + FunctionArgumentAttributeValue attrDurationNStdExample1 = null; + FunctionArgumentAttributeValue attrDurationMsecs = null; + FunctionArgumentAttributeValue attrDurationCrossover = null; + + // misc bad + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrBlank = null; + FunctionArgumentAttributeValue attrInteger = null; + // set values + try { + // Date attrs + attrDateTimeStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeStdExample1)); + attrDateTimeMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeMsecs)); + attrDateTimeCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeCrossover)); + attrDateTimeBC = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeBC)); + attrDateTimeTimeZone0 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone0)); + attrDateTimeTimeZone5 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone5)); + + // Duration attrs + attrDuration0 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(duration0)); + attrDurationStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationStdExample1)); + attrDurationNStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationNStdExample1)); + attrDurationMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationMsecs)); + attrDurationCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(durationCrossover)); + + // misc bad + attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue("")); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(null)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionDateTimeArithmetic fd = (FunctionDefinitionDateTimeArithmetic) StdFunctions.FD_DATETIME_SUBTRACT_DAYTIMEDURATION; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATETIME_SUBTRACT_DAYTIMEDURATION, fd.getId()); + assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + // Duration = 0 => same as original + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDuration0); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + ISO8601DateTime resValue = (ISO8601DateTime)res.getValue().getValue(); + assertEquals(dateTimeStdExample1, resValue); + + + // simple positive operation + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + ISO8601DateTime testResponse = new ISO8601DateTime( + null, + new ISO8601Date(2000, 1, 7), + new ISO8601Time(5, 3, 10, 700) ); + assertEquals(testResponse, resValue); + + + // negative operation + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDurationNStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(2000, 1, 17), + new ISO8601Time(19, 23, 17, 300) ); + assertEquals(testResponse, resValue); + + // millisecs work correctly + arguments.clear(); + arguments.add(attrDateTimeMsecs); + arguments.add(attrDurationMsecs); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(2000, 1, 7), + new ISO8601Time(5, 2, 59, 999) ); + assertEquals(testResponse, resValue); + + // cross minute => cross day => cross month => cross year + arguments.clear(); + arguments.add(attrDateTimeCrossover); + arguments.add(attrDurationCrossover); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(2000, 12, 31), + new ISO8601Time(23, 59, 30, 1)); + assertEquals(testResponse, resValue); + + // negative (BC) original date add goes the right direction + arguments.clear(); + arguments.add(attrDateTimeBC); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(-2000, 1, 7), + new ISO8601Time(5, 3, 10, 700) ); + assertEquals(testResponse, resValue); + + // non-null timezone not changed + // original has timezone offset = 0 + arguments.clear(); + arguments.add(attrDateTimeTimeZone0); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + timeZone0, + new ISO8601Date(timeZone0, 2000, 1, 7), + new ISO8601Time(timeZone0, 5, 3, 10, 700) ); + assertEquals(testResponse, resValue); + + // original has timezone offset not 0 + arguments.clear(); + arguments.add(attrDateTimeTimeZone5); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + timeZone5, + new ISO8601Date(timeZone5, 2000, 1, 7), + new ISO8601Time(timeZone5, 5, 3, 10, 700) ); + assertEquals(testResponse, resValue); + + // empty non-null first arg + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-subtract-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // empty non-null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-subtract-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // two blanks + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-subtract-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null firat arg + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-subtract-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-subtract-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrInteger); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-subtract-dayTimeDuration Expected data type 'dateTime' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-subtract-dayTimeDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + + + + + + + @Test + public void testDateTime_add_yearMonthDuration() { + // Date objects to be adjusted + ISO8601DateTime dateTimeStdExample1 = new ISO8601DateTime(null, + new ISO8601Date(2000, 1, 12), + new ISO8601Time(12, 13, 14, 0)); + ISO8601DateTime dateTimeMsecs = new ISO8601DateTime(null, + new ISO8601Date(2000, 1, 12), + new ISO8601Time(12, 13, 14, 777)); + ISO8601DateTime dateTimeCrossover = new ISO8601DateTime(null, + new ISO8601Date(2000, 12, 31), + new ISO8601Time(23, 59, 30, 1)); + ISO8601DateTime dateTimeBC = new ISO8601DateTime(null, + new ISO8601Date(-2000, 1, 12), + new ISO8601Time(12, 13, 14, 0)); + ISO8601TimeZone timeZone0 = new ISO8601TimeZone(0); + ISO8601TimeZone timeZone5 = new ISO8601TimeZone(5 * 60); + ISO8601DateTime dateTimeTimeZone0 = new ISO8601DateTime(timeZone0, + new ISO8601Date(timeZone0, 2000, 1, 12), + new ISO8601Time(timeZone0, 12, 13, 14, 0)); + ISO8601DateTime dateTimeTimeZone5 = new ISO8601DateTime(timeZone5, + new ISO8601Date(timeZone5, 2000, 1, 12), + new ISO8601Time(timeZone5, 12, 13, 14, 0)); + + // Durations + XPathYearMonthDuration duration0 = new XPathYearMonthDuration(1, 0, 0); + XPathYearMonthDuration durationStdExample1 = new XPathYearMonthDuration(1, 5, 7); + XPathYearMonthDuration durationNStdExample1 = new XPathYearMonthDuration(-1, 5, 7); + XPathYearMonthDuration durationMsecs = new XPathYearMonthDuration(1, 5, 7); + XPathYearMonthDuration durationCrossover = new XPathYearMonthDuration(1, 0, 1); + + // ARGS declarations + // Dates + FunctionArgumentAttributeValue attrDateTimeStdExample1 = null; + FunctionArgumentAttributeValue attrDateTimeMsecs = null; + FunctionArgumentAttributeValue attrDateTimeCrossover = null; + FunctionArgumentAttributeValue attrDateTimeBC = null; + FunctionArgumentAttributeValue attrDateTimeTimeZone0 = null; + FunctionArgumentAttributeValue attrDateTimeTimeZone5 = null; + + // Durations + FunctionArgumentAttributeValue attrDuration0 = null; + FunctionArgumentAttributeValue attrDurationStdExample1 = null; + FunctionArgumentAttributeValue attrDurationNStdExample1 = null; + FunctionArgumentAttributeValue attrDurationMsecs = null; + FunctionArgumentAttributeValue attrDurationCrossover = null; + + // misc bad + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrBlank = null; + FunctionArgumentAttributeValue attrInteger = null; + // set values + try { + // Date attrs + attrDateTimeStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeStdExample1)); + attrDateTimeMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeMsecs)); + attrDateTimeCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeCrossover)); + attrDateTimeBC = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeBC)); + attrDateTimeTimeZone0 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone0)); + attrDateTimeTimeZone5 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone5)); + + // Duration attrs + attrDuration0 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(duration0)); + attrDurationStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationStdExample1)); + attrDurationNStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationNStdExample1)); + attrDurationMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationMsecs)); + attrDurationCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationCrossover)); + + // misc bad + attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue("")); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(null)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionDateTimeArithmetic fd = (FunctionDefinitionDateTimeArithmetic) StdFunctions.FD_DATETIME_ADD_YEARMONTHDURATION; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATETIME_ADD_YEARMONTHDURATION, fd.getId()); + assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + // Duration = 0 => same as original + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDuration0); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + ISO8601DateTime resValue = (ISO8601DateTime)res.getValue().getValue(); + assertEquals(dateTimeStdExample1, resValue); + + + // simple positive operation + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + ISO8601DateTime testResponse = new ISO8601DateTime( + null, + new ISO8601Date(2005, 8, 12), + new ISO8601Time(12, 13, 14, 0) ); + assertEquals(testResponse, resValue); + + // negative operation + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDurationNStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(1994, 6, 12), + new ISO8601Time(12, 13, 14, 0) ); + assertEquals(testResponse, resValue); + + // millisecs work correctly (not relevant to YearMonth, but should not break + arguments.clear(); + arguments.add(attrDateTimeMsecs); + arguments.add(attrDurationMsecs); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(2005, 8, 12), + new ISO8601Time(12, 13, 14, 777) ); + assertEquals(testResponse, resValue); + + // cross minute => cross day => cross month => cross year + arguments.clear(); + arguments.add(attrDateTimeCrossover); + arguments.add(attrDurationCrossover); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(2001, 1, 31), + new ISO8601Time(23, 59, 30, 1) ); + assertEquals(testResponse, resValue); + + // negative (BC) original date add goes the right direction + arguments.clear(); + arguments.add(attrDateTimeBC); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(-1995, 8, 12), + new ISO8601Time(12, 13, 14, 0) ); + assertEquals(testResponse, resValue); + + // non-null timezone not changed + // original has timezone offset = 0 + arguments.clear(); + arguments.add(attrDateTimeTimeZone0); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + timeZone0, + new ISO8601Date(timeZone0, 2005, 8, 12), + new ISO8601Time(timeZone0, 12, 13, 14, 0) ); + assertEquals(testResponse, resValue); + + // original has timezone offset not 0 + arguments.clear(); + arguments.add(attrDateTimeTimeZone5); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + timeZone5, + new ISO8601Date(timeZone5, 2005, 8, 12), + new ISO8601Time(timeZone5, 12, 13, 14, 0) ); + assertEquals(testResponse, resValue); + + // empty non-null first arg + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // empty non-null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // two blanks + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null firat arg + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrInteger); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-add-yearMonthDuration Expected data type 'dateTime' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + + @Test + public void testDateTime_subtract_yearMonthDuration() { + // Date objects to be adjusted + ISO8601DateTime dateTimeStdExample1 = new ISO8601DateTime(null, + new ISO8601Date(2000, 1, 12), + new ISO8601Time(12, 13, 14, 0)); + ISO8601DateTime dateTimeMsecs = new ISO8601DateTime(null, + new ISO8601Date(2000, 1, 12), + new ISO8601Time(12, 13, 14, 777)); + ISO8601DateTime dateTimeCrossover = new ISO8601DateTime(null, + new ISO8601Date(2000, 1, 1), + new ISO8601Time(23, 59, 30, 1)); + ISO8601DateTime dateTimeBC = new ISO8601DateTime(null, + new ISO8601Date(-2000, 1, 12), + new ISO8601Time(12, 13, 14, 0)); + ISO8601TimeZone timeZone0 = new ISO8601TimeZone(0); + ISO8601TimeZone timeZone5 = new ISO8601TimeZone(5 * 60); + ISO8601DateTime dateTimeTimeZone0 = new ISO8601DateTime(timeZone0, + new ISO8601Date(timeZone0, 2000, 1, 12), + new ISO8601Time(timeZone0, 12, 13, 14, 0)); + ISO8601DateTime dateTimeTimeZone5 = new ISO8601DateTime(timeZone5, + new ISO8601Date(timeZone5, 2000, 1, 12), + new ISO8601Time(timeZone5, 12, 13, 14, 0)); + + // Durations + XPathYearMonthDuration duration0 = new XPathYearMonthDuration(1, 0, 0); + XPathYearMonthDuration durationStdExample1 = new XPathYearMonthDuration(1, 5, 7); + XPathYearMonthDuration durationNStdExample1 = new XPathYearMonthDuration(-1, 5, 7); + XPathYearMonthDuration durationMsecs = new XPathYearMonthDuration(1, 5, 7); + XPathYearMonthDuration durationCrossover = new XPathYearMonthDuration(1, 0, 1); + + // ARGS declarations + // Dates + FunctionArgumentAttributeValue attrDateTimeStdExample1 = null; + FunctionArgumentAttributeValue attrDateTimeMsecs = null; + FunctionArgumentAttributeValue attrDateTimeCrossover = null; + FunctionArgumentAttributeValue attrDateTimeBC = null; + FunctionArgumentAttributeValue attrDateTimeTimeZone0 = null; + FunctionArgumentAttributeValue attrDateTimeTimeZone5 = null; + + // Durations + FunctionArgumentAttributeValue attrDuration0 = null; + FunctionArgumentAttributeValue attrDurationStdExample1 = null; + FunctionArgumentAttributeValue attrDurationNStdExample1 = null; + FunctionArgumentAttributeValue attrDurationMsecs = null; + FunctionArgumentAttributeValue attrDurationCrossover = null; + + // misc bad + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrBlank = null; + FunctionArgumentAttributeValue attrInteger = null; + // set values + try { + // Date attrs + attrDateTimeStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeStdExample1)); + attrDateTimeMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeMsecs)); + attrDateTimeCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeCrossover)); + attrDateTimeBC = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeBC)); + attrDateTimeTimeZone0 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone0)); + attrDateTimeTimeZone5 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(dateTimeTimeZone5)); + + // Duration attrs + attrDuration0 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(duration0)); + attrDurationStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationStdExample1)); + attrDurationNStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationNStdExample1)); + attrDurationMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationMsecs)); + attrDurationCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationCrossover)); + + // misc bad + attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue("")); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(null)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionDateTimeArithmetic fd = (FunctionDefinitionDateTimeArithmetic) StdFunctions.FD_DATETIME_SUBTRACT_YEARMONTHDURATION; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATETIME_SUBTRACT_YEARMONTHDURATION, fd.getId()); + assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + // Duration = 0 => same as original + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDuration0); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + ISO8601DateTime resValue = (ISO8601DateTime)res.getValue().getValue(); + assertEquals(dateTimeStdExample1, resValue); + + + // simple positive operation + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + ISO8601DateTime testResponse = new ISO8601DateTime( + null, + new ISO8601Date(1994, 6, 12), + new ISO8601Time(12, 13, 14, 0) ); + assertEquals(testResponse, resValue); + + // negative operation + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDurationNStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(2005, 8, 12), + new ISO8601Time(12, 13, 14, 0) ); + assertEquals(testResponse, resValue); + + // millisecs work correctly (not relevant to YearMonth, but should not break + arguments.clear(); + arguments.add(attrDateTimeMsecs); + arguments.add(attrDurationMsecs); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(1994, 6, 12), + new ISO8601Time(12, 13, 14, 777) ); + assertEquals(testResponse, resValue); + + // cross minute => cross day => cross month => cross year + arguments.clear(); + arguments.add(attrDateTimeCrossover); + arguments.add(attrDurationCrossover); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(1999, 12, 1), + new ISO8601Time(23, 59, 30, 1) ); + assertEquals(testResponse, resValue); + + // negative (BC) original date add goes the right direction + arguments.clear(); + arguments.add(attrDateTimeBC); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + null, + new ISO8601Date(-2006, 6, 12), + new ISO8601Time(12, 13, 14, 0) ); + assertEquals(testResponse, resValue); + + // non-null timezone not changed + // original has timezone offset = 0 + arguments.clear(); + arguments.add(attrDateTimeTimeZone0); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + timeZone0, + new ISO8601Date(timeZone0, 1994, 6, 12), + new ISO8601Time(timeZone0, 12, 13, 14, 0) ); + assertEquals(testResponse, resValue); + + // original has timezone offset not 0 + arguments.clear(); + arguments.add(attrDateTimeTimeZone5); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601DateTime.class, res.getValue().getValue().getClass()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + testResponse = new ISO8601DateTime( + timeZone5, + new ISO8601Date(timeZone5, 1994, 6, 12), + new ISO8601Time(timeZone5, 12, 13, 14, 0) ); + assertEquals(testResponse, resValue); + + // empty non-null first arg + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // empty non-null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // two blanks + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null firat arg + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrInteger); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-subtract-yearMonthDuration Expected data type 'dateTime' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + + + + + + + + + @Test + public void testDate_add_yearMonthDuration() { + // Date objects to be adjusted + ISO8601Date dateTimeStdExample1 = new ISO8601Date(2000, 1, 12); + ISO8601Date dateTimeMsecs =new ISO8601Date(2000, 1, 12); + ISO8601Date dateTimeCrossover = new ISO8601Date(2000, 12, 31); + ISO8601Date dateTimeBC = new ISO8601Date(-2000, 1, 12); + ISO8601TimeZone timeZone0 = new ISO8601TimeZone(0); + ISO8601TimeZone timeZone5 = new ISO8601TimeZone(5 * 60); + ISO8601Date dateTimeTimeZone0 = new ISO8601Date(timeZone0, 2000, 1, 12); + ISO8601Date dateTimeTimeZone5 = new ISO8601Date(timeZone5, 2000, 1, 12); + + // Durations + XPathYearMonthDuration duration0 = new XPathYearMonthDuration(1, 0, 0); + XPathYearMonthDuration durationStdExample1 = new XPathYearMonthDuration(1, 5, 7); + XPathYearMonthDuration durationNStdExample1 = new XPathYearMonthDuration(-1, 5, 7); + XPathYearMonthDuration durationMsecs = new XPathYearMonthDuration(1, 5, 7); + XPathYearMonthDuration durationCrossover = new XPathYearMonthDuration(1, 0, 1); + + // ARGS declarations + // Dates + FunctionArgumentAttributeValue attrDateTimeStdExample1 = null; + FunctionArgumentAttributeValue attrDateTimeMsecs = null; + FunctionArgumentAttributeValue attrDateTimeCrossover = null; + FunctionArgumentAttributeValue attrDateTimeBC = null; + FunctionArgumentAttributeValue attrDateTimeTimeZone0 = null; + FunctionArgumentAttributeValue attrDateTimeTimeZone5 = null; + + // Durations + FunctionArgumentAttributeValue attrDuration0 = null; + FunctionArgumentAttributeValue attrDurationStdExample1 = null; + FunctionArgumentAttributeValue attrDurationNStdExample1 = null; + FunctionArgumentAttributeValue attrDurationMsecs = null; + FunctionArgumentAttributeValue attrDurationCrossover = null; + + // misc bad + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrBlank = null; + FunctionArgumentAttributeValue attrInteger = null; + // set values + try { + // Date attrs + attrDateTimeStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeStdExample1)); + attrDateTimeMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeMsecs)); + attrDateTimeCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeCrossover)); + attrDateTimeBC = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeBC)); + attrDateTimeTimeZone0 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeTimeZone0)); + attrDateTimeTimeZone5 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeTimeZone5)); + + // Duration attrs + attrDuration0 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(duration0)); + attrDurationStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationStdExample1)); + attrDurationNStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationNStdExample1)); + attrDurationMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationMsecs)); + attrDurationCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationCrossover)); + + // misc bad + attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue("")); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(null)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionDateTimeArithmetic fd = (FunctionDefinitionDateTimeArithmetic) StdFunctions.FD_DATE_ADD_YEARMONTHDURATION; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATE_ADD_YEARMONTHDURATION, fd.getId()); + assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + // Duration = 0 => same as original + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDuration0); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + ISO8601Date resValue = (ISO8601Date)res.getValue().getValue(); + assertEquals(dateTimeStdExample1, resValue); + + + // simple positive operation + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + resValue = (ISO8601Date)res.getValue().getValue(); + ISO8601Date testResponse = new ISO8601Date(2005, 8, 12); + assertEquals(testResponse, resValue); + + // negative operation + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDurationNStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + resValue = (ISO8601Date)res.getValue().getValue(); + testResponse = new ISO8601Date(1994, 6, 12); + assertEquals(testResponse, resValue); + + // millisecs work correctly (not relevant to YearMonth, but should not break + arguments.clear(); + arguments.add(attrDateTimeMsecs); + arguments.add(attrDurationMsecs); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + resValue = (ISO8601Date)res.getValue().getValue(); + testResponse = new ISO8601Date(2005, 8, 12); + assertEquals(testResponse, resValue); + + // cross minute => cross day => cross month => cross year + arguments.clear(); + arguments.add(attrDateTimeCrossover); + arguments.add(attrDurationCrossover); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + resValue = (ISO8601Date)res.getValue().getValue(); + testResponse = new ISO8601Date(2001, 1, 31); + assertEquals(testResponse, resValue); + + // negative (BC) original date add goes the right direction + arguments.clear(); + arguments.add(attrDateTimeBC); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + resValue = (ISO8601Date)res.getValue().getValue(); + testResponse = new ISO8601Date(-1995, 8, 12); + assertEquals(testResponse, resValue); + + // non-null timezone not changed + // original has timezone offset = 0 + arguments.clear(); + arguments.add(attrDateTimeTimeZone0); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + resValue = (ISO8601Date)res.getValue().getValue(); + testResponse = new ISO8601Date(timeZone0, 2005, 8, 12); + assertEquals(testResponse, resValue); + + // original has timezone offset not 0 + arguments.clear(); + arguments.add(attrDateTimeTimeZone5); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + resValue = (ISO8601Date)res.getValue().getValue(); + testResponse = new ISO8601Date(timeZone5, 2005, 8, 12); + assertEquals(testResponse, resValue); + + // empty non-null first arg + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // empty non-null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // two blanks + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null firat arg + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrInteger); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-add-yearMonthDuration Expected data type 'date' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-add-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + + + + @Test + public void testDate_subtract_yearMonthDuration() { + // Date objects to be adjusted + ISO8601Date dateTimeStdExample1 =new ISO8601Date(2000, 1, 12); + ISO8601Date dateTimeMsecs = new ISO8601Date(2000, 1, 12); + ISO8601Date dateTimeCrossover = new ISO8601Date(2000, 1, 1); + ISO8601Date dateTimeBC = new ISO8601Date(-2000, 1, 12); + ISO8601TimeZone timeZone0 = new ISO8601TimeZone(0); + ISO8601TimeZone timeZone5 = new ISO8601TimeZone(5 * 60); + ISO8601Date dateTimeTimeZone0 = new ISO8601Date(timeZone0, 2000, 1, 12); + ISO8601Date dateTimeTimeZone5 = new ISO8601Date(timeZone5, 2000, 1, 12); + + // Durations + XPathYearMonthDuration duration0 = new XPathYearMonthDuration(1, 0, 0); + XPathYearMonthDuration durationStdExample1 = new XPathYearMonthDuration(1, 5, 7); + XPathYearMonthDuration durationNStdExample1 = new XPathYearMonthDuration(-1, 5, 7); + XPathYearMonthDuration durationMsecs = new XPathYearMonthDuration(1, 5, 7); + XPathYearMonthDuration durationCrossover = new XPathYearMonthDuration(1, 0, 1); + + // ARGS declarations + // Dates + FunctionArgumentAttributeValue attrDateTimeStdExample1 = null; + FunctionArgumentAttributeValue attrDateTimeMsecs = null; + FunctionArgumentAttributeValue attrDateTimeCrossover = null; + FunctionArgumentAttributeValue attrDateTimeBC = null; + FunctionArgumentAttributeValue attrDateTimeTimeZone0 = null; + FunctionArgumentAttributeValue attrDateTimeTimeZone5 = null; + + // Durations + FunctionArgumentAttributeValue attrDuration0 = null; + FunctionArgumentAttributeValue attrDurationStdExample1 = null; + FunctionArgumentAttributeValue attrDurationNStdExample1 = null; + FunctionArgumentAttributeValue attrDurationMsecs = null; + FunctionArgumentAttributeValue attrDurationCrossover = null; + + // misc bad + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrBlank = null; + FunctionArgumentAttributeValue attrInteger = null; + // set values + try { + // Date attrs + attrDateTimeStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeStdExample1)); + attrDateTimeMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeMsecs)); + attrDateTimeCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeCrossover)); + attrDateTimeBC = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeBC)); + attrDateTimeTimeZone0 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeTimeZone0)); + attrDateTimeTimeZone5 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(dateTimeTimeZone5)); + + // Duration attrs + attrDuration0 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(duration0)); + attrDurationStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationStdExample1)); + attrDurationNStdExample1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationNStdExample1)); + attrDurationMsecs = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationMsecs)); + attrDurationCrossover = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(durationCrossover)); + + // misc bad + attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue("")); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(null)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionDateTimeArithmetic fd = (FunctionDefinitionDateTimeArithmetic) StdFunctions.FD_DATE_SUBTRACT_YEARMONTHDURATION; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATE_SUBTRACT_YEARMONTHDURATION, fd.getId()); + assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + // Duration = 0 => same as original + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDuration0); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + ISO8601Date resValue = (ISO8601Date)res.getValue().getValue(); + assertEquals(dateTimeStdExample1, resValue); + + + // simple positive operation + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + resValue = (ISO8601Date)res.getValue().getValue(); + ISO8601Date testResponse = new ISO8601Date(1994, 6, 12); + assertEquals(testResponse, resValue); + + // negative operation + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrDurationNStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + resValue = (ISO8601Date)res.getValue().getValue(); + testResponse = new ISO8601Date(2005, 8, 12); + assertEquals(testResponse, resValue); + + // millisecs work correctly (not relevant to YearMonth, but should not break + arguments.clear(); + arguments.add(attrDateTimeMsecs); + arguments.add(attrDurationMsecs); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + resValue = (ISO8601Date)res.getValue().getValue(); + testResponse = new ISO8601Date(1994, 6, 12); + assertEquals(testResponse, resValue); + + // cross minute => cross day => cross month => cross year + arguments.clear(); + arguments.add(attrDateTimeCrossover); + arguments.add(attrDurationCrossover); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + resValue = (ISO8601Date)res.getValue().getValue(); + testResponse = new ISO8601Date(1999, 12, 1); + assertEquals(testResponse, resValue); + + // negative (BC) original date add goes the right direction + arguments.clear(); + arguments.add(attrDateTimeBC); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + resValue = (ISO8601Date)res.getValue().getValue(); + testResponse = new ISO8601Date(-2006, 6, 12); + assertEquals(testResponse, resValue); + + // non-null timezone not changed + // original has timezone offset = 0 + arguments.clear(); + arguments.add(attrDateTimeTimeZone0); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + resValue = (ISO8601Date)res.getValue().getValue(); + testResponse = new ISO8601Date(timeZone0, 1994, 6, 12); + assertEquals(testResponse, resValue); + + // original has timezone offset not 0 + arguments.clear(); + arguments.add(attrDateTimeTimeZone5); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(com.att.research.xacml.std.datatypes.ISO8601Date.class, res.getValue().getValue().getClass()); + resValue = (ISO8601Date)res.getValue().getValue(); + testResponse = new ISO8601Date(timeZone5, 1994, 6, 12); + assertEquals(testResponse, resValue); + + // empty non-null first arg + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // empty non-null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // two blanks + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null firat arg + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrInteger); + arguments.add(attrDurationStdExample1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-subtract-yearMonthDuration Expected data type 'date' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrDateTimeStdExample1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-subtract-yearMonthDuration Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionEqualityTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionEqualityTest.java new file mode 100644 index 000000000..9a94ef631 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionEqualityTest.java @@ -0,0 +1,1192 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import javax.security.auth.x500.X500Principal; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML1; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.Base64Binary; +import com.att.research.xacml.std.datatypes.DataTypeRFC822Name; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacml.std.datatypes.HexBinary; +import com.att.research.xacml.std.datatypes.RFC822Name; +import com.att.research.xacml.std.datatypes.XPathDayTimeDuration; +import com.att.research.xacml.std.datatypes.XPathYearMonthDuration; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test FunctionDefinitionEquality, all of its super-classes, and all XACML functions supported by that class. + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * In the first implementation of XACML we had separate files for each XACML Function. + * This release combines multiple Functions in fewer files to minimize code duplication. + * This file supports the following XACML codes: + * string-equal + * boolean-equal + * integer-equal + * double-equal + * date-equal + * time-equal + * dateTime-equal + * dayTimeDuration-equal + * yearMonthDuration-equal + * + * Each of these is put into a separate test method just to keep things organized. + * + * + */ +public class FunctionDefinitionEqualityTest { + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + FunctionArgumentAttributeValue stringAttr1 = null; + FunctionArgumentAttributeValue stringAttr2 = null; + FunctionArgumentAttributeValue stringAttr3 = null; + FunctionArgumentAttributeValue stringAttr4 = null; + + FunctionArgumentAttributeValue booleanAttrT1 = null; + FunctionArgumentAttributeValue booleanAttrT2 = null; + FunctionArgumentAttributeValue booleanAttrF1 = null; + FunctionArgumentAttributeValue booleanAttrF2 = null; + + FunctionArgumentAttributeValue intAttr1 = null; + FunctionArgumentAttributeValue intAttr1a = null; + FunctionArgumentAttributeValue intAttr2 = null; + FunctionArgumentAttributeValue intAttr0 = null; + FunctionArgumentAttributeValue intAttrNeg1 = null; + + public FunctionDefinitionEqualityTest() { + try { + stringAttr1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc")); + stringAttr2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc")); + stringAttr3 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("ABC")); + stringAttr4 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("def")); + + booleanAttrT1 = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(true)); + booleanAttrT2 = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(true)); + booleanAttrF1 = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + booleanAttrF2 = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + + intAttr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); + intAttr1a = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); + intAttr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(2)); + intAttr0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); + intAttrNeg1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(-1)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + } + + + + + /** + * String (matching case) + */ + @Test + public void testString_Equal() { + + // String exact match + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_STRING_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check "abc" with "abc" - separate string objects with same value + arguments.add(stringAttr1); + arguments.add(stringAttr2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check "abc" with "ABC" (not same) + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(stringAttr3); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + + + /** + * Boolean + */ + @Test + public void testBoolean_Equal() { + + // String exact match + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_BOOLEAN_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_BOOLEAN_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check separate objects with same value + arguments.add(booleanAttrT1); + arguments.add(booleanAttrT2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check different values + arguments.clear(); + arguments.add(booleanAttrT1); + arguments.add(booleanAttrF1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + + /** + * Integer + */ + @Test + public void testInteger_Equal() { + + // String exact match + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_INTEGER_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_INTEGER_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check separate objects with same value + arguments.add(intAttr1); + arguments.add(intAttr1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check not same + arguments.clear(); + arguments.add(intAttr1); + arguments.add(intAttr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + arguments.clear(); + arguments.add(intAttr1); + arguments.add(intAttrNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + + + /** + * Double + */ + @Test + public void testDouble_Equal() { + FunctionArgumentAttributeValue attr1 = null; + FunctionArgumentAttributeValue attr1a = null; + FunctionArgumentAttributeValue attr2 = null; + FunctionArgumentAttributeValue attrNeg1 = null; + try { + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.0)); + attr1a = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.0)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(2.4)); + attrNeg1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(-1.0)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + // String exact match + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_DOUBLE_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DOUBLE_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check separate objects with the same value + arguments.add(attr1); + arguments.add(attr1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check not same + arguments.clear(); + arguments.add(attr1); + arguments.add(attr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + arguments.clear(); + arguments.add(attr1); + arguments.add(attrNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + + + + + /** + * Date + */ + @Test + public void testDate_Equal() { + Calendar calendar = Calendar.getInstance(); + Date today = calendar.getTime(); + Date longAgo = new Date(1234); + // create a date that is different than "today" but within the same day (i.e. has a different hour) + if (calendar.get(Calendar.HOUR_OF_DAY) > 3) { + calendar.set(Calendar.HOUR_OF_DAY, 3); + } else { + calendar.set(Calendar.HOUR_OF_DAY, 5); + } + Date todayPlus = calendar.getTime(); + + + FunctionArgumentAttributeValue attrToday = null; + FunctionArgumentAttributeValue attrToday2 = null; + FunctionArgumentAttributeValue attrLaterToday = null; + FunctionArgumentAttributeValue attrYesterday = null; + try { + attrToday = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(today)); + attrToday2 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(today)); + attrLaterToday = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(todayPlus)); + attrYesterday = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue(longAgo)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + // String exact match + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_DATE_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATE_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check separate objects with the same value + arguments.add(attrToday); + arguments.add(attrToday2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check not same + arguments.clear(); + arguments.add(attrToday); + arguments.add(attrYesterday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // Date objects with different times but within the same day should match + arguments.clear(); + arguments.add(attrToday); + arguments.add(attrLaterToday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + + + + /** + * Time + */ + @Test + public void testTime_Equal() { + + Date now = new Date(); + Date now2 = new Date(now.getTime()); + Date notNow = new Date(now.getTime() - 100000); + + FunctionArgumentAttributeValue attrNow = null; + FunctionArgumentAttributeValue attrNow2 = null; + FunctionArgumentAttributeValue attrNotNow = null; + try { + attrNow = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(now)); + attrNow2 = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(now2)); + attrNotNow = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue(notNow)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + // String exact match + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_TIME_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_TIME_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check separate objects with the same value + arguments.add(attrNow); + arguments.add(attrNow2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check not same + arguments.clear(); + arguments.add(attrNow); + arguments.add(attrNotNow); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + + + + /** + * DateTime + */ + @Test + public void testDateTime_Equal() { + Calendar calendar = Calendar.getInstance(); + Date today = calendar.getTime(); + Date longAgo = new Date(1234); + // create a dateTime that is different than "today" changing only the Timezone + if (calendar.get(Calendar.ZONE_OFFSET) > 3) { + calendar.set(Calendar.ZONE_OFFSET, 3); + } else { + calendar.set(Calendar.ZONE_OFFSET, 5); + } + Date todayPlus = calendar.getTime(); + + + FunctionArgumentAttributeValue attrToday = null; + FunctionArgumentAttributeValue attrToday2 = null; + FunctionArgumentAttributeValue attrLaterToday = null; + FunctionArgumentAttributeValue attrYesterday = null; + try { + attrToday = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(today)); + attrToday2 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(today)); + attrLaterToday = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(todayPlus)); + attrYesterday = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue(longAgo)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + // String exact match + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_DATETIME_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATETIME_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check separate objects with the same value + arguments.add(attrToday); + arguments.add(attrToday2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check not same + arguments.clear(); + arguments.add(attrToday); + arguments.add(attrYesterday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // DateTime with different Zones should not match + arguments.clear(); + arguments.add(attrToday); + arguments.add(attrLaterToday); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + + /** + * dayTimeDuration - Version1 + */ + @Test + public void testDayTimeDuration_Equal_V1() { + + XPathDayTimeDuration dur1 = new XPathDayTimeDuration(1, 3, 5, 12, 38); + XPathDayTimeDuration dur2 = new XPathDayTimeDuration(1, 3, 5, 12, 38); + XPathDayTimeDuration differentDur = new XPathDayTimeDuration(-1, 4, 7, 5, 33); + + FunctionArgumentAttributeValue attrDur1 = null; + FunctionArgumentAttributeValue attrDur2 = null; + FunctionArgumentAttributeValue attrDifferentDur = null; + try { + attrDur1 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(dur1)); + attrDur2 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(dur2)); + attrDifferentDur = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(differentDur)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_DAYTIMEDURATION_EQUAL_VERSION1; + + // check identity and type of the thing created + assertEquals(XACML1.ID_FUNCTION_DAYTIMEDURATION_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_DAYTIMEDURATION.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check separate objects with the same value + arguments.add(attrDur1); + arguments.add(attrDur2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check not same + arguments.clear(); + arguments.add(attrDur1); + arguments.add(attrDifferentDur); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + + /** + * dayTimeDuration - Current version + */ + @Test + public void testDayTimeDuration_Equal() { + + XPathDayTimeDuration dur1 = new XPathDayTimeDuration(1, 3, 5, 12, 38); + XPathDayTimeDuration dur2 = new XPathDayTimeDuration(1, 3, 5, 12, 38); + XPathDayTimeDuration differentDur = new XPathDayTimeDuration(-1, 4, 7, 5, 33); + + FunctionArgumentAttributeValue attrDur1 = null; + FunctionArgumentAttributeValue attrDur2 = null; + FunctionArgumentAttributeValue attrDifferentDur = null; + try { + attrDur1 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(dur1)); + attrDur2 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(dur2)); + attrDifferentDur = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(differentDur)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_DAYTIMEDURATION_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DAYTIMEDURATION_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_DAYTIMEDURATION.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check separate objects with the same value + arguments.add(attrDur1); + arguments.add(attrDur2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check not same + arguments.clear(); + arguments.add(attrDur1); + arguments.add(attrDifferentDur); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + + + /** + * dayTimeDuration - Version1 + */ + @Test + public void testYearMonthDuration_Equal_V1() { + + XPathYearMonthDuration dur1 = new XPathYearMonthDuration(1, 3, 5); + XPathYearMonthDuration dur2 = new XPathYearMonthDuration(1, 3, 5); + XPathYearMonthDuration differentDur = new XPathYearMonthDuration(-1, 4, 7); + + FunctionArgumentAttributeValue attrDur1 = null; + FunctionArgumentAttributeValue attrDur2 = null; + FunctionArgumentAttributeValue attrDifferentDur = null; + try { + attrDur1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(dur1)); + attrDur2 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(dur2)); + attrDifferentDur = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(differentDur)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_YEARMONTHDURATION_EQUAL_VERSION1; + + // check identity and type of the thing created + assertEquals(XACML1.ID_FUNCTION_YEARMONTHDURATION_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_YEARMONTHDURATION.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check separate objects with the same value + arguments.add(attrDur1); + arguments.add(attrDur2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check not same + arguments.clear(); + arguments.add(attrDur1); + arguments.add(attrDifferentDur); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + + + + /** + * dayTimeDuration - Current version + */ + @Test + public void testYearMonthDuration_Equal() { + + XPathYearMonthDuration dur1 = new XPathYearMonthDuration(1, 3, 5); + XPathYearMonthDuration dur2 = new XPathYearMonthDuration(1, 3, 5); + XPathYearMonthDuration differentDur = new XPathYearMonthDuration(-1, 4, 7); + + FunctionArgumentAttributeValue attrDur1 = null; + FunctionArgumentAttributeValue attrDur2 = null; + FunctionArgumentAttributeValue attrDifferentDur = null; + try { + attrDur1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(dur1)); + attrDur2 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(dur2)); + attrDifferentDur = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(differentDur)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_YEARMONTHDURATION_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_YEARMONTHDURATION_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_YEARMONTHDURATION.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check separate objects with the same value + arguments.add(attrDur1); + arguments.add(attrDur2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check not same + arguments.clear(); + arguments.add(attrDur1); + arguments.add(attrDifferentDur); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + + /** + * URI + */ + @Test + public void testAnyURI_Equal() { + + URI uri1 = null; + URI uri2 = null; + URI uriNotThere = null; + try { + uri1 = new URI("http://someplace.com/gothere"); + uri2 = new URI("http://someplace.com/gothere"); + uriNotThere = new URI("http://someplace.com/notGoingThere"); + } catch (Exception e) { + fail(e.toString()); + } + + FunctionArgumentAttributeValue attrUri1 = null; + FunctionArgumentAttributeValue attrUri2 = null; + FunctionArgumentAttributeValue attrUriNotThere = null; + try { + attrUri1 = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(uri1)); + attrUri2 = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(uri2)); + attrUriNotThere = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(uriNotThere)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_ANYURI_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_ANYURI_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_ANYURI.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check separate objects with the same value + arguments.add(attrUri1); + arguments.add(attrUri2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check not same + arguments.clear(); + arguments.add(attrUri1); + arguments.add(attrUriNotThere); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + + /** + * X500Name + */ + @Test + public void testX500Name_Equal() { + + X500Principal name1 = new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US"); + X500Principal name2 = new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US"); + X500Principal name3 = new X500Principal("CN=NotDuke, OU=NotThere, O=Oracle, C=US"); + + + FunctionArgumentAttributeValue attrName1 = null; + FunctionArgumentAttributeValue attrName1a = null; + FunctionArgumentAttributeValue attrNotSameName = null; + try { + attrName1 = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(name1)); + attrName1a = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(name2)); + attrNotSameName = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(name3)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_X500NAME_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_X500NAME_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_X500NAME.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check separate objects with the same value + arguments.add(attrName1); + arguments.add(attrName1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check not same + arguments.clear(); + arguments.add(attrName1); + arguments.add(attrNotSameName); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + + + /** + * RFC822Name + */ + @Test + public void testRfc822Name_Equal() { + + RFC822Name name1 = null; + RFC822Name name1a = null; + RFC822Name differentLocalName = null; + RFC822Name differentDomainName = null; + RFC822Name localCaseName = null; + RFC822Name domainCaseName = null; + @SuppressWarnings("unused") + RFC822Name noAtName = null; + + try { + name1 = RFC822Name.newInstance("localPart@DomainPart"); + name1a = RFC822Name.newInstance("localPart@DomainPart"); + differentLocalName = RFC822Name.newInstance("differentlocalPart@DomainPart"); + differentDomainName = RFC822Name.newInstance("localPart@differentDomainPart"); + localCaseName = RFC822Name.newInstance("LOCALPart@DomainPart"); + domainCaseName = RFC822Name.newInstance("localPart@DOMAINPart"); + + + } catch (Exception e) { + fail(e.toString()); + } + + // should not be able to create a name without an @. If you try, newInstance returns null + Exception exSeen = null; + try { + noAtName = RFC822Name.newInstance("nameWithoutAnAtSign"); + } catch (Exception e) { + exSeen = e; + } + assertNotNull(exSeen); + + + FunctionArgumentAttributeValue attrName1 = null; + FunctionArgumentAttributeValue attrName1a = null; + FunctionArgumentAttributeValue attrDifferentLocalName = null; + FunctionArgumentAttributeValue attrDifferentDomainName = null; + FunctionArgumentAttributeValue attrLocalCaseName = null; + FunctionArgumentAttributeValue attrDomainCaseName = null; + try { + attrName1 = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(name1)); + attrName1a = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(name1a)); + attrDifferentLocalName = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(differentLocalName)); + attrDifferentDomainName = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(differentDomainName)); + attrLocalCaseName = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(localCaseName)); + attrDomainCaseName = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(domainCaseName)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_RFC822NAME_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_RFC822NAME_EQUAL, fd.getId()); + assertEquals(DataTypeRFC822Name.newInstance().getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check separate objects with the same value + arguments.add(attrName1); + arguments.add(attrName1a); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check not same Local + arguments.clear(); + arguments.add(attrName1); + arguments.add(attrDifferentLocalName); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // check not same Domain + arguments.clear(); + arguments.add(attrName1); + arguments.add(attrDifferentDomainName); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // test case-sensitivity in local part + arguments.clear(); + arguments.add(attrName1); + arguments.add(attrLocalCaseName); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // test non-case-sensitivity in Domain part + arguments.clear(); + arguments.add(attrName1); + arguments.add(attrDomainCaseName); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + + /** + * Hex Binary + */ + @Test + public void testHexBinary_Equal() { + HexBinary binary = null; + HexBinary sameBinary = null; + HexBinary differentBinary = null; + try { + binary = HexBinary.newInstance("e04fd020ea3a6910a2d808002b30309d"); + sameBinary = HexBinary.newInstance("e04fd020ea3a6910a2d808002b30309d"); + differentBinary = HexBinary.newInstance("f123a890ee3d"); + } catch (Exception e) { + fail(e.toString()); + } + + FunctionArgumentAttributeValue attrBinary = null; + FunctionArgumentAttributeValue attrSameBinary = null; + FunctionArgumentAttributeValue attrDifferentBinary = null;; + try { + attrBinary = new FunctionArgumentAttributeValue(DataTypes.DT_HEXBINARY.createAttributeValue(binary)); + attrSameBinary = new FunctionArgumentAttributeValue(DataTypes.DT_HEXBINARY.createAttributeValue(sameBinary)); + attrDifferentBinary = new FunctionArgumentAttributeValue(DataTypes.DT_HEXBINARY.createAttributeValue(differentBinary)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_HEXBINARY_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_HEXBINARY_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_HEXBINARY.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check separate objects with the same value + arguments.add(attrBinary); + arguments.add(attrSameBinary); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check not same + arguments.clear(); + arguments.add(attrBinary); + arguments.add(attrDifferentBinary); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } + + + /** + * Base64 Binary + */ + @Test + public void testBase64Binary_Equal() { + Base64Binary binary = null; + Base64Binary sameBinary = null; + Base64Binary differentBinary = null; + try { + binary = Base64Binary.newInstance("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz"); + sameBinary = Base64Binary.newInstance("TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz"); + differentBinary = Base64Binary.newInstance("f123a890ee3d"); + } catch (Exception e) { + fail(e.toString()); + } + + FunctionArgumentAttributeValue attrBinary = null; + FunctionArgumentAttributeValue attrSameBinary = null; + FunctionArgumentAttributeValue attrDifferentBinary = null; + try { + attrBinary = new FunctionArgumentAttributeValue(DataTypes.DT_BASE64BINARY.createAttributeValue(binary)); + attrSameBinary = new FunctionArgumentAttributeValue(DataTypes.DT_BASE64BINARY.createAttributeValue(sameBinary)); + attrDifferentBinary = new FunctionArgumentAttributeValue(DataTypes.DT_BASE64BINARY.createAttributeValue(differentBinary)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_BASE64BINARY_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_BASE64BINARY_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_BASE64BINARY.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + // test normal equals and non-equals + // check separate objects with the same value + arguments.add(attrBinary); + arguments.add(attrSameBinary); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check not same + arguments.clear(); + arguments.add(attrBinary); + arguments.add(attrDifferentBinary); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + } +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionHigherOrderBagTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionHigherOrderBagTest.java new file mode 100644 index 000000000..95a83d76e --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionHigherOrderBagTest.java @@ -0,0 +1,2193 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.Bag; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentBag; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionHigherOrderBagTest { + + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + + + // + // ANY-OF tests + // + + + @Test + public void testAny_of() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String f = "f"; + String g = "g"; + String h = "h"; + String j = "j"; + + + Bag bagabcdefg = null; + Bag bagbdfhj = null; + Bag bagace = null; + Bag bagb = null; + Bag bagaaacccef = null; + Bag bagInt = null; + Bag bagStringInt = null; + Bag bagEmpty = null; + Bag bagStringBooleansTrue = null; + Bag bagStringBooleansFalse = null; + + + // primitive attrs + FunctionArgumentAttributeValue attra = null; + FunctionArgumentAttributeValue attrb = null; + FunctionArgumentAttributeValue attrh = null; + + + // predicates passed as arguments + FunctionArgumentAttributeValue attrPredicateStringEqual = null; + FunctionArgumentAttributeValue attrPredicateStringIntersection = null; + FunctionArgumentAttributeValue attrPredicateBooleanFromString = null; + + try { + + // Create Bag contents + bagabcdefg = new Bag(); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); + bagbdfhj = new Bag(); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); + bagace = new Bag(); + bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagb = new Bag(); + bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagaaacccef = new Bag(); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagInt = new Bag(); + bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagStringInt = new Bag(); + bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagEmpty = new Bag(); + bagStringBooleansTrue = new Bag(); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); + bagStringBooleansFalse = new Bag(); + bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); + + + // create primitive attrs + attra = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(a)); + attrb = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(b)); + attrh = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(h)); + + + // predicates passed as function arguments + attrPredicateStringEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_EQUAL)); + attrPredicateStringIntersection = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_INTERSECTION)); + attrPredicateBooleanFromString = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_BOOLEAN_FROM_STRING)); + + } catch (Exception ex) { + fail("creating attribute e="+ ex); + } + + // make into attributes + FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); + FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); + FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); + FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); + FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); + FunctionArgumentBag attrBagStringBooleansTrue = new FunctionArgumentBag(bagStringBooleansTrue); + FunctionArgumentBag attrBagStringBooleansFalse = new FunctionArgumentBag(bagStringBooleansFalse); + + FunctionDefinitionHigherOrderBag fd = (FunctionDefinitionHigherOrderBag) StdFunctions.FD_ANY_OF; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_ANY_OF, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + // normal match + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attra); + arguments.add(attrBagabcdefg); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // bag in first position - match + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrBagabcdefg); + arguments.add(attra); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // normal no-match + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attra); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // multiple primitives + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrh); + arguments.add(attrb); + arguments.add(attrBagace); + arguments.add(attra); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of Predicate error: function:string-equal Expected 2 arguments, got 4", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // no primitives - predicate function expects 2 + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of Predicate error: function:string-equal Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // no primitives - predicate expects only 1 arg + arguments.clear(); + arguments.add(attrPredicateBooleanFromString); + arguments.add(attrBagStringBooleansTrue); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + arguments.clear(); + arguments.add(attrPredicateBooleanFromString); + arguments.add(attrBagStringBooleansFalse); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // bag is empty + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrh); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // no bag + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrh); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of Did not get any Bag argument; must have at least 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // extra bag + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrh); + arguments.add(attrBagStringBooleansTrue); + arguments.add(attrh); + arguments.add(attrBagStringBooleansTrue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of must have only 1 bag; found one at index 2 and another at 4", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // bad predicate + arguments.clear(); + arguments.add(attrh); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of First argument expected URI, got http://www.w3.org/2001/XMLSchema#string", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // non-boolean predicate + arguments.clear(); + arguments.add(attrPredicateStringIntersection); + arguments.add(attrh); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of Predicate Function must return boolean, but 'urn:oasis:names:tc:xacml:1.0:function:string-intersection' returns 'string", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // predicate after first arg + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrPredicateStringIntersection); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of Predicate error: function:string-equal Expected data type 'string' saw 'anyURI' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bags of different types + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrh); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + // first null + arguments.clear(); + arguments.add(null); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of Predicate Function (first argument) was null", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second null + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrBagabcdefg); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of Got null argument at index 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + + @Test + public void testAll_of() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String f = "f"; + String g = "g"; + String h = "h"; + String j = "j"; + + String w = "w"; + + + Bag bagabcdefg = null; + Bag bagbdfhj = null; + Bag bagace = null; + Bag bagb = null; + Bag bagaaacccef = null; + Bag bagInt = null; + Bag bagStringInt = null; + Bag bagEmpty = null; + Bag bagStringBooleansFalse = null; + Bag bagStringBooleansTrue = null; + + + // primitive attrs + FunctionArgumentAttributeValue attra = null; + FunctionArgumentAttributeValue attrh = null; + FunctionArgumentAttributeValue attrw = null; + + + + // predicates passed as arguments + FunctionArgumentAttributeValue attrPredicateStringEqual = null; + FunctionArgumentAttributeValue attrPredicateStringIntersection = null; + FunctionArgumentAttributeValue attrPredicateStringGreaterThan = null; + FunctionArgumentAttributeValue attrPredicateBooleanFromString = null; + + try { + + // Create Bag contents + bagabcdefg = new Bag(); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); + bagbdfhj = new Bag(); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); + bagace = new Bag(); + bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagb = new Bag(); + bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagaaacccef = new Bag(); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagInt = new Bag(); + bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagStringInt = new Bag(); + bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagEmpty = new Bag(); + bagStringBooleansTrue = new Bag(); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); + bagStringBooleansFalse = new Bag(); + bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); + + + + // create primitive attrs + attra = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(a)); + attrh = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(h)); + attrw = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(w)); + + + // predicates passed as function arguments + attrPredicateStringEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_EQUAL)); + attrPredicateStringIntersection = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_INTERSECTION)); + attrPredicateStringGreaterThan = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_GREATER_THAN)); + attrPredicateBooleanFromString = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_BOOLEAN_FROM_STRING)); + + } catch (Exception ex) { + fail("creating attribute e="+ ex); + } + + // make into attributes + FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); + FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); + FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); + FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); + FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); + FunctionArgumentBag attrBagStringBooleansTrue = new FunctionArgumentBag(bagStringBooleansTrue); + FunctionArgumentBag attrBagStringBooleansFalse = new FunctionArgumentBag(bagStringBooleansFalse); + + FunctionDefinitionHigherOrderBag fd = (FunctionDefinitionHigherOrderBag) StdFunctions.FD_ALL_OF; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_ALL_OF, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + // normal match + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrw); + arguments.add(attrBagace); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // normal no-match + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attra); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // no primitives - predicate function expects 2 + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of Predicate error: function:string-equal Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // no primitives - predicate expects only 1 arg + arguments.clear(); + arguments.add(attrPredicateBooleanFromString); + arguments.add(attrBagStringBooleansTrue); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + arguments.clear(); + arguments.add(attrPredicateBooleanFromString); + arguments.add(attrBagStringBooleansFalse); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // bag is empty + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrh); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // no bag + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrh); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of Did not get any Bag argument; must have at least 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // extra bag + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrh); + arguments.add(attrBagStringBooleansTrue); + arguments.add(attrh); + arguments.add(attrBagStringBooleansTrue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of must have only 1 bag; found one at index 2 and another at 4", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // bad predicate + arguments.clear(); + arguments.add(attrh); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of First argument expected URI, got http://www.w3.org/2001/XMLSchema#string", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // non-boolean predicate + arguments.clear(); + arguments.add(attrPredicateStringIntersection); + arguments.add(attrh); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of Predicate Function must return boolean, but 'urn:oasis:names:tc:xacml:1.0:function:string-intersection' returns 'string", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // predicate after first arg + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrPredicateStringIntersection); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of Predicate error: function:string-greater-than Expected data type 'string' saw 'anyURI' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bags of different types + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrh); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + // first null + arguments.clear(); + arguments.add(null); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of Predicate Function (first argument) was null", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second null + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagabcdefg); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of Got null argument at index 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + + + + + + + + + + @Test + public void testAny_of_any() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String f = "f"; + String g = "g"; + String h = "h"; + String j = "j"; + + String w = "w"; + + + Bag bagabcdefg = null; + Bag bagbdfhj = null; + Bag bagace = null; + Bag bagb = null; + Bag bagaaacccef = null; + Bag bagInt = null; + Bag bagStringInt = null; + Bag bagEmpty = null; + Bag bagStringBooleansFalse = null; + Bag bagStringBooleansTrue = null; + Bag bagBooleansFalse = null; + Bag bagBooleansTrue = null; + + + // primitive attrs + FunctionArgumentAttributeValue attra = null; + FunctionArgumentAttributeValue attrh = null; + FunctionArgumentAttributeValue attrw = null; + + + FunctionArgumentAttributeValue attrInt4 = null; + + + // predicates passed as arguments + FunctionArgumentAttributeValue attrPredicateStringEqual = null; + FunctionArgumentAttributeValue attrPredicateStringIntersection = null; + FunctionArgumentAttributeValue attrPredicateStringGreaterThan = null; + FunctionArgumentAttributeValue attrPredicateBooleanFromString = null; + FunctionArgumentAttributeValue attrPredicateNof = null; + + try { + + // Create Bag contents + bagabcdefg = new Bag(); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); + bagbdfhj = new Bag(); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); + bagace = new Bag(); + bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagb = new Bag(); + bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagaaacccef = new Bag(); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagInt = new Bag(); + bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagStringInt = new Bag(); + bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagEmpty = new Bag(); + bagStringBooleansTrue = new Bag(); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); + bagStringBooleansFalse = new Bag(); + bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagBooleansTrue = new Bag(); + bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(true)); + bagBooleansFalse = new Bag(); + bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + + + // create primitive attrs + attra = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(a)); + attrh = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(h)); + attrw = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(w)); + + attrInt4 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(4)); + + + // predicates passed as function arguments + attrPredicateStringEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_EQUAL)); + attrPredicateStringIntersection = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_INTERSECTION)); + attrPredicateStringGreaterThan = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_GREATER_THAN)); + attrPredicateBooleanFromString = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_BOOLEAN_FROM_STRING)); + attrPredicateNof = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_N_OF)); + + } catch (Exception ex) { + fail("creating attribute e="+ ex); + } + + // make into attributes + FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); + FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); + FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); + FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); + FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); + FunctionArgumentBag attrBagStringBooleansTrue = new FunctionArgumentBag(bagStringBooleansTrue); + FunctionArgumentBag attrBagStringBooleansFalse = new FunctionArgumentBag(bagStringBooleansFalse); + FunctionArgumentBag attrBagBooleansTrue = new FunctionArgumentBag(bagBooleansTrue); + FunctionArgumentBag attrBagBooleansFalse = new FunctionArgumentBag(bagBooleansFalse); + + FunctionDefinitionHigherOrderBag fd = (FunctionDefinitionHigherOrderBag) StdFunctions.FD_ANY_OF_ANY; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_ANY_OF_ANY, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + // normal match + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrw); + arguments.add(attrBagace); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // normal no-match + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attra); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // no primitives - predicate function expects 2 + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-any Predicate error: function:string-equal Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrBagace); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // no primitives - predicate expects only 1 arg + arguments.clear(); + arguments.add(attrPredicateBooleanFromString); + arguments.add(attrBagStringBooleansTrue); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + arguments.clear(); + arguments.add(attrPredicateBooleanFromString); + arguments.add(attrBagStringBooleansFalse); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // n-of with lots of bags - success + arguments.clear(); + arguments.add(attrPredicateNof); + arguments.add(attrInt4); + arguments.add(attrBagBooleansTrue); + arguments.add(attrBagBooleansTrue); + arguments.add(attrBagBooleansTrue); + arguments.add(attrBagBooleansTrue); + arguments.add(attrBagBooleansTrue); + arguments.add(attrBagBooleansTrue); + arguments.add(attrBagBooleansTrue); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // n-of with lots of bags - fail + arguments.clear(); + arguments.add(attrPredicateNof); + arguments.add(attrInt4); + arguments.add(attrBagBooleansFalse); + arguments.add(attrBagBooleansFalse); + arguments.add(attrBagBooleansTrue); + arguments.add(attrBagBooleansTrue); + arguments.add(attrBagBooleansFalse); + arguments.add(attrBagBooleansFalse); + arguments.add(attrBagBooleansFalse); + arguments.add(attrBagBooleansFalse); + arguments.add(attrBagBooleansFalse); + arguments.add(attrBagBooleansFalse); + arguments.add(attrBagBooleansFalse); + arguments.add(attrBagBooleansFalse); + arguments.add(attrBagBooleansFalse); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + + // bag is empty + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrh); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-any Bag is empty at index 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // no bag + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrh); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-any Predicate error: function:string-greater-than Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrh); + arguments.add(attrh); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // bad predicate + arguments.clear(); + arguments.add(attrh); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-any First argument expected URI, got http://www.w3.org/2001/XMLSchema#string", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // non-boolean predicate + arguments.clear(); + arguments.add(attrPredicateStringIntersection); + arguments.add(attrh); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-any Predicate Function must return boolean, but 'urn:oasis:names:tc:xacml:1.0:function:string-intersection' returns 'string", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // predicate after first arg + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrPredicateStringIntersection); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-any Predicate error: function:string-greater-than Expected data type 'string' saw 'anyURI' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bags of different types + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrh); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first null + arguments.clear(); + arguments.add(null); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-any Predicate Function (first argument) was null", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second null + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagabcdefg); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-any Got null argument at index 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + + + + + + + + + + + + @Test + public void testAll_of_any() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String f = "f"; + String g = "g"; + String h = "h"; + String j = "j"; + + String w = "w"; + String x = "x"; + + + Bag bagabcdefg = null; + Bag bagbdfhj = null; + Bag bagace = null; + Bag bagb = null; + Bag bagaaacccef = null; + Bag bagawx = null; + Bag bagInt = null; + Bag bagStringInt = null; + Bag bagEmpty = null; + Bag bagStringBooleansFalse = null; + Bag bagStringBooleansTrue = null; + Bag bagBooleansFalse = null; + Bag bagBooleansTrue = null; + + + // primitive attrs + FunctionArgumentAttributeValue attra = null; + FunctionArgumentAttributeValue attrh = null; + + + + + // predicates passed as arguments + FunctionArgumentAttributeValue attrPredicateStringEqual = null; + FunctionArgumentAttributeValue attrPredicateStringIntersection = null; + FunctionArgumentAttributeValue attrPredicateStringLessThan = null; + FunctionArgumentAttributeValue attrPredicateStringGreaterThan = null; + FunctionArgumentAttributeValue attrPredicateBooleanFromString = null; + + try { + + // Create Bag contents + bagabcdefg = new Bag(); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); + bagbdfhj = new Bag(); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); + bagace = new Bag(); + bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagb = new Bag(); + bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagaaacccef = new Bag(); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagawx = new Bag(); + bagawx.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagawx.add(DataTypes.DT_STRING.createAttributeValue(w)); + bagawx.add(DataTypes.DT_STRING.createAttributeValue(x)); + bagInt = new Bag(); + bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagStringInt = new Bag(); + bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagEmpty = new Bag(); + bagStringBooleansTrue = new Bag(); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); + bagStringBooleansFalse = new Bag(); + bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagBooleansTrue = new Bag(); + bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(true)); + bagBooleansFalse = new Bag(); + bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + + + // create primitive attrs + attra = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(a)); + attrh = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(h)); + + + + // predicates passed as function arguments + attrPredicateStringEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_EQUAL)); + attrPredicateStringIntersection = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_INTERSECTION)); + attrPredicateStringLessThan = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_LESS_THAN)); + attrPredicateStringGreaterThan = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_GREATER_THAN)); + attrPredicateBooleanFromString = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_BOOLEAN_FROM_STRING)); + + } catch (Exception ex) { + fail("creating attribute e="+ ex); + } + + // make into attributes + FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); + FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); + FunctionArgumentBag attrBagawx = new FunctionArgumentBag(bagawx); + FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); + FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); + FunctionArgumentBag attrBagStringBooleansTrue = new FunctionArgumentBag(bagStringBooleansTrue); + + FunctionDefinitionHigherOrderBag fd = (FunctionDefinitionHigherOrderBag) StdFunctions.FD_ALL_OF_ANY; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_ALL_OF_ANY, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + // normal match + arguments.clear(); + arguments.add(attrPredicateStringLessThan); + arguments.add(attrBagabcdefg); + arguments.add(attrBagawx); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // normal no-match + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagace); + arguments.add(attrBagawx); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // primitive instead of bag + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attra); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-any 2nd argument must be bag, got 'string'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrBagace); + arguments.add(attra); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-any 3rd argument must be bag, got 'string'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // no primitives - predicate expects only 1 arg + arguments.clear(); + arguments.add(attrPredicateBooleanFromString); + arguments.add(attrBagStringBooleansTrue); + arguments.add(attrBagStringBooleansTrue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-any Predicate error: function:boolean-from-string Expected 1 arguments, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + + // bag is empty + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagace); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagEmpty); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // no bag + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrh); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-any Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // bad predicate + arguments.clear(); + arguments.add(attrh); + arguments.add(attrBagStringInt); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-any First argument expected URI, got http://www.w3.org/2001/XMLSchema#string", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // non-boolean predicate + arguments.clear(); + arguments.add(attrPredicateStringIntersection); + arguments.add(attrBagStringInt); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-any Predicate Function must return boolean, but 'urn:oasis:names:tc:xacml:1.0:function:string-intersection' returns 'string", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // predicate after first arg + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrPredicateStringIntersection); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-any 2nd argument must be bag, got 'anyURI'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bags of different types + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagace); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-any Predicate error: function:string-greater-than Expected data type 'string' saw 'integer' at arg index 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // no args + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-any Expected at least 2 arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // one arg + arguments.clear(); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-any Expected at least 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many args + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-any Expected 3 arguments, got 4", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // first null + arguments.clear(); + arguments.add(null); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-any Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second null + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagabcdefg); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-any 3rd argument must be bag, got 'null'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + + + + + + + + + @Test + public void testAny_of_all() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String f = "f"; + String g = "g"; + String h = "h"; + String j = "j"; + + String w = "w"; + String x = "x"; + + + Bag bagabcdefg = null; + Bag bagbdfhj = null; + Bag bagace = null; + Bag bagb = null; + Bag bagaaacccef = null; + Bag bagewx = null; + Bag bagInt = null; + Bag bagStringInt = null; + Bag bagEmpty = null; + Bag bagStringBooleansFalse = null; + Bag bagStringBooleansTrue = null; + Bag bagBooleansFalse = null; + Bag bagBooleansTrue = null; + + + // primitive attrs + FunctionArgumentAttributeValue attra = null; + FunctionArgumentAttributeValue attrh = null; + + + + + // predicates passed as arguments + FunctionArgumentAttributeValue attrPredicateStringEqual = null; + FunctionArgumentAttributeValue attrPredicateStringIntersection = null; + FunctionArgumentAttributeValue attrPredicateStringGreaterThanOrEqual = null; + FunctionArgumentAttributeValue attrPredicateStringGreaterThan = null; + FunctionArgumentAttributeValue attrPredicateBooleanFromString = null; + + try { + + // Create Bag contents + bagabcdefg = new Bag(); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); + bagbdfhj = new Bag(); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); + bagace = new Bag(); + bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagb = new Bag(); + bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagaaacccef = new Bag(); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagewx = new Bag(); + bagewx.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagewx.add(DataTypes.DT_STRING.createAttributeValue(w)); + bagewx.add(DataTypes.DT_STRING.createAttributeValue(x)); + bagInt = new Bag(); + bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagStringInt = new Bag(); + bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagEmpty = new Bag(); + bagStringBooleansTrue = new Bag(); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); + bagStringBooleansFalse = new Bag(); + bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagBooleansTrue = new Bag(); + bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(true)); + bagBooleansFalse = new Bag(); + bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + + + // create primitive attrs + attra = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(a)); + attrh = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(h)); + + + + // predicates passed as function arguments + attrPredicateStringEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_EQUAL)); + attrPredicateStringIntersection = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_INTERSECTION)); + attrPredicateStringGreaterThanOrEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_GREATER_THAN_OR_EQUAL)); + attrPredicateStringGreaterThan = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_GREATER_THAN)); + attrPredicateBooleanFromString = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_BOOLEAN_FROM_STRING)); + + } catch (Exception ex) { + fail("creating attribute e="+ ex); + } + + // make into attributes + FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); + FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); + FunctionArgumentBag attrBagewx = new FunctionArgumentBag(bagewx); + FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); + FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); + FunctionArgumentBag attrBagStringBooleansTrue = new FunctionArgumentBag(bagStringBooleansTrue); + + FunctionDefinitionHigherOrderBag fd = (FunctionDefinitionHigherOrderBag) StdFunctions.FD_ANY_OF_ALL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_ANY_OF_ALL, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + // normal match + arguments.clear(); + arguments.add(attrPredicateStringGreaterThanOrEqual); + arguments.add(attrBagewx); + arguments.add(attrBagace); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // normal no-match + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagace); + arguments.add(attrBagewx); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // primitive instead of bag + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attra); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-all 2nd argument must be bag, got 'string'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrBagace); + arguments.add(attra); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-all 3rd argument must be bag, got 'string'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // no primitives - predicate expects only 1 arg + arguments.clear(); + arguments.add(attrPredicateBooleanFromString); + arguments.add(attrBagStringBooleansTrue); + arguments.add(attrBagStringBooleansTrue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-all Predicate error: function:boolean-from-string Expected 1 arguments, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bag is empty + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagace); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagEmpty); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // no bag + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrh); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-all Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // bad predicate + arguments.clear(); + arguments.add(attrh); + arguments.add(attrBagStringInt); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-all First argument expected URI, got http://www.w3.org/2001/XMLSchema#string", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // non-boolean predicate + arguments.clear(); + arguments.add(attrPredicateStringIntersection); + arguments.add(attrBagStringInt); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-all Predicate Function must return boolean, but 'urn:oasis:names:tc:xacml:1.0:function:string-intersection' returns 'string", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // predicate after first arg + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrPredicateStringIntersection); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-all 2nd argument must be bag, got 'anyURI'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bags of different types + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagace); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-all Predicate error: function:string-greater-than Expected data type 'string' saw 'integer' at arg index 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // no args + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-all Expected at least 2 arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // one arg + arguments.clear(); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-all Expected at least 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many args + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-all Expected 3 arguments, got 4", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // first null + arguments.clear(); + arguments.add(null); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-all Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second null + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagabcdefg); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:any-of-all 3rd argument must be bag, got 'null'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + + + @Test + public void testAll_of_all() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String f = "f"; + String g = "g"; + String h = "h"; + String j = "j"; + + String w = "w"; + String x = "x"; + + + Bag bagabcdefg = null; + Bag bagbdfhj = null; + Bag bagace = null; + Bag bagb = null; + Bag bagaaacccef = null; + Bag bagawx = null; + Bag bagwx = null; + Bag bagInt = null; + Bag bagStringInt = null; + Bag bagEmpty = null; + Bag bagStringBooleansFalse = null; + Bag bagStringBooleansTrue = null; + Bag bagBooleansFalse = null; + Bag bagBooleansTrue = null; + + + // primitive attrs + FunctionArgumentAttributeValue attra = null; + FunctionArgumentAttributeValue attrh = null; + + + + + // predicates passed as arguments + FunctionArgumentAttributeValue attrPredicateStringEqual = null; + FunctionArgumentAttributeValue attrPredicateStringIntersection = null; + FunctionArgumentAttributeValue attrPredicateStringGreaterThan = null; + FunctionArgumentAttributeValue attrPredicateBooleanFromString = null; + + try { + + // Create Bag contents + bagabcdefg = new Bag(); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); + bagbdfhj = new Bag(); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); + bagace = new Bag(); + bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagb = new Bag(); + bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagaaacccef = new Bag(); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagawx = new Bag(); + bagawx.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagawx.add(DataTypes.DT_STRING.createAttributeValue(w)); + bagawx.add(DataTypes.DT_STRING.createAttributeValue(x)); + bagwx = new Bag(); + bagwx.add(DataTypes.DT_STRING.createAttributeValue(w)); + bagwx.add(DataTypes.DT_STRING.createAttributeValue(x)); + bagInt = new Bag(); + bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagStringInt = new Bag(); + bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagEmpty = new Bag(); + bagStringBooleansTrue = new Bag(); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); + bagStringBooleansFalse = new Bag(); + bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagBooleansTrue = new Bag(); + bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + bagBooleansTrue.add(DataTypes.DT_BOOLEAN.createAttributeValue(true)); + bagBooleansFalse = new Bag(); + bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + bagBooleansFalse.add(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + + + // create primitive attrs + attra = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(a)); + attrh = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(h)); + + + + // predicates passed as function arguments + attrPredicateStringEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_EQUAL)); + attrPredicateStringIntersection = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_INTERSECTION)); + attrPredicateStringGreaterThan = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_GREATER_THAN)); + attrPredicateBooleanFromString = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_BOOLEAN_FROM_STRING)); + + } catch (Exception ex) { + fail("creating attribute e="+ ex); + } + + // make into attributes + FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); + FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); + FunctionArgumentBag attrBagawx = new FunctionArgumentBag(bagawx); + FunctionArgumentBag attrBagwx = new FunctionArgumentBag(bagwx); + FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); + FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); + FunctionArgumentBag attrBagStringBooleansTrue = new FunctionArgumentBag(bagStringBooleansTrue); + + FunctionDefinitionHigherOrderBag fd = (FunctionDefinitionHigherOrderBag) StdFunctions.FD_ALL_OF_ALL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_ALL_OF_ALL, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + // normal match + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagwx); + arguments.add(attrBagace); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // normal no-match + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagawx); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagace); + arguments.add(attrBagwx); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // primitive instead of bag + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attra); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-all 2nd argument must be bag, got 'string'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrPredicateStringEqual); + arguments.add(attrBagace); + arguments.add(attra); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-all 3rd argument must be bag, got 'string'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // no primitives - predicate expects only 1 arg + arguments.clear(); + arguments.add(attrPredicateBooleanFromString); + arguments.add(attrBagStringBooleansTrue); + arguments.add(attrBagStringBooleansTrue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-all Predicate error: function:boolean-from-string Expected 1 arguments, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bag is empty + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagace); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagEmpty); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // no bag + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrh); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-all Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // bad predicate + arguments.clear(); + arguments.add(attrh); + arguments.add(attrBagStringInt); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-all First argument expected URI, got http://www.w3.org/2001/XMLSchema#string", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // non-boolean predicate + arguments.clear(); + arguments.add(attrPredicateStringIntersection); + arguments.add(attrBagStringInt); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-all Predicate Function must return boolean, but 'urn:oasis:names:tc:xacml:1.0:function:string-intersection' returns 'string", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // predicate after first arg + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrPredicateStringIntersection); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-all 2nd argument must be bag, got 'anyURI'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bags of different types + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagwx); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-all Predicate error: function:string-greater-than Expected data type 'string' saw 'integer' at arg index 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // no args + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-all Expected at least 2 arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // one arg + arguments.clear(); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-all Expected at least 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many args + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-all Expected 3 arguments, got 4", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // first null + arguments.clear(); + arguments.add(null); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-all Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second null + arguments.clear(); + arguments.add(attrPredicateStringGreaterThan); + arguments.add(attrBagabcdefg); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:all-of-all 3rd argument must be bag, got 'null'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + + + + + + + @Test + public void testMap() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String f = "f"; + String g = "g"; + String h = "h"; + String j = "j"; + + + Bag bagabcdefg = null; + Bag bagbdfhj = null; + Bag bagace = null; + Bag bagb = null; + Bag bagaaacccef = null; + Bag bagInt = null; + Bag bagStringInt = null; + Bag bagEmpty = null; + Bag bagStringBooleansFalse = null; + Bag bagStringBooleansTrue = null; + Bag bagInt123 = null; + Bag bagInt789 = null; + + + // primitive attrs + FunctionArgumentAttributeValue attrh = null; + FunctionArgumentAttributeValue attrInt7 = null; + + + + // predicates passed as arguments + FunctionArgumentAttributeValue attrPredicateStringNormalizeToLowerCase = null; + FunctionArgumentAttributeValue attrPredicateIntegerEqual = null; + FunctionArgumentAttributeValue attrPredicateIntegerAdd = null; + + try { + + // Create Bag contents + bagabcdefg = new Bag(); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); + bagbdfhj = new Bag(); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); + bagace = new Bag(); + bagace.add(DataTypes.DT_STRING.createAttributeValue("A")); + bagace.add(DataTypes.DT_STRING.createAttributeValue("C")); + bagace.add(DataTypes.DT_STRING.createAttributeValue("E")); + bagb = new Bag(); + bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagaaacccef = new Bag(); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagInt = new Bag(); + bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagStringInt = new Bag(); + bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); + + bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagEmpty = new Bag(); + bagStringBooleansTrue = new Bag(); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); + bagStringBooleansTrue.add(DataTypes.DT_STRING.createAttributeValue("true")); + bagStringBooleansFalse = new Bag(); + bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagStringBooleansFalse.add(DataTypes.DT_STRING.createAttributeValue("false")); + bagInt123 = new Bag(); + bagInt123.add(DataTypes.DT_INTEGER.createAttributeValue(1)); + bagInt123.add(DataTypes.DT_INTEGER.createAttributeValue(2)); + bagInt123.add(DataTypes.DT_INTEGER.createAttributeValue(3)); + bagInt789 = new Bag(); + bagInt789.add(DataTypes.DT_INTEGER.createAttributeValue(7)); + bagInt789.add(DataTypes.DT_INTEGER.createAttributeValue(8)); + bagInt789.add(DataTypes.DT_INTEGER.createAttributeValue(9)); + + + + // create primitive attrs + attrh = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(h)); + attrInt7 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(7)); + + + // predicates passed as function arguments + attrPredicateStringNormalizeToLowerCase = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_STRING_NORMALIZE_TO_LOWER_CASE)); + attrPredicateIntegerEqual = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_INTEGER_EQUAL)); + attrPredicateIntegerAdd = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(XACML3.ID_FUNCTION_INTEGER_ADD)); + + } catch (Exception ex) { + fail("creating attribute e="+ ex); + } + + // make into attributes + FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); + FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); + FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); + FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); + FunctionArgumentBag attrBagStringBooleansTrue = new FunctionArgumentBag(bagStringBooleansTrue); + FunctionArgumentBag attrBagInt789 = new FunctionArgumentBag(bagInt789); + + FunctionDefinitionHigherOrderBag fd = (FunctionDefinitionHigherOrderBag) StdFunctions.FD_MAP; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_MAP, fd.getId()); + assertNull( fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertTrue(fd.returnsBag()); + + // normal match + arguments.clear(); + arguments.add(attrPredicateStringNormalizeToLowerCase); + arguments.add(attrBagace); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertTrue(res.isBag()); + Bag bag = res.getBag(); + assertEquals(3, bag.size()); + List> bagAttributes = bag.getAttributeValueList(); + try { + assertTrue(bagAttributes.contains(DataTypes.DT_STRING.createAttributeValue("a"))); + assertFalse(bagAttributes.contains(DataTypes.DT_STRING.createAttributeValue("A"))); + assertTrue(bagAttributes.contains(DataTypes.DT_STRING.createAttributeValue("c"))); + assertFalse(bagAttributes.contains(DataTypes.DT_STRING.createAttributeValue("C"))); + assertTrue(bagAttributes.contains(DataTypes.DT_STRING.createAttributeValue("e"))); + assertFalse(bagAttributes.contains(DataTypes.DT_STRING.createAttributeValue("E"))); + } catch (Exception ex) { + fail("checking result e="+ex); + } + + // 2-input predicate + arguments.clear(); + arguments.add(attrPredicateIntegerAdd); + arguments.add(attrInt7); + arguments.add(attrBagInt789); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertTrue(res.isBag()); + bag = res.getBag(); + assertEquals(3, bag.size()); + bagAttributes = bag.getAttributeValueList(); + try { + assertTrue(bagAttributes.contains(DataTypes.DT_INTEGER.createAttributeValue("14"))); + assertTrue(bagAttributes.contains(DataTypes.DT_INTEGER.createAttributeValue("15"))); + assertTrue(bagAttributes.contains(DataTypes.DT_INTEGER.createAttributeValue("16"))); + } catch (Exception ex) { + fail("checking result e="+ex); + } + + + // predicate returns booleans + arguments.clear(); + arguments.add(attrPredicateIntegerEqual); + arguments.add(attrInt7); + arguments.add(attrBagInt789); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertTrue(res.isBag()); + bag = res.getBag(); + assertEquals(3, bag.size()); + bagAttributes = bag.getAttributeValueList(); + try { + assertEquals(bagAttributes.get(0), (DataTypes.DT_BOOLEAN.createAttributeValue(true))); + assertEquals(bagAttributes.get(1), (DataTypes.DT_BOOLEAN.createAttributeValue(false))); + assertEquals(bagAttributes.get(2), (DataTypes.DT_BOOLEAN.createAttributeValue(false))); + } catch (Exception ex) { + fail("checking result e="+ex); + } + + // predicate returns bag + + + + // no primitives - predicate function expects 2 + arguments.clear(); + arguments.add(attrPredicateIntegerAdd); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:map Predicate error: function:integer-add Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bag is empty + arguments.clear(); + arguments.add(attrPredicateStringNormalizeToLowerCase); + arguments.add(attrh); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertTrue(res.isBag()); + bag = res.getBag(); + assertEquals(0, bag.size());; + + // no bag + arguments.clear(); + arguments.add(attrPredicateStringNormalizeToLowerCase); + arguments.add(attrh); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:map Did not get any Bag argument; must have at least 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // extra bag + arguments.clear(); + arguments.add(attrPredicateStringNormalizeToLowerCase); + arguments.add(attrh); + arguments.add(attrBagStringBooleansTrue); + arguments.add(attrh); + arguments.add(attrBagStringBooleansTrue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:map must have only 1 bag; found one at index 2 and another at 4", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // bad predicate + arguments.clear(); + arguments.add(attrh); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:map First argument expected URI, got http://www.w3.org/2001/XMLSchema#string", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // predicate gets unexpected number of args + arguments.clear(); + arguments.add(attrPredicateStringNormalizeToLowerCase); + arguments.add(attrh); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:map Predicate error: function:string-normalize-to-lower-case Expected 1 arguments, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // predicate gets bad primitive type + arguments.clear(); + arguments.add(attrPredicateStringNormalizeToLowerCase); + arguments.add(attrPredicateStringNormalizeToLowerCase); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:map Predicate error: function:string-normalize-to-lower-case Expected 1 arguments, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bags of different types + arguments.clear(); + arguments.add(attrPredicateStringNormalizeToLowerCase); + arguments.add(attrh); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + // first null + arguments.clear(); + arguments.add(null); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:map Predicate Function (first argument) was null", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second null + arguments.clear(); + arguments.add(attrPredicateStringNormalizeToLowerCase); + arguments.add(attrBagabcdefg); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:map Got null argument at index 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionHomogeneousSimpleTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionHomogeneousSimpleTest.java new file mode 100644 index 000000000..c72bfaba1 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionHomogeneousSimpleTest.java @@ -0,0 +1,151 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.att.research.xacml.api.Status; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.Bag; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentBag; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * FunctionDefinitionHomogeneousSimple is an abstract class, so we have to test it by creating a sub-class. + * The constructor is tested by default when an instance of the sub-class is created for other tests. + * + * Each of these functions needs to be tested for each type of function to be sure the values are correct, + * so this is just a simple test to see that the mechanism works. + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionHomogeneousSimpleTest { + + + + @Test + public void testGetDataTypeArgs() { + + // test a simple instance using the Equality class + FunctionDefinitionEquality fd = new FunctionDefinitionEquality(XACML3.ID_FUNCTION_STRING_EQUAL, DataTypes.DT_STRING); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + } + + @Test + public void testGetNumArgs() { + // test a simple instance using the Equality class + FunctionDefinitionEquality fd = new FunctionDefinitionEquality(XACML3.ID_FUNCTION_STRING_EQUAL, DataTypes.DT_STRING); + assertEquals(new Integer(2), fd.getNumArgs()); + } + + @Test + public void testValidateArguments() { + // create some arguments to use later + FunctionArgumentAttributeValue stringAttr1 = null; + FunctionArgumentAttributeValue stringAttr2 = null; + FunctionArgumentAttributeValue stringAttr3 = null; + FunctionArgumentAttributeValue intAttr = null; + try { + stringAttr1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc")); + stringAttr2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("def")); + stringAttr3 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("ghi")); + intAttr = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionEquality fd = new FunctionDefinitionEquality(XACML3.ID_FUNCTION_STRING_EQUAL, DataTypes.DT_STRING); + List convertedValues = new ArrayList<>(); + List listFunctionArguments = new ArrayList<>(); + + // test correct # of args, both of them strings + listFunctionArguments.add(stringAttr1); + listFunctionArguments.add(stringAttr2); + Status status = fd.validateArguments(listFunctionArguments, convertedValues); + assertTrue(status.isOk()); + assertEquals(convertedValues.size(),2); + + // test too few args + listFunctionArguments.remove(1); + status = fd.validateArguments(listFunctionArguments, convertedValues); + assertFalse(status.isOk()); + assertEquals("Expected 2 arguments, got 1", status.getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", status.getStatusCode().getStatusCodeValue().stringValue()); + + // test too many args + listFunctionArguments.add(stringAttr2); + listFunctionArguments.add(stringAttr3); + status = fd.validateArguments(listFunctionArguments, convertedValues); + assertFalse(status.isOk()); + assertEquals("Expected 2 arguments, got 3", status.getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", status.getStatusCode().getStatusCodeValue().stringValue()); + + // test with null arg + listFunctionArguments.clear(); + listFunctionArguments.add(null); + listFunctionArguments.add(stringAttr1); + status = fd.validateArguments(listFunctionArguments, convertedValues); + assertFalse(status.isOk()); + assertEquals("Got null argument at arg index 0", status.getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", status.getStatusCode().getStatusCodeValue().stringValue()); + + // test function that takes 0 args +//TODO test with func that specifies 0 args? ASSUME for now that there are no such functions since a function needs to operate on something +// fail("need to test function with 0 args and various inputs - see validateArguments code"); + + + // test with one is a bag + listFunctionArguments.clear(); + listFunctionArguments.add(stringAttr1); + Bag bag = new Bag(); + FunctionArgument bagArg = new FunctionArgumentBag(bag); + listFunctionArguments.add(bagArg); + status = fd.validateArguments(listFunctionArguments, convertedValues); + assertFalse(status.isOk()); + assertEquals("Expected a simple value, saw a bag at arg index 1", status.getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", status.getStatusCode().getStatusCodeValue().stringValue()); + + // test with string and int + listFunctionArguments.clear(); + listFunctionArguments.add(stringAttr1); + listFunctionArguments.add(intAttr); + status = fd.validateArguments(listFunctionArguments, convertedValues); + assertFalse(status.isOk()); + assertEquals("Expected data type 'string' saw 'integer' at arg index 1", status.getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", status.getStatusCode().getStatusCodeValue().stringValue()); + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionLogicalTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionLogicalTest.java new file mode 100644 index 000000000..1778dd112 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionLogicalTest.java @@ -0,0 +1,422 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionLogicalTest { + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + // use the same args for each test + FunctionArgumentAttributeValue attrT = null; + FunctionArgumentAttributeValue attrF = null; + public FunctionDefinitionLogicalTest () { + try { + attrT = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(true)); + attrF = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(false)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + } + + + @Test + public void testOR() { + FunctionArgumentAttributeValue attr5 = null; + try { + attr5 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(5)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionLogical fd = (FunctionDefinitionLogical) StdFunctions.FD_OR; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_OR, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // test normal + arguments.add(attrT); + arguments.add(attrF); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(true), resValue); + + arguments.clear(); + arguments.add(attrF); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(false), resValue); + + // test no args + arguments.clear(); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(false), resValue); + + // first true, second error + arguments.clear(); + arguments.add(attrT); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(true), resValue); + + // first false, second error + arguments.clear(); + arguments.add(attrF); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:or Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // multiple false + arguments.clear(); + arguments.add(attrF); + arguments.add(attrF); + arguments.add(attrF); + arguments.add(attrF); + arguments.add(attrF); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(false), resValue); + + // non-boolean + arguments.clear(); + arguments.add(attrF); + arguments.add(attr5); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:or Expected data type 'boolean' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // first arg error + arguments.clear(); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:or Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + @Test + public void testAND() { + FunctionArgumentAttributeValue attr5 = null; + try { + attr5 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(5)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + + FunctionDefinitionLogical fd = (FunctionDefinitionLogical) StdFunctions.FD_AND; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_AND, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // test normal + arguments.add(attrT); + arguments.add(attrF); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(false), resValue); + + arguments.clear(); + arguments.add(attrF); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(false), resValue); + + // test no args + arguments.clear(); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(true), resValue); + + // first true, second error + arguments.clear(); + arguments.add(attrT); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:and Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // first false, second error + arguments.clear(); + arguments.add(attrF); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(false), resValue); + + // multiple true + arguments.clear(); + arguments.add(attrT); + arguments.add(attrT); + arguments.add(attrT); + arguments.add(attrT); + arguments.add(attrT); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(true), resValue); + + // non-boolean + arguments.clear(); + arguments.add(attrT); + arguments.add(attr5); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals("function:and Expected data type 'boolean' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // first arg error + arguments.clear(); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals("function:and Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + @Test + public void testN_of() { + FunctionArgumentAttributeValue attr0 = null; + FunctionArgumentAttributeValue attr2 = null; + try { + attr0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); + attr2 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(2)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + + FunctionDefinitionLogical fd = (FunctionDefinitionLogical) StdFunctions.FD_N_OF; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_N_OF, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // test normal + arguments.add(attr2); + arguments.add(attrT); + arguments.add(attrF); + arguments.add(attrT); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(true), resValue); + + // normal fail + arguments.clear(); + arguments.add(attr2); + arguments.add(attrT); + arguments.add(attrF); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(false), resValue); + + + // null count + arguments.clear(); + arguments.add(null); + arguments.add(attrT); + arguments.add(attrF); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(true), resValue); + + // 0 count + arguments.clear(); + arguments.add(attr0); + arguments.add(attrT); + arguments.add(attrF); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(true), resValue); + + // bad object type for count + arguments.clear(); + arguments.add(attrT); + arguments.add(attrT); + arguments.add(attrF); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:n-of For input string: \"true\"", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // count larger than list + arguments.clear(); + arguments.add(attr2); + arguments.add(attrT); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:n-of Expected 2 arguments but only 1 arguments in list after the count", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // aborts after find ok + arguments.clear(); + arguments.add(attr2); + arguments.add(attrT); + arguments.add(attrT); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(true), resValue); + + // error before find ok + arguments.clear(); + arguments.add(attr2); + arguments.add(null); + arguments.add(attrT); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:n-of Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // non-boolean in list + arguments.clear(); + arguments.add(attr2); + arguments.add(attrT); + arguments.add(attr0); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:n-of Expected data type 'boolean' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + @Test + public void testNot() { + + FunctionDefinitionLogical fd = (FunctionDefinitionLogical) StdFunctions.FD_NOT; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_NOT, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // test normal + arguments.clear(); + arguments.add(attrT); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(false), resValue); + + arguments.clear(); + arguments.add(attrF); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(true), resValue); + + + // test null/0 args + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:not Expected 1 argument, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // test 2 args + arguments.clear(); + arguments.add(attrT); + arguments.add(attrF); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:not Expected 1 argument, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionNumberTypeConversionTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionNumberTypeConversionTest.java new file mode 100644 index 000000000..471025e12 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionNumberTypeConversionTest.java @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Tests for various classes containing only one function. + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionNumberTypeConversionTest { + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + @Test + public void testDouble_to_integer() { + FunctionArgumentAttributeValue attr1 = null; + try { + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(5.432)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionNumberTypeConversion fd = (FunctionDefinitionNumberTypeConversion) StdFunctions.FD_DOUBLE_TO_INTEGER; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DOUBLE_TO_INTEGER, fd.getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + + // test normal add + arguments.add(attr1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + BigInteger resValue = (BigInteger)res.getValue().getValue(); + assertEquals(BigInteger.valueOf(5), resValue); + } + + + @Test + public void testInteger_to_double() { + FunctionArgumentAttributeValue attr1 = null; + try { + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(5)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionNumberTypeConversion fd = (FunctionDefinitionNumberTypeConversion) StdFunctions.FD_INTEGER_TO_DOUBLE; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_INTEGER_TO_DOUBLE, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + + // test normal add + arguments.add(attr1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Double resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(5.0), resValue); + } + + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionRegexpMatchTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionRegexpMatchTest.java new file mode 100644 index 000000000..c631e1e2d --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionRegexpMatchTest.java @@ -0,0 +1,511 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import javax.security.auth.x500.X500Principal; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacml.std.datatypes.IPAddress; +import com.att.research.xacml.std.datatypes.RFC2396DomainName; +import com.att.research.xacml.std.datatypes.RFC822Name; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionRegexpMatchTest { + + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + + @Test + public void testString() { + String v1 = new String("abc"); + String v2 = new String("def"); + + + FunctionArgumentAttributeValue attrV1 = null; + FunctionArgumentAttributeValue attrV2 = null; + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrInteger = null; + try { + attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); + attrV2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v2)); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionRegexpMatch fd = (FunctionDefinitionRegexpMatch) StdFunctions.FD_STRING_REGEXP_MATCH; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_REGEXP_MATCH, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // match + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrV1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // no match + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrV2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // null regex + arguments.clear(); + arguments.add(null); + arguments.add(attrV2); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-regexp-match Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrV2); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-regexp-match Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null object to match + arguments.clear(); + arguments.add(attrV1); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-regexp-match Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-regexp-match Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // regex not string + arguments.clear(); + arguments.add(attrInteger); + arguments.add(attrV2); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-regexp-match Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // object to match not correct type + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrInteger); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-regexp-match Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + @Test + public void testAnyURI() { + String regexp = new String("abc"); + URI uri1 = null; + URI uri2 = null; + try { + uri1 = new URI("abc"); + uri2 = new URI("def"); + } catch (Exception e) { + fail("Unable to create URIs, e="+e); + } + + + FunctionArgumentAttributeValue attrRegexp = null; + FunctionArgumentAttributeValue attrUri1 = null; + FunctionArgumentAttributeValue attrUri2 = null; + FunctionArgumentAttributeValue attrInteger = null; + try { + attrRegexp = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(regexp)); + attrUri1 = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(uri1)); + attrUri2 = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(uri2)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionRegexpMatch fd = (FunctionDefinitionRegexpMatch) StdFunctions.FD_ANYURI_REGEXP_MATCH; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_ANYURI_REGEXP_MATCH, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // match + arguments.clear(); + arguments.add(attrRegexp); + arguments.add(attrUri1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // no match + arguments.clear(); + arguments.add(attrRegexp); + arguments.add(attrUri2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // object to match not correct type + arguments.clear(); + arguments.add(attrRegexp); + arguments.add(attrInteger); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-regexp-match Expected data type 'anyURI' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + @Test + public void testIpAddress() { + String regexp = new String(".*123.*"); + IPAddress addr1 = null; + IPAddress addr2 = null; + try { + addr1 = IPAddress.newInstance("10.123.13.14"); + addr2 = IPAddress.newInstance("10.12.13.14"); + } catch (Exception e) { + fail("Unable to create IPAddresses, e="+e); + } + + + FunctionArgumentAttributeValue attrRegexp = null; + FunctionArgumentAttributeValue attrAddr1 = null; + FunctionArgumentAttributeValue attrAddr2 = null; + FunctionArgumentAttributeValue attrInteger = null; + try { + attrRegexp = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(regexp)); + attrAddr1 = new FunctionArgumentAttributeValue(DataTypes.DT_IPADDRESS.createAttributeValue(addr1)); + attrAddr2 = new FunctionArgumentAttributeValue(DataTypes.DT_IPADDRESS.createAttributeValue(addr2)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionRegexpMatch fd = (FunctionDefinitionRegexpMatch) StdFunctions.FD_IPADDRESS_REGEXP_MATCH; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_IPADDRESS_REGEXP_MATCH, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // match + arguments.clear(); + arguments.add(attrRegexp); + arguments.add(attrAddr1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // no match + arguments.clear(); + arguments.add(attrRegexp); + arguments.add(attrAddr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // object to match not correct type + arguments.clear(); + arguments.add(attrRegexp); + arguments.add(attrInteger); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-regexp-match Expected data type 'ipAddress' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + @Test + public void testDnsName() { + String regexp = new String("abc"); + RFC2396DomainName addr1 = null; + RFC2396DomainName addr2 = null; + try { + addr1 = RFC2396DomainName.newInstance("abc"); + addr2 = RFC2396DomainName.newInstance("def"); + } catch (Exception e) { + fail("Unable to create DNSNames, e="+e); + } + + + FunctionArgumentAttributeValue attrRegexp = null; + FunctionArgumentAttributeValue attrAddr1 = null; + FunctionArgumentAttributeValue attrAddr2 = null; + FunctionArgumentAttributeValue attrInteger = null; + try { + attrRegexp = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(regexp)); + attrAddr1 = new FunctionArgumentAttributeValue(DataTypes.DT_DNSNAME.createAttributeValue(addr1)); + attrAddr2 = new FunctionArgumentAttributeValue(DataTypes.DT_DNSNAME.createAttributeValue(addr2)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionRegexpMatch fd = (FunctionDefinitionRegexpMatch) StdFunctions.FD_DNSNAME_REGEXP_MATCH; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DNSNAME_REGEXP_MATCH, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // match + arguments.clear(); + arguments.add(attrRegexp); + arguments.add(attrAddr1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // no match + arguments.clear(); + arguments.add(attrRegexp); + arguments.add(attrAddr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // object to match not correct type + arguments.clear(); + arguments.add(attrRegexp); + arguments.add(attrInteger); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dnsName-regexp-match Expected data type 'dnsName' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + @Test + public void testRfc822Name() { + String regexp = new String(".*abc.*"); + RFC822Name addr1 = null; + RFC822Name addr2 = null; + try { + addr1 = RFC822Name.newInstance("abc@somewhere"); + addr2 = RFC822Name.newInstance("def@somewhere"); + } catch (Exception e) { + fail("Unable to create RFC822Names, e="+e); + } + + + FunctionArgumentAttributeValue attrRegexp = null; + FunctionArgumentAttributeValue attrAddr1 = null; + FunctionArgumentAttributeValue attrAddr2 = null; + FunctionArgumentAttributeValue attrInteger = null; + try { + attrRegexp = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(regexp)); + attrAddr1 = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(addr1)); + attrAddr2 = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(addr2)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionRegexpMatch fd = (FunctionDefinitionRegexpMatch) StdFunctions.FD_RFC822NAME_REGEXP_MATCH; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_RFC822NAME_REGEXP_MATCH, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // match + arguments.clear(); + arguments.add(attrRegexp); + arguments.add(attrAddr1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // no match + arguments.clear(); + arguments.add(attrRegexp); + arguments.add(attrAddr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // object to match not correct type + arguments.clear(); + arguments.add(attrRegexp); + arguments.add(attrInteger); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:rfc822Name-regexp-match Expected data type 'rfc822Name' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + @Test + public void testX500Name() { + String regexp = new String(".*Duke.*"); + X500Principal addr1 = null; + X500Principal addr2 = null; + try { + addr1 = new X500Principal("CN=Duke, OU=JavaSoft, O=Sun Microsystems, C=US"); + addr2 = new X500Principal("CN=Policy Engine, OU=Research, O=ATT, C=US"); + } catch (Exception e) { + fail("Unable to create X500Name, e="+e); + } + + + FunctionArgumentAttributeValue attrRegexp = null; + FunctionArgumentAttributeValue attrAddr1 = null; + FunctionArgumentAttributeValue attrAddr2 = null; + FunctionArgumentAttributeValue attrInteger = null; + try { + attrRegexp = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(regexp)); + attrAddr1 = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(addr1)); + attrAddr2 = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(addr2)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionRegexpMatch fd = (FunctionDefinitionRegexpMatch) StdFunctions.FD_X500NAME_REGEXP_MATCH; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_X500NAME_REGEXP_MATCH, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // match + arguments.clear(); + arguments.add(attrRegexp); + arguments.add(attrAddr1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // no match + arguments.clear(); + arguments.add(attrRegexp); + arguments.add(attrAddr2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // object to match not correct type + arguments.clear(); + arguments.add(attrRegexp); + arguments.add(attrInteger); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:x500Name-regexp-match Expected data type 'x500Name' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionSetTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionSetTest.java new file mode 100644 index 000000000..8f22c8227 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionSetTest.java @@ -0,0 +1,1903 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.junit.Test; + +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.Bag; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentBag; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionSetTest { + + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + + + // + // INTERSECTION tests + // + + + @Test + public void testString_intersection() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String f = "f"; + String g = "g"; + String h = "h"; + String j = "j"; + + + Bag bagabcdefg = null; + Bag bagbdfhj = null; + Bag bagace = null; + Bag bagb = null; + Bag bagaaacccef = null; + Bag bagInt = null; + Bag bagStringInt = null; + Bag bagEmpty = null; + + FunctionArgumentAttributeValue attrBadType = null; + + try { + bagabcdefg = new Bag(); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); + bagbdfhj = new Bag(); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); + bagace = new Bag(); + bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagb = new Bag(); + bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagaaacccef = new Bag(); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagInt = new Bag(); + bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagStringInt = new Bag(); + bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagEmpty = new Bag(); + + attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.1)); + } catch (Exception ex) { + fail("creating attribute e="+ ex); + } + + // make into attributes + FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); + FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); + FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); + FunctionArgumentBag attrBagb = new FunctionArgumentBag(bagb); + FunctionArgumentBag attrBagaaacccef = new FunctionArgumentBag(bagaaacccef); + FunctionArgumentBag attrBagInt = new FunctionArgumentBag(bagInt); + FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); + FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); + + FunctionDefinitionSet fd = (FunctionDefinitionSet) StdFunctions.FD_STRING_INTERSECTION; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_INTERSECTION, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertTrue(fd.returnsBag()); + + // normal intersection (everything in both bags, no duplicates) + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Bag bag = res.getBag(); + assertNotNull(bag); + Iterator> it = bag.getAttributeValues(); + assertEquals(7, bag.size()); + AttributeValue attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + + // several but not all intersection + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(3, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(b, attrValueObject.getValue() ); + + // no intersection + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(0, bag.size()); + + // one intersection + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagb); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(1, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(b, attrValueObject.getValue() ); + + // bag one has duplicates that do not intersect + arguments.clear(); + arguments.add(attrBagaaacccef); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(1, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(f, attrValueObject.getValue() ); + + // bag one has duplicates that do intersect + arguments.clear(); + arguments.add(attrBagaaacccef); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(3, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + attrValueObject = it.next(); + assertEquals(c, attrValueObject.getValue() ); + attrValueObject = it.next(); + assertEquals(e, attrValueObject.getValue() ); + + // bag 2 has duplicates that do not intersect + arguments.clear(); + arguments.add(attrBagbdfhj); + arguments.add(attrBagaaacccef); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(1, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(f, attrValueObject.getValue() ); + + // bag 2 has duplicates that intersect + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagaaacccef); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(3, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + attrValueObject = it.next(); + assertEquals(c, attrValueObject.getValue() ); + attrValueObject = it.next(); + assertEquals(e, attrValueObject.getValue() ); + + // first bag is empty + arguments.clear(); + arguments.add(attrBagEmpty); + arguments.add(attrBagaaacccef); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(0, bag.size()); + + // second bag is empty + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(0, bag.size()); + + // bags of different types + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(1, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagInt); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(0, bag.size()); + + // first not a bag + arguments.clear(); + arguments.add(attrBadType); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-intersection Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second not a bag + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-intersection Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // first null + arguments.clear(); + arguments.add(null); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-intersection Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second null + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-intersection Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too few args + arguments.clear(); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-intersection Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-intersection Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many args + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-intersection Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + @Test + public void testInteger_intersection() { + BigInteger a = new BigInteger("1"); + BigInteger b = new BigInteger("2"); + BigInteger c = new BigInteger("3"); + BigInteger d = new BigInteger("4"); + BigInteger e = new BigInteger("5"); + BigInteger f = new BigInteger("6"); + BigInteger g = new BigInteger("7"); + BigInteger h = new BigInteger("8"); + BigInteger j = new BigInteger("9"); + + + Bag bagabcdefg = null; + Bag bagbdfhj = null; + Bag bagace = null; + Bag bagb = null; + Bag bagaaacccef = null; + Bag bagInt = null; + Bag bagStringInt = null; + Bag bagEmpty = null; + + FunctionArgumentAttributeValue attrBadType = null; + + try { + bagabcdefg = new Bag(); + bagabcdefg.add(DataTypes.DT_INTEGER.createAttributeValue(a)); + bagabcdefg.add(DataTypes.DT_INTEGER.createAttributeValue(b)); + bagabcdefg.add(DataTypes.DT_INTEGER.createAttributeValue(c)); + bagabcdefg.add(DataTypes.DT_INTEGER.createAttributeValue(d)); + bagabcdefg.add(DataTypes.DT_INTEGER.createAttributeValue(e)); + bagabcdefg.add(DataTypes.DT_INTEGER.createAttributeValue(f)); + bagabcdefg.add(DataTypes.DT_INTEGER.createAttributeValue(g)); + bagbdfhj = new Bag(); + bagbdfhj.add(DataTypes.DT_INTEGER.createAttributeValue(b)); + bagbdfhj.add(DataTypes.DT_INTEGER.createAttributeValue(d)); + bagbdfhj.add(DataTypes.DT_INTEGER.createAttributeValue(f)); + bagbdfhj.add(DataTypes.DT_INTEGER.createAttributeValue(h)); + bagbdfhj.add(DataTypes.DT_INTEGER.createAttributeValue(j)); + bagace = new Bag(); + bagace.add(DataTypes.DT_INTEGER.createAttributeValue(a)); + bagace.add(DataTypes.DT_INTEGER.createAttributeValue(c)); + bagace.add(DataTypes.DT_INTEGER.createAttributeValue(e)); + bagb = new Bag(); + bagb.add(DataTypes.DT_INTEGER.createAttributeValue(b)); + bagaaacccef = new Bag(); + bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(e)); + bagaaacccef.add(DataTypes.DT_INTEGER.createAttributeValue(f)); + bagInt = new Bag(); + bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagStringInt = new Bag(); + bagStringInt.add(DataTypes.DT_STRING.createAttributeValue("abc")); + bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(1)); + bagEmpty = new Bag(); + + attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.1)); + } catch (Exception ex) { + fail("creating attribute e="+ ex); + } + + // make into attributes + FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); + FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); + FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); + FunctionArgumentBag attrBagb = new FunctionArgumentBag(bagb); + FunctionArgumentBag attrBagaaacccef = new FunctionArgumentBag(bagaaacccef); + FunctionArgumentBag attrBagInt = new FunctionArgumentBag(bagInt); + FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); + FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); + + FunctionDefinitionSet fd = (FunctionDefinitionSet) StdFunctions.FD_INTEGER_INTERSECTION; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_INTEGER_INTERSECTION, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertTrue(fd.returnsBag()); + + // normal intersection (everything in both bags, no duplicates) + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Bag bag = res.getBag(); + assertNotNull(bag); + Iterator> it = bag.getAttributeValues(); + assertEquals(7, bag.size()); + AttributeValue attrValueObject = it.next(); + assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + + // several but not all intersection + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(3, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); + assertEquals(b, attrValueObject.getValue() ); + + // no intersection + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(0, bag.size()); + + // one intersection + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagb); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(1, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); + assertEquals(b, attrValueObject.getValue() ); + + // bag one has duplicates that do not intersect + arguments.clear(); + arguments.add(attrBagaaacccef); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(1, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); + assertEquals(f, attrValueObject.getValue() ); + + // bag one has duplicates that do intersect + arguments.clear(); + arguments.add(attrBagaaacccef); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(3, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + attrValueObject = it.next(); + assertEquals(c, attrValueObject.getValue() ); + attrValueObject = it.next(); + assertEquals(e, attrValueObject.getValue() ); + + // bag 2 has duplicates that do not intersect + arguments.clear(); + arguments.add(attrBagbdfhj); + arguments.add(attrBagaaacccef); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(1, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); + assertEquals(f, attrValueObject.getValue() ); + + // bag 2 has duplicates that intersect + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagaaacccef); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(3, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + attrValueObject = it.next(); + assertEquals(c, attrValueObject.getValue() ); + attrValueObject = it.next(); + assertEquals(e, attrValueObject.getValue() ); + + // first bag is empty + arguments.clear(); + arguments.add(attrBagEmpty); + arguments.add(attrBagaaacccef); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(0, bag.size()); + + // second bag is empty + arguments.clear(); + arguments.add(attrBagbdfhj); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(0, bag.size()); + + // bags of different types + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(1, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagInt); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(1, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_INTEGER.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + + + // first not a bag + arguments.clear(); + arguments.add(attrBadType); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:integer-intersection Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second not a bag + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:integer-intersection Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // first null + arguments.clear(); + arguments.add(null); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:integer-intersection Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second null + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:integer-intersection Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too few args + arguments.clear(); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:integer-intersection Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:integer-intersection Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many args + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:integer-intersection Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + + + + + + + + + + // + // AT_LEAST_ONE_MEMBER_OF tests + // + + @Test + public void testString_at_least_one_member_of() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String f = "f"; + String g = "g"; + String h = "h"; + String j = "j"; + + + Bag bagabcdefg = null; + Bag bagbdfhj = null; + Bag bagace = null; + Bag bagb = null; + Bag bagaaaccce = null; + Bag bagInt = null; + Bag bagStringInt = null; + Bag bagEmpty = null; + + FunctionArgumentAttributeValue attrBadType = null; + + try { + bagabcdefg = new Bag(); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); + bagbdfhj = new Bag(); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); + bagace = new Bag(); + bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagb = new Bag(); + bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagaaaccce = new Bag(); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagInt = new Bag(); + bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagStringInt = new Bag(); + bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagEmpty = new Bag(); + + attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.1)); + } catch (Exception ex) { + fail("creating attribute e="+ ex); + } + + // make into attributes + FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); + FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); + FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); + FunctionArgumentBag attrBagb = new FunctionArgumentBag(bagb); + FunctionArgumentBag attrBagaaaccce = new FunctionArgumentBag(bagaaaccce); + FunctionArgumentBag attrBagInt = new FunctionArgumentBag(bagInt); + FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); + FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); + + FunctionDefinitionSet fd = (FunctionDefinitionSet) StdFunctions.FD_STRING_AT_LEAST_ONE_MEMBER_OF; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_AT_LEAST_ONE_MEMBER_OF, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + // normal intersection (everything in both bags, no duplicates) + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + + // several but not all intersection + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // no intersection + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // one intersection + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagb); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // bag one has duplicates that do not intersect + arguments.clear(); + arguments.add(attrBagaaaccce); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // bag one has duplicates that do intersect + arguments.clear(); + arguments.add(attrBagaaaccce); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // bag 2 has duplicates that do not intersect + arguments.clear(); + arguments.add(attrBagbdfhj); + arguments.add(attrBagaaaccce); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // bag 2 has duplicates that intersect + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagaaaccce); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // 2 empty bags + arguments.clear(); + arguments.add(attrBagEmpty); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first non-empty, 2nd empty + arguments.clear(); + arguments.add(attrBagaaaccce); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first empty, 2nd not empty + arguments.clear(); + arguments.add(attrBagEmpty); + arguments.add(attrBagaaaccce); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // bags of different types + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagInt); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first not a bag + arguments.clear(); + arguments.add(attrBadType); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-at-least-one-member-of Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second not a bag + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-at-least-one-member-of Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // first null + arguments.clear(); + arguments.add(null); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-at-least-one-member-of Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second null + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-at-least-one-member-of Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too few args + arguments.clear(); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-at-least-one-member-of Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-at-least-one-member-of Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many args + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-at-least-one-member-of Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + + + + + + + + + + // + // UNION tests + // + + + + + + @Test + public void testString_union() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String f = "f"; + String g = "g"; + String h = "h"; + String j = "j"; + + + Bag bagabcdefg = null; + Bag bagbdfhj = null; + Bag bagace = null; + Bag bagaaacccef = null; + Bag bagInt = null; + Bag bagStringInt = null; + Bag bagEmpty = null; + + FunctionArgumentAttributeValue attrBadType = null; + + try { + bagabcdefg = new Bag(); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); + bagbdfhj = new Bag(); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); + bagace = new Bag(); + bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagaaacccef = new Bag(); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagaaacccef.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagInt = new Bag(); + bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagStringInt = new Bag(); + bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagEmpty = new Bag(); + + attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.1)); + } catch (Exception ex) { + fail("creating attribute e="+ ex); + } + + // make into attributes + FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); + FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); + FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); + FunctionArgumentBag attrBagaaacccef = new FunctionArgumentBag(bagaaacccef); + FunctionArgumentBag attrBagInt = new FunctionArgumentBag(bagInt); + FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); + FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); + + FunctionDefinitionSet fd = (FunctionDefinitionSet) StdFunctions.FD_STRING_UNION; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_UNION, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertTrue(fd.returnsBag()); + + // normal intersection (everything in both bags, no duplicates) + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Bag bag = res.getBag(); + assertNotNull(bag); + Iterator> it = bag.getAttributeValues(); + assertEquals(7, bag.size()); + AttributeValue attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + + // several but not all union + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(8, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + + // bag one has duplicates that do not match first bag + arguments.clear(); + arguments.add(attrBagaaacccef); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(8, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + + // bag one has duplicates that do match first bag + arguments.clear(); + arguments.add(attrBagaaacccef); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(4, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + attrValueObject = it.next(); + assertEquals(c, attrValueObject.getValue() ); + attrValueObject = it.next(); + assertEquals(e, attrValueObject.getValue() ); + + // bag 2 has duplicates that do not match first bag + arguments.clear(); + arguments.add(attrBagbdfhj); + arguments.add(attrBagaaacccef); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(8, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(b, attrValueObject.getValue() ); + + // bag 2 has duplicates that do match first bag + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagaaacccef); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(4, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + attrValueObject = it.next(); + assertEquals(c, attrValueObject.getValue() ); + attrValueObject = it.next(); + assertEquals(e, attrValueObject.getValue() ); + + // two empty bags + arguments.clear(); + arguments.add(attrBagEmpty); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(0, bag.size()); + + // first bag empty, 2nd not empty + arguments.clear(); + arguments.add(attrBagEmpty); + arguments.add(attrBagaaacccef); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(4, bag.size()); + + // first bag not empty, 2nd empty + arguments.clear(); + arguments.add(attrBagaaacccef); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(4, bag.size()); + + // bags of different types + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(4, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagInt); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + bag = res.getBag(); + assertNotNull(bag); + it = bag.getAttributeValues(); + assertEquals(4, bag.size()); + attrValueObject = it.next(); + assertEquals(DataTypes.DT_STRING.getId(), attrValueObject.getDataTypeId()); + assertEquals(a, attrValueObject.getValue() ); + + // first not a bag + arguments.clear(); + arguments.add(attrBadType); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-union Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second not a bag + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-union Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // first null + arguments.clear(); + arguments.add(null); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-union Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second null + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-union Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too few args + arguments.clear(); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-union Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-union Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many args + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-union Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + + + + + + + // + // SUBSET tests + // + + @Test + public void testString_subset() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String f = "f"; + String g = "g"; + String h = "h"; + String j = "j"; + + + Bag bagabcdefg = null; + Bag bagbdfhj = null; + Bag bagace = null; + Bag bagb = null; + Bag bagaaaccce = null; + Bag bagInt = null; + Bag bagStringInt = null; + Bag bagEmpty = null; + + FunctionArgumentAttributeValue attrBadType = null; + + try { + bagabcdefg = new Bag(); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); + bagbdfhj = new Bag(); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); + bagace = new Bag(); + bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagb = new Bag(); + bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagaaaccce = new Bag(); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagInt = new Bag(); + bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagStringInt = new Bag(); + bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagEmpty = new Bag(); + + attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.1)); + } catch (Exception ex) { + fail("creating attribute e="+ ex); + } + + // make into attributes + FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); + FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); + FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); + FunctionArgumentBag attrBagb = new FunctionArgumentBag(bagb); + FunctionArgumentBag attrBagaaaccce = new FunctionArgumentBag(bagaaaccce); + FunctionArgumentBag attrBagInt = new FunctionArgumentBag(bagInt); + FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); + FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); + + FunctionDefinitionSet fd = (FunctionDefinitionSet) StdFunctions.FD_STRING_SUBSET; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_SUBSET, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + // normal intersection (everything in both bags, no duplicates) + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + + // not subset + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // subset + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + + // no intersection + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // Not + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagb); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // Subset + arguments.clear(); + arguments.add(attrBagb); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // bag one has duplicates that do not intersect + arguments.clear(); + arguments.add(attrBagaaaccce); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // bag one has duplicates that do intersect + arguments.clear(); + arguments.add(attrBagaaaccce); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // bag 2 has duplicates that do not intersect + arguments.clear(); + arguments.add(attrBagbdfhj); + arguments.add(attrBagaaaccce); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // bag 2 has duplicates that intersect + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagaaaccce); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // 2 empty bags + arguments.clear(); + arguments.add(attrBagEmpty); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first non-empty, 2nd empty + arguments.clear(); + arguments.add(attrBagaaaccce); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first empty, 2nd not empty + arguments.clear(); + arguments.add(attrBagEmpty); + arguments.add(attrBagaaaccce); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // bags of different types + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + arguments.clear(); + arguments.add(attrBagb); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagInt); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first not a bag + arguments.clear(); + arguments.add(attrBadType); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-subset Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second not a bag + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-subset Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // first null + arguments.clear(); + arguments.add(null); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-subset Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second null + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-subset Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too few args + arguments.clear(); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-subset Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-subset Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many args + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-subset Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + + + + + + + + // + // SET_EQUALS tests + // + + @Test + public void testString_set_equals() { + String a = "a"; + String b = "b"; + String c = "c"; + String d = "d"; + String e = "e"; + String f = "f"; + String g = "g"; + String h = "h"; + String j = "j"; + + + Bag bagabcdefg = null; + Bag bagbdfhj = null; + Bag bagace = null; + Bag bagb = null; + Bag bagaaaccce = null; + Bag bagInt = null; + Bag bagStringInt = null; + Bag bagEmpty = null; + + FunctionArgumentAttributeValue attrBadType = null; + + try { + bagabcdefg = new Bag(); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagabcdefg.add(DataTypes.DT_STRING.createAttributeValue(g)); + bagbdfhj = new Bag(); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(d)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(f)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(h)); + bagbdfhj.add(DataTypes.DT_STRING.createAttributeValue(j)); + bagace = new Bag(); + bagace.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagace.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagb = new Bag(); + bagb.add(DataTypes.DT_STRING.createAttributeValue(b)); + bagaaaccce = new Bag(); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(c)); + bagaaaccce.add(DataTypes.DT_STRING.createAttributeValue(e)); + bagInt = new Bag(); + bagInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagStringInt = new Bag(); + bagStringInt.add(DataTypes.DT_STRING.createAttributeValue(a)); + bagStringInt.add(DataTypes.DT_INTEGER.createAttributeValue(123)); + bagEmpty = new Bag(); + + attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(1.1)); + } catch (Exception ex) { + fail("creating attribute e="+ ex); + } + + // make into attributes + FunctionArgumentBag attrBagabcdefg = new FunctionArgumentBag(bagabcdefg); + FunctionArgumentBag attrBagbdfhj = new FunctionArgumentBag(bagbdfhj); + FunctionArgumentBag attrBagace = new FunctionArgumentBag(bagace); + FunctionArgumentBag attrBagb = new FunctionArgumentBag(bagb); + FunctionArgumentBag attrBagaaaccce = new FunctionArgumentBag(bagaaaccce); + FunctionArgumentBag attrBagInt = new FunctionArgumentBag(bagInt); + FunctionArgumentBag attrBagStringInt = new FunctionArgumentBag(bagStringInt); + FunctionArgumentBag attrBagEmpty = new FunctionArgumentBag(bagEmpty); + + FunctionDefinitionSet fd = (FunctionDefinitionSet) StdFunctions.FD_STRING_SET_EQUALS; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_SET_EQUALS, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + // normal intersection (everything in both bags, no duplicates) + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + + // several but not all intersection + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // no intersection + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // one intersection + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagb); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // bag one has duplicates that do not intersect + arguments.clear(); + arguments.add(attrBagaaaccce); + arguments.add(attrBagbdfhj); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // bag one has duplicates that do intersect + arguments.clear(); + arguments.add(attrBagaaaccce); + arguments.add(attrBagace); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // bag 2 has duplicates that do not intersect + arguments.clear(); + arguments.add(attrBagbdfhj); + arguments.add(attrBagaaaccce); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // bag 2 has duplicates that intersect + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagaaaccce); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // 2 empty bags + arguments.clear(); + arguments.add(attrBagEmpty); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first non-empty, 2nd empty + arguments.clear(); + arguments.add(attrBagaaaccce); + arguments.add(attrBagEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first empty, 2nd not empty + arguments.clear(); + arguments.add(attrBagEmpty); + arguments.add(attrBagaaaccce); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // bags of different types + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagStringInt); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + arguments.clear(); + arguments.add(attrBagace); + arguments.add(attrBagInt); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first not a bag + arguments.clear(); + arguments.add(attrBadType); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-set-equals Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second not a bag + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-set-equals Expected a bag, saw a simple value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // first null + arguments.clear(); + arguments.add(null); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-set-equals Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // second null + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-set-equals Got null argument", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too few args + arguments.clear(); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-set-equals Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-set-equals Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many args + arguments.clear(); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + arguments.add(attrBagabcdefg); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-set-equals Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + + + + + + + // + // + // REST OF DATA TYPES OMITTED + // because they "should" all work the same + // + // + + + + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionSpecialMatchTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionSpecialMatchTest.java new file mode 100644 index 000000000..e4c68514d --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionSpecialMatchTest.java @@ -0,0 +1,487 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import javax.security.auth.x500.X500Principal; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.Bag; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentBag; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionSpecialMatchTest { + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + @Test + public void testX500NameMatch() { + // assume that the contents of the name components are not significant and we can treat them as simple blocks of "=" + String A = "cn=Some person"; + String B = "O=Medico Corp"; + String C = "C=US"; + String D = "DNQUALIFIER=d string"; + String E = "SURNAME=some name"; + String F = "INITIALS=inits"; + + + X500Principal abc = new X500Principal(A + "," + B + "," + C); + X500Principal dabc = new X500Principal(D + "," + A + "," + B + "," + C); + X500Principal abcd = new X500Principal(A + "," + B + "," + C + "," + D); + X500Principal adbc = new X500Principal(A + "," + D + "," + B + "," + C); + X500Principal dcab = new X500Principal(D + "," + C + "," + A + "," + B) ; + X500Principal def = new X500Principal(D + "," + E + "," + F) ; + + + FunctionArgumentAttributeValue attrABC = null; + FunctionArgumentAttributeValue attrDABC = null; + FunctionArgumentAttributeValue attrABCD = null; + FunctionArgumentAttributeValue attrADBC = null; + FunctionArgumentAttributeValue attrDCAB = null; + FunctionArgumentAttributeValue attrDEF = null; + + FunctionArgumentAttributeValue attrBad = null; + FunctionArgumentBag attrBag = new FunctionArgumentBag(new Bag()); + + + try { + attrABC = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(abc)); + attrDABC = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(dabc)); + attrABCD = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(abcd)); + attrADBC = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(adbc)); + attrDCAB = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(dcab)); + attrDEF = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(def)); + + attrBad = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionX500NameMatch fd = (FunctionDefinitionX500NameMatch) StdFunctions.FD_X500NAME_MATCH; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_X500NAME_MATCH, fd.getId()); + assertEquals(DataTypes.DT_X500NAME.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + + // test normal, first exact match for second + arguments.clear(); + arguments.add(attrABC); + arguments.add(attrABC); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // test first is end of second + arguments.clear(); + arguments.add(attrABC); + arguments.add(attrDABC); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // first exact match for sub-section but not end of second + arguments.clear(); + arguments.add(attrABC); + arguments.add(attrABCD); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // components of first match components in second but not contiguous + arguments.clear(); + arguments.add(attrABC); + arguments.add(attrADBC); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // components of first match components in second but not in order + arguments.clear(); + arguments.add(attrABC); + arguments.add(attrDCAB); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first does not match second at all + arguments.clear(); + arguments.add(attrABC); + arguments.add(attrDEF); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first arg larger than 2nd arg + arguments.clear(); + arguments.add(attrABCD); + arguments.add(attrABC); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // bad arg types + arguments.clear(); + arguments.add(attrABC); + arguments.add(attrBad); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:x500Name-match Expected data type 'x500Name' saw 'integer' at arg index 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many args + arguments.clear(); + arguments.add(attrABC); + arguments.add(attrABC); + arguments.add(attrABC); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:x500Name-match Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too few args + arguments.clear(); + arguments.add(attrABC); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:x500Name-match Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:x500Name-match Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // one arg is bag + arguments.clear(); + arguments.add(attrABC); + arguments.add(attrBag); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:x500Name-match Expected a simple value, saw a bag at arg index 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null arg + arguments.clear(); + arguments.add(null); + arguments.add(attrBag); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:x500Name-match Got null argument at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + @Test + public void testRfc822NameMatch() { + + + + + FunctionArgumentAttributeValue attrStringabcxyz = null; + FunctionArgumentAttributeValue attrStringABCxyz = null; + FunctionArgumentAttributeValue attrStringabcXYZ = null; + FunctionArgumentAttributeValue attrStringcx = null; + FunctionArgumentAttributeValue attrStringwholedomainpart = null; + FunctionArgumentAttributeValue attrStringWholeDomainPart = null; + FunctionArgumentAttributeValue attrStringWholeDomain = null; + FunctionArgumentAttributeValue attrStringdomainpart = null; + FunctionArgumentAttributeValue attrStringDomainPart = null; + FunctionArgumentAttributeValue attrStringdotWholeDomain = null; + FunctionArgumentAttributeValue attrStringdomain = null; + + FunctionArgumentAttributeValue attrStringNoMatch = null; + FunctionArgumentAttributeValue attrStringMultipleAt = null; + FunctionArgumentAttributeValue attrStringMissingLocal = null; + FunctionArgumentAttributeValue attrStringMissingDomain = null; + + + FunctionArgumentAttributeValue attrRfcabcxyz = null; + FunctionArgumentAttributeValue attrRfcwholedomainpart = null; + FunctionArgumentAttributeValue attrRfcWholeDomainPart = null; + + FunctionArgumentBag attrBag = new FunctionArgumentBag(new Bag()); + + try { + attrStringabcxyz = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc@xyz")); + attrStringABCxyz = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("ABC@xyz")); + attrStringabcXYZ = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc@XYZ")); + attrStringcx = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("c@x")); + attrStringwholedomainpart = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("whole.domain.part")); + attrStringWholeDomainPart = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("Whole.Domain.Part")); + attrStringWholeDomain = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("Whole.Domain")); + attrStringdomainpart = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(".domain.part")); + attrStringDomainPart = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(".Domain.Part")); + attrStringdotWholeDomain = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(".Whole.Domain")); + attrStringdomain = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(".domain.")); + + attrStringNoMatch = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("no match to any legal name")); + attrStringMultipleAt = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("name@with@multipleAts")); + attrStringMissingLocal = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("@multipleAts")); + attrStringMissingDomain = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("localpart@")); + + attrRfcabcxyz = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue("abc@xyz")); + attrRfcwholedomainpart = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue("abc@whole.domain.part")); + attrRfcWholeDomainPart = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue("abc@Whole.Domain.Part")); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionRFC822NameMatch fd = (FunctionDefinitionRFC822NameMatch) StdFunctions.FD_RFC822NAME_MATCH; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_RFC822NAME_MATCH, fd.getId()); + assertEquals(DataTypes.DT_RFC822NAME.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // string identical to name - exact match on whole search term + arguments.clear(); + arguments.add(attrStringabcxyz); + arguments.add(attrRfcabcxyz); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.getStatus().isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // no match local case different + arguments.clear(); + arguments.add(attrStringABCxyz); + arguments.add(attrRfcabcxyz); + res = fd.evaluate(null, arguments); + assertTrue(res.getStatus().isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // match domain case different + arguments.clear(); + arguments.add(attrStringabcXYZ); + arguments.add(attrRfcabcxyz); + res = fd.evaluate(null, arguments); + assertTrue(res.getStatus().isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + + // partial local + partial domain + arguments.clear(); + arguments.add(attrStringcx); + arguments.add(attrRfcabcxyz); + res = fd.evaluate(null, arguments); + assertTrue(res.getStatus().isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // whole domain + arguments.clear(); + arguments.add(attrStringwholedomainpart); + arguments.add(attrRfcwholedomainpart); + res = fd.evaluate(null, arguments); + assertTrue(res.getStatus().isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // whole domain different case + arguments.clear(); + arguments.add(attrStringWholeDomainPart); + arguments.add(attrRfcwholedomainpart); + res = fd.evaluate(null, arguments); + assertTrue(res.getStatus().isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + arguments.clear(); + arguments.add(attrStringwholedomainpart); + arguments.add(attrRfcWholeDomainPart); + res = fd.evaluate(null, arguments); + assertTrue(res.getStatus().isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // whole domain fail + arguments.clear(); + arguments.add(attrStringWholeDomain); + arguments.add(attrRfcWholeDomainPart); + res = fd.evaluate(null, arguments); + assertTrue(res.getStatus().isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // partial domain match + arguments.clear(); + arguments.add(attrStringDomainPart); + arguments.add(attrRfcWholeDomainPart); + res = fd.evaluate(null, arguments); + assertTrue(res.getStatus().isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // partial domain different case + arguments.clear(); + arguments.add(attrStringdomainpart); + arguments.add(attrRfcWholeDomainPart); + res = fd.evaluate(null, arguments); + assertTrue(res.getStatus().isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // partial domain fail + arguments.clear(); + arguments.add(attrStringdotWholeDomain); + arguments.add(attrRfcWholeDomainPart); + res = fd.evaluate(null, arguments); + assertTrue(res.getStatus().isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + arguments.clear(); + arguments.add(attrStringdomain); + arguments.add(attrRfcWholeDomainPart); + res = fd.evaluate(null, arguments); + assertTrue(res.getStatus().isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // search term contains more than 1 @ + arguments.clear(); + arguments.add(attrStringMultipleAt); + arguments.add(attrRfcabcxyz); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:rfc822Name-match String contained more than 1 '@' in 'name@with@multipleAts'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // search term missing local part + arguments.clear(); + arguments.add(attrStringMissingLocal); + arguments.add(attrRfcabcxyz); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:rfc822Name-match String missing local part in '@multipleAts'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // search term missing domain part + arguments.clear(); + arguments.add(attrStringMissingDomain); + arguments.add(attrRfcabcxyz); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:rfc822Name-match String missing domain part in 'localpart@'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg types + arguments.clear(); + arguments.add(attrRfcabcxyz); + arguments.add(attrStringNoMatch); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:rfc822Name-match Expected data type 'string' saw 'rfc822Name' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many args + arguments.clear(); + arguments.add(attrStringNoMatch); + arguments.add(attrStringNoMatch); + arguments.add(attrStringNoMatch); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:rfc822Name-match Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too few args + arguments.clear(); + arguments.add(attrStringNoMatch); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:rfc822Name-match Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:rfc822Name-match Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // one arg is bag + arguments.clear(); + arguments.add(attrStringNoMatch); + arguments.add(attrBag); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:rfc822Name-match Expected a simple value, saw a bag at arg index 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null arg + arguments.clear(); + arguments.add(null); + arguments.add(attrStringNoMatch); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:rfc822Name-match Got null argument at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringConversionTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringConversionTest.java new file mode 100644 index 000000000..3268266f4 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringConversionTest.java @@ -0,0 +1,2504 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.math.BigInteger; +import java.net.URI; +import java.net.URISyntaxException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; + +import javax.security.auth.x500.X500Principal; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacml.std.datatypes.IPAddress; +import com.att.research.xacml.std.datatypes.IPv4Address; +import com.att.research.xacml.std.datatypes.IPv6Address; +import com.att.research.xacml.std.datatypes.ISO8601Date; +import com.att.research.xacml.std.datatypes.ISO8601DateTime; +import com.att.research.xacml.std.datatypes.ISO8601Time; +import com.att.research.xacml.std.datatypes.ISO8601TimeZone; +import com.att.research.xacml.std.datatypes.PortRange; +import com.att.research.xacml.std.datatypes.RFC2396DomainName; +import com.att.research.xacml.std.datatypes.RFC822Name; +import com.att.research.xacml.std.datatypes.XPathDayTimeDuration; +import com.att.research.xacml.std.datatypes.XPathYearMonthDuration; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Tests for converting objects to/from Strings. + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionStringConversionTest { + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + + /** + * Boolean + */ + @Test + public void testBoolean_from_string() { + FunctionArgumentAttributeValue attrString1 = null; + FunctionArgumentAttributeValue attrStringBadValue = null; + FunctionArgumentAttributeValue attrStringBadType = null; + try { + attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("true")); + attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_BOOLEAN_FROM_STRING; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_BOOLEAN_FROM_STRING, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrString1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(new Boolean(true), resValue); + + // bad value + arguments.clear(); + arguments.add(attrStringBadValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:boolean-from-string Cannot convert from \"java.lang.String\" with value \"not valid obj value\" to boolean", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:boolean-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + @Test + public void testString_from_boolean() { + FunctionArgumentAttributeValue attrObj1 = null; + FunctionArgumentAttributeValue attrStringBadType = null; + String objValueString = "false"; + try { + attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_BOOLEAN.createAttributeValue(objValueString)); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_BOOLEAN; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_FROM_BOOLEAN, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrObj1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(objValueString, res.getValue().getValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-from-boolean Expected data type 'boolean' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + + /** + * Integer + */ + @Test + public void testInteger_from_string() { + FunctionArgumentAttributeValue attrString1 = null; + FunctionArgumentAttributeValue attrStringBadValue = null; + FunctionArgumentAttributeValue attrStringBadType = null; + try { + attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123456")); + attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_INTEGER_FROM_STRING; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_INTEGER_FROM_STRING, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrString1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + BigInteger resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("123456"), resValue); + + // bad value + arguments.clear(); + arguments.add(attrStringBadValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:integer-from-string For input string: \"n\"", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:integer-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + @Test + public void testString_from_integer() { + FunctionArgumentAttributeValue attrObj1 = null; + FunctionArgumentAttributeValue attrStringBadType = null; + String objValueString = "1234"; + try { + attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(objValueString)); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_INTEGER; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_FROM_INTEGER, fd.getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrObj1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(objValueString, res.getValue().getValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-from-integer Expected data type 'integer' saw 'double' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + /** + * Double + */ + @Test + public void testDouble_from_string() { + FunctionArgumentAttributeValue attrString1 = null; + FunctionArgumentAttributeValue attrStringBadValue = null; + FunctionArgumentAttributeValue attrStringBadType = null; + try { + attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("5.432")); + attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_DOUBLE_FROM_STRING; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DOUBLE_FROM_STRING, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrString1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Double resValue = (Double)res.getValue().getValue(); + assertEquals(new Double(5.432), resValue); + + // bad value + arguments.clear(); + arguments.add(attrStringBadValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:double-from-string For input string: \"not valid obj value\"", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:double-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + @Test + public void testString_from_double() { + FunctionArgumentAttributeValue attrObj1 = null; + FunctionArgumentAttributeValue attrObjBig = null; + FunctionArgumentAttributeValue attrStringBadType = null; + String objValueString = "5.432"; + String objValueStringBig = "55555555555555555555.123455"; + try { + attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(objValueString)); + attrObjBig = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(objValueStringBig)); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_DOUBLE; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_FROM_DOUBLE, fd.getId()); + assertEquals(DataTypes.DT_DOUBLE.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrObj1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(objValueString, res.getValue().getValue()); + + arguments.clear(); + arguments.add(attrObjBig); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals("5.555555555555556E19", res.getValue().getValue()); + + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-from-double Expected data type 'double' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + + + /** + * Time + */ + @Test + public void testTime_from_string() { + FunctionArgumentAttributeValue attrString1 = null; + FunctionArgumentAttributeValue attrString2 = null; + FunctionArgumentAttributeValue attrString3 = null; + FunctionArgumentAttributeValue attrString4 = null; + FunctionArgumentAttributeValue attrStringTimeZone = null; + FunctionArgumentAttributeValue attrStringBadValue = null; + FunctionArgumentAttributeValue attrStringBadType = null; + try { + attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("05:12:34.323")); + attrString2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("5:12:34.323")); + attrString3 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("05:12")); + attrString4 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("05:12:34")); + attrStringTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("05:12:34.323+03:00")); + attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_TIME_FROM_STRING; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_TIME_FROM_STRING, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrString1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + ISO8601Time resValue = (ISO8601Time)res.getValue().getValue(); + assertEquals(new ISO8601Time(5, 12, 34, 323), resValue); + + // check missing 0 in front + arguments.clear(); + arguments.add(attrString2); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:time-from-string Invalid hour of day", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // check missing seconds/msecs + arguments.clear(); + arguments.add(attrString3); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:time-from-string Time string too short", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // check missing just msecs + arguments.clear(); + arguments.add(attrString4); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (ISO8601Time)res.getValue().getValue(); + assertEquals(new ISO8601Time(5, 12, 34, 0), resValue); + + // check TimeZone + arguments.clear(); + arguments.add(attrStringTimeZone); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (ISO8601Time)res.getValue().getValue(); + assertEquals(new ISO8601Time(new ISO8601TimeZone(180), 5, 12, 34, 323), resValue); + + // bad value + arguments.clear(); + arguments.add(attrStringBadValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:time-from-string Invalid hour of day", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:time-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + @Test + public void testString_from_time() { + FunctionArgumentAttributeValue attrObj1 = null; + FunctionArgumentAttributeValue attrObj2 = null; + FunctionArgumentAttributeValue attrObjTimeZone = null; + FunctionArgumentAttributeValue attrStringBadType = null; + try { + attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue("05:12:34.323")); + attrObj2 = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue("05:01:02.323")); + attrObjTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_TIME.createAttributeValue("05:12:34.323+03:00")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_TIME; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_FROM_TIME, fd.getId()); + assertEquals(DataTypes.DT_TIME.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrObj1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals("05:12:34.323", res.getValue().getValue()); + + // missing digits in string value? + arguments.clear(); + arguments.add(attrObj2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals("05:01:02.323", res.getValue().getValue()); + + // include TimeZone + arguments.clear(); + arguments.add(attrObjTimeZone); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals("05:12:34.323+03:00", res.getValue().getValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-from-time Expected data type 'time' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + + + /** + * Date + */ + @Test + public void testDate_from_string() { + FunctionArgumentAttributeValue attrString1 = null; + FunctionArgumentAttributeValue attrString2 = null; + FunctionArgumentAttributeValue attrString3 = null; + FunctionArgumentAttributeValue attrString4 = null; + FunctionArgumentAttributeValue attrString5 = null; + FunctionArgumentAttributeValue attrString6 = null; + FunctionArgumentAttributeValue attrString7 = null; + FunctionArgumentAttributeValue attrString8 = null; + FunctionArgumentAttributeValue attrString9 = null; + FunctionArgumentAttributeValue attrStringDateZone = null; + FunctionArgumentAttributeValue attrStringBadValue = null; + FunctionArgumentAttributeValue attrStringBadType = null; + try { + attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-12")); + attrString2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("-2013-05-12")); + attrString3 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("1232013-05-12")); + attrString4 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("-1232013-05-12")); + attrString5 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("213-05-12")); + attrString6 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-5-12")); + attrString7 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-2")); + attrString8 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-32-12")); + attrString9 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-45")); + attrStringDateZone = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-12+03:00")); + attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_DATE_FROM_STRING; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATE_FROM_STRING, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrString1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + ISO8601Date resValue = (ISO8601Date)res.getValue().getValue(); + assertEquals(new ISO8601Date(2013, 5, 12), resValue); + + // check negative + arguments.clear(); + arguments.add(attrString2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (ISO8601Date)res.getValue().getValue(); + assertEquals(new ISO8601Date(-2013, 5, 12), resValue); + + // check big + arguments.clear(); + arguments.add(attrString3); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (ISO8601Date)res.getValue().getValue(); + assertEquals(new ISO8601Date(1232013, 5, 12), resValue); + + // check big negative + arguments.clear(); + arguments.add(attrString4); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (ISO8601Date)res.getValue().getValue(); + assertEquals(new ISO8601Date(-1232013, 5, 12), resValue); + + // bad year + arguments.clear(); + arguments.add(attrString5); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-from-string Invalid year (must be at least 4 digits)", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad month + arguments.clear(); + arguments.add(attrString6); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-from-string Invalid month", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad day format + arguments.clear(); + arguments.add(attrString7); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-from-string Invalid day", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // month out of range + arguments.clear(); + arguments.add(attrString8); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-from-string Invalid month", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // day out of range + arguments.clear(); + arguments.add(attrString9); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-from-string Invalid day", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // check TimeZone + arguments.clear(); + arguments.add(attrStringDateZone); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (ISO8601Date)res.getValue().getValue(); + assertEquals(new ISO8601Date(new ISO8601TimeZone(180), 2013, 5, 12), resValue); + + // bad value + arguments.clear(); + arguments.add(attrStringBadValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-from-string Invalid year", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:date-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + @Test + public void testString_from_date() { + FunctionArgumentAttributeValue attrObj1 = null; + FunctionArgumentAttributeValue attrObj2 = null; + FunctionArgumentAttributeValue attrObjDateZone = null; + FunctionArgumentAttributeValue attrStringBadType = null; + try { + attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue("2013-05-12")); + attrObj2 = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue("0001-01-01")); + attrObjDateZone = new FunctionArgumentAttributeValue(DataTypes.DT_DATE.createAttributeValue("2013-05-12+03:00")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_DATE; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_FROM_DATE, fd.getId()); + assertEquals(DataTypes.DT_DATE.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrObj1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals("2013-05-12", res.getValue().getValue()); + + // missing digits in string value? + arguments.clear(); + arguments.add(attrObj2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals("1-01-01", res.getValue().getValue()); + + // include DateZone + arguments.clear(); + arguments.add(attrObjDateZone); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals("2013-05-12+03:00", res.getValue().getValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-from-date Expected data type 'date' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + + + + /** + * DateTime + */ + @Test + public void testDateTime_from_string() { + FunctionArgumentAttributeValue attrString1 = null; + FunctionArgumentAttributeValue attrString2 = null; + FunctionArgumentAttributeValue attrString3 = null; + FunctionArgumentAttributeValue attrString4 = null; + FunctionArgumentAttributeValue attrString5 = null; + FunctionArgumentAttributeValue attrString6 = null; + FunctionArgumentAttributeValue attrString7 = null; + FunctionArgumentAttributeValue attrString8 = null; + FunctionArgumentAttributeValue attrString9 = null; + FunctionArgumentAttributeValue attrStringDateTimeZone = null; + FunctionArgumentAttributeValue attrStringBadValue = null; + FunctionArgumentAttributeValue attrStringBadType = null; + try { + attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-12T12:14:15.323")); + attrString2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("-2013-05-12T12:14:15.323")); + attrString3 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("1232013-05-12T12:14:15.323")); + attrString4 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("-1232013-05-12T12:14:15.323")); + attrString5 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("213-05-12T12:14:15.323")); + attrString6 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-5-12T12:14:15.323")); + attrString7 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-2T12:14:15.323")); + attrString8 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-32-12T12:14:15.323")); + attrString9 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-45T12:14:15.323")); + attrStringDateTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2013-05-12T12:14:15.323+03:00")); + attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_DATETIME_FROM_STRING; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DATETIME_FROM_STRING, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrString1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + ISO8601DateTime resValue = (ISO8601DateTime)res.getValue().getValue(); + assertEquals(new ISO8601DateTime(null, new ISO8601Date(2013, 5, 12), new ISO8601Time(12, 14, 15, 323)), resValue); + + // check negative + arguments.clear(); + arguments.add(attrString2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + assertEquals(new ISO8601DateTime(null, new ISO8601Date(-2013, 5, 12), new ISO8601Time(12, 14, 15, 323)), resValue); + + + // check big + arguments.clear(); + arguments.add(attrString3); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + assertEquals(new ISO8601DateTime(null, new ISO8601Date(1232013, 5, 12), new ISO8601Time(12, 14, 15, 323)), resValue); + + // check big negative + arguments.clear(); + arguments.add(attrString4); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + assertEquals(new ISO8601DateTime(null, new ISO8601Date(-1232013, 5, 12), new ISO8601Time(12, 14, 15, 323)), resValue); + + // bad year + arguments.clear(); + arguments.add(attrString5); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-from-string Invalid year (must be at least 4 digits)", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad month + arguments.clear(); + arguments.add(attrString6); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-from-string Invalid month", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad day format + arguments.clear(); + arguments.add(attrString7); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-from-string Invalid day", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // month out of range + arguments.clear(); + arguments.add(attrString8); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-from-string Invalid month", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // day out of range + arguments.clear(); + arguments.add(attrString9); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-from-string Invalid day", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // check TimeZone + arguments.clear(); + arguments.add(attrStringDateTimeZone); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (ISO8601DateTime)res.getValue().getValue(); + assertEquals(new ISO8601DateTime(new ISO8601TimeZone(180), new ISO8601Date(new ISO8601TimeZone(180), 2013, 5, 12), new ISO8601Time(new ISO8601TimeZone(180),12, 14, 15, 323)), resValue); + + // bad value + arguments.clear(); + arguments.add(attrStringBadValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-from-string Invalid year", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dateTime-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + @Test + public void testString_from_dateTime() { + FunctionArgumentAttributeValue attrObj1 = null; + FunctionArgumentAttributeValue attrObj2 = null; + FunctionArgumentAttributeValue attrObjDateTimeZone = null; + FunctionArgumentAttributeValue attrStringBadType = null; + try { + attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue("2013-05-12T12:14:15.323")); + attrObj2 = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue("0001-01-01T12:14:15.323")); + attrObjDateTimeZone = new FunctionArgumentAttributeValue(DataTypes.DT_DATETIME.createAttributeValue("2013-05-12T12:14:15.323+03:00")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_DATETIME; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_FROM_DATETIME, fd.getId()); + assertEquals(DataTypes.DT_DATETIME.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrObj1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals("2013-05-12T12:14:15.323", res.getValue().getValue()); + + // missing digits in string value? + arguments.clear(); + arguments.add(attrObj2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals("1-01-01T12:14:15.323", res.getValue().getValue()); + + // include DateTimeZone + arguments.clear(); + arguments.add(attrObjDateTimeZone); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals("2013-05-12T12:14:15.323+03:00", res.getValue().getValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-from-dateTime Expected data type 'dateTime' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + + + /** + * URI + */ + @Test + public void testURI_from_string() { + FunctionArgumentAttributeValue attrString1 = null; + FunctionArgumentAttributeValue attrStringBadValue = null; + FunctionArgumentAttributeValue attrStringBadType = null; + try { + attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("http://someMachine.com/subdir")); + attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_ANYURI_FROM_STRING; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_ANYURI_FROM_STRING, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_ANYURI.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrString1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + URI resValue = (URI)res.getValue().getValue(); + try { + assertEquals(new URI("http://someMachine.com/subdir"), resValue); + } catch (URISyntaxException e) { + fail("uri generation e="+e); + } + + // bad value + arguments.clear(); + arguments.add(attrStringBadValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-from-string Illegal character in path at index 3: not valid obj value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + @Test + public void testString_from_anyURI() { + FunctionArgumentAttributeValue attrObj1 = null; + FunctionArgumentAttributeValue attrStringBadType = null; + String objValueString = "http://aMachine.com:8080/aRef"; + try { + attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(objValueString)); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_ANYURI; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_FROM_ANYURI, fd.getId()); + assertEquals(DataTypes.DT_ANYURI.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrObj1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(objValueString, res.getValue().getValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-from-anyURI Expected data type 'anyURI' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + /** + * XPathDayTimeDuration + */ + @Test + public void testXPathDayTimeDuration_from_string() { + FunctionArgumentAttributeValue attrString1 = null; + FunctionArgumentAttributeValue attrStringNeg1 = null; + FunctionArgumentAttributeValue attrStringNeg2 = null; + FunctionArgumentAttributeValue attrStringNoDay = null; + FunctionArgumentAttributeValue attrStringNoHour = null; + FunctionArgumentAttributeValue attrStringNoMin = null; + FunctionArgumentAttributeValue attrStringNoSec = null; + FunctionArgumentAttributeValue attrStringNoP = null; + FunctionArgumentAttributeValue attrStringSecondsDot = null; + FunctionArgumentAttributeValue attrStringMissingTOk = null; + FunctionArgumentAttributeValue attrStringMissingTBad = null; + FunctionArgumentAttributeValue attrStringBadValue = null; + FunctionArgumentAttributeValue attrStringBadType = null; + try { + attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3DT10H30M23S")); + attrStringNeg1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("-P3DT10H30M23S")); + attrStringNeg2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P-3DT10H30M23S")); + attrStringNoDay = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("PT10H30M23S")); + attrStringNoHour = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3DT30M23S")); + attrStringNoMin = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3DT10H23S")); + attrStringNoSec = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3DT10H30M")); + attrStringNoP = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("3DT10H30M")); + attrStringSecondsDot = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3DT10H30M23.456S")); + attrStringMissingTOk = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3D")); + attrStringMissingTBad = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3D10H30M23S")); + + attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_DAYTIMEDURATION_FROM_STRING; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DAYTIMEDURATION_FROM_STRING, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_DAYTIMEDURATION.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrString1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + XPathDayTimeDuration resValue = (XPathDayTimeDuration)res.getValue().getValue(); + assertEquals(new XPathDayTimeDuration(1, 3, 10, 30, 23), resValue); + + + // negative values in front is allowed + arguments.clear(); + arguments.add(attrStringNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (XPathDayTimeDuration)res.getValue().getValue(); + assertEquals(new XPathDayTimeDuration(-1, 3, 10, 30, 23), resValue); + + // negative in middle of string not ok + arguments.clear(); + arguments.add(attrStringNeg2); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dayTimeDuration-from-string Invalid chunk \"P-3DT10H30M23S\" at position 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // omit parts that are 0 + arguments.clear(); + arguments.add(attrStringNoDay); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (XPathDayTimeDuration)res.getValue().getValue(); + assertEquals(new XPathDayTimeDuration(1, 0, 10, 30, 23), resValue); + + arguments.clear(); + arguments.add(attrStringNoHour); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (XPathDayTimeDuration)res.getValue().getValue(); + assertEquals(new XPathDayTimeDuration(1, 3, 0, 30, 23), resValue); + + arguments.clear(); + arguments.add(attrStringNoMin); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (XPathDayTimeDuration)res.getValue().getValue(); + assertEquals(new XPathDayTimeDuration(1, 3, 10, 0, 23), resValue); + + arguments.clear(); + arguments.add(attrStringNoSec); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (XPathDayTimeDuration)res.getValue().getValue(); + assertEquals(new XPathDayTimeDuration(1, 3, 10, 30, 0), resValue); + + // P must always be present + arguments.clear(); + arguments.add(attrStringNoP); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dayTimeDuration-from-string Invalid ISO8601 duration string \"3DT10H30M\" at position 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // seconds may contain decimal + arguments.clear(); + arguments.add(attrStringSecondsDot); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (XPathDayTimeDuration)res.getValue().getValue(); + assertEquals(new XPathDayTimeDuration(1, 3, 10, 30, 23.456), resValue); + + // T must be absent iff all time items are absent + arguments.clear(); + arguments.add(attrStringMissingTOk); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (XPathDayTimeDuration)res.getValue().getValue(); + assertEquals(new XPathDayTimeDuration(1, 3, 0, 0, 0), resValue); + + // negative in middle of string not ok + arguments.clear(); + arguments.add(attrStringMissingTBad); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dayTimeDuration-from-string Invalid ISO8601 duration string \"P3D10H30M23S\" at position 6: out of order component", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // bad value + arguments.clear(); + arguments.add(attrStringBadValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dayTimeDuration-from-string Invalid ISO8601 duration string \"not valid obj value\" at position 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dayTimeDuration-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + @Test + public void testString_from_dayTimeDuration() { + FunctionArgumentAttributeValue attrObj1 = null; + FunctionArgumentAttributeValue attrStringBadType = null; + String objValueString = "P3DT10H30M23S"; + try { + attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_DAYTIMEDURATION.createAttributeValue(objValueString)); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_DAYTIMEDURATION; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_FROM_DAYTIMEDURATION, fd.getId()); + assertEquals(DataTypes.DT_DAYTIMEDURATION.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrObj1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(objValueString, res.getValue().getValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-from-dayTimeDuration Expected data type 'dayTimeDuration' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + + + + + + + /** + * XPathYearMonthDuration + */ + @Test + public void testXPathYearMonthDuration_from_string() { + FunctionArgumentAttributeValue attrString1 = null; + FunctionArgumentAttributeValue attrStringNeg1 = null; + FunctionArgumentAttributeValue attrStringNeg2 = null; + FunctionArgumentAttributeValue attrStringNoYear1 = null; + FunctionArgumentAttributeValue attrStringNoYear2 = null; + FunctionArgumentAttributeValue attrStringNoMonth1 = null; + FunctionArgumentAttributeValue attrStringNoMonth2 = null; + FunctionArgumentAttributeValue attrStringNoValue = null; + FunctionArgumentAttributeValue attrStringNoP = null; + FunctionArgumentAttributeValue attrStringBigMonths = null; + FunctionArgumentAttributeValue attrStringMissingTOk = null; + FunctionArgumentAttributeValue attrStringMissingTBad = null; + FunctionArgumentAttributeValue attrStringZeroMonths = null; + FunctionArgumentAttributeValue attrStringBadValue = null; + FunctionArgumentAttributeValue attrStringBadType = null; + try { + attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P1Y2M")); + attrStringNeg1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("-P1Y2M")); + attrStringNeg2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P-1Y2M")); + attrStringNoYear1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P2M")); + attrStringNoYear2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("PY2M")); + attrStringNoMonth1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P1Y")); + attrStringNoMonth2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P1YM")); + attrStringNoValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P")); + attrStringNoP = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("1Y2M")); + attrStringBigMonths = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P1Y12M")); + attrStringMissingTOk = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3D")); + attrStringMissingTBad = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P3D10H30M23S")); + attrStringZeroMonths = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("P0M")); + + attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_YEARMONTHDURATION_FROM_STRING; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_YEARMONTHDURATION_FROM_STRING, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_YEARMONTHDURATION.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrString1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + XPathYearMonthDuration resValue = (XPathYearMonthDuration)res.getValue().getValue(); + assertEquals(new XPathYearMonthDuration(1,1, 2), resValue); + + + // negative values in front is allowed + arguments.clear(); + arguments.add(attrStringNeg1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (XPathYearMonthDuration)res.getValue().getValue(); + assertEquals(new XPathYearMonthDuration(-1, 1, 2), resValue); + + // negative in middle of string not ok + arguments.clear(); + arguments.add(attrStringNeg2); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:yearMonthDuration-from-string Invalid chunk \"P-1Y2M\" at position 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // omit parts that are 0 + arguments.clear(); + arguments.add(attrStringNoYear1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (XPathYearMonthDuration)res.getValue().getValue(); + assertEquals(new XPathYearMonthDuration(1, 0, 2), resValue); + + arguments.clear(); + arguments.add(attrStringNoYear2); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:yearMonthDuration-from-string Invalid chunk \"PY2M\" at position 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + arguments.clear(); + arguments.add(attrStringNoMonth1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (XPathYearMonthDuration)res.getValue().getValue(); + assertEquals(new XPathYearMonthDuration(1, 1, 0), resValue); + + arguments.clear(); + arguments.add(attrStringNoMonth2); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:yearMonthDuration-from-string Invalid chunk \"P1YM\" at position 3", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // No field with a value + arguments.clear(); + arguments.add(attrStringNoValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:yearMonthDuration-from-string Invalid ISO8601 duration string \"P\": No duration components following P", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // P must always be present + arguments.clear(); + arguments.add(attrStringNoP); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:yearMonthDuration-from-string Invalid ISO8601 duration string \"1Y2M\" at position 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // Canonical Form of output may not have more than 12 months, but input as string is ok? + arguments.clear(); + arguments.add(attrStringBigMonths); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (XPathYearMonthDuration)res.getValue().getValue(); + assertEquals(new XPathYearMonthDuration(1, 1, 12), resValue); + + // Canonical representation of 0 Months + arguments.clear(); + arguments.add(attrStringZeroMonths); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (XPathYearMonthDuration)res.getValue().getValue(); + assertEquals(new XPathYearMonthDuration(1, 0, 0), resValue); + + // T must be absent iff all time items are absent + arguments.clear(); + arguments.add(attrStringMissingTOk); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:yearMonthDuration-from-string Invalid XPath yearMonthDuraiton \"{durationSign=1years=0months=0days=3hours=0minutes=0seconds=0millis=0}\": includes days, hours, minutes, or seconds", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // negative in middle of string not ok + arguments.clear(); + arguments.add(attrStringMissingTBad); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:yearMonthDuration-from-string Invalid ISO8601 duration string \"P3D10H30M23S\" at position 6: out of order component", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // bad value + arguments.clear(); + arguments.add(attrStringBadValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:yearMonthDuration-from-string Invalid ISO8601 duration string \"not valid obj value\" at position 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:yearMonthDuration-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + @Test + public void testString_from_yearMonthDuration() { + FunctionArgumentAttributeValue attrObj1 = null; + FunctionArgumentAttributeValue attrStringBadType = null; + String objValueString = "P1Y2M"; + try { + attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_YEARMONTHDURATION.createAttributeValue(objValueString)); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_YEARMONTHDURATION; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_FROM_YEARMONTHDURATION, fd.getId()); + assertEquals(DataTypes.DT_YEARMONTHDURATION.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrObj1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(objValueString, res.getValue().getValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-from-yearMonthDuration Expected data type 'yearMonthDuration' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + + + + /** + * X500Principal + * + * See http://www.ietf.org/rfc/rfc2253.txt and http://www.ietf.org/rfc/rfc2251.txt + */ + @Test + public void testX500Principal_from_string() { + FunctionArgumentAttributeValue attrString1 = null; + FunctionArgumentAttributeValue attrStringNoComma = null; + FunctionArgumentAttributeValue attrStringEmpty = null; + FunctionArgumentAttributeValue attrStringNoValue = null; + FunctionArgumentAttributeValue attrStringOrder = null; + FunctionArgumentAttributeValue attrStringDottedDecimalOID = null; + FunctionArgumentAttributeValue attrStringBadValue = null; + FunctionArgumentAttributeValue attrStringBadType = null; + try { + attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("CN=Name, L=local, ST=NJ, O=ATT, C=USA")); + attrStringNoComma = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("CN=Name, L=local ST=NJ, O=ATT, C=USA")); + attrStringEmpty = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); + attrStringNoValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("CN=Name, L=, ST=NJ, O=ATT, C=USA")); + attrStringOrder = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("L=local, ST=NJ, O=ATT, CN=Name, C=USA")); + attrStringDottedDecimalOID = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2.5.4.3=A. N. Other")); + + attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_X500NAME_FROM_STRING; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_X500NAME_FROM_STRING, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_X500NAME.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrString1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + X500Principal resValue = (X500Principal)res.getValue().getValue(); + assertEquals(new X500Principal("CN=Name, L=local, ST=NJ, O=ATT, C=USA"), resValue); + + // no comma between components => next attribute/value is included as part of first value + arguments.clear(); + arguments.add(attrStringNoComma); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (X500Principal)res.getValue().getValue(); + assertEquals(new X500Principal("CN=Name, L=local ST=NJ, O=ATT, C=USA"), resValue); + + // nothing in name (fail) + arguments.clear(); + arguments.add(attrStringEmpty); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (X500Principal)res.getValue().getValue(); + assertEquals(new X500Principal(""), resValue); + + // type value with no = + arguments.clear(); + arguments.add(attrStringNoValue); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (X500Principal)res.getValue().getValue(); + assertEquals(new X500Principal("CN=Name, L=, ST=NJ, O=ATT, C=USA"), resValue); + + // different order + arguments.clear(); + arguments.add(attrStringOrder); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (X500Principal)res.getValue().getValue(); + assertNotEquals(new X500Principal("CN=Name, L=local, ST=NJ, O=ATT, C=USA"), resValue); + + // dotted-decimal name with numbers + arguments.clear(); + arguments.add(attrStringDottedDecimalOID); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (X500Principal)res.getValue().getValue(); + assertEquals(new X500Principal("2.5.4.3=A. N. Other"), resValue); + + + + // bad value + arguments.clear(); + arguments.add(attrStringBadValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:x500Name-from-string improperly specified input name: not valid obj value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:x500Name-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + @Test + public void testString_from_x500Name() { + FunctionArgumentAttributeValue attrObj1 = null; + FunctionArgumentAttributeValue attrStringBadType = null; + String objValueString = "CN=Name, L=local, ST=NJ, O=ATT, C=USA"; + try { + attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_X500NAME.createAttributeValue(objValueString)); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_X500NAME; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_FROM_X500NAME, fd.getId()); + assertEquals(DataTypes.DT_X500NAME.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrObj1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(objValueString, res.getValue().getValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-from-x500Name Expected data type 'x500Name' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + + /** + * RFC822Name + */ + @Test + public void testRFC822Name_from_string() { + FunctionArgumentAttributeValue attrString1 = null; + FunctionArgumentAttributeValue attrStringCapsDomain = null; + FunctionArgumentAttributeValue attrStringCapsLocal = null; + FunctionArgumentAttributeValue attrStringMissingAt = null; + FunctionArgumentAttributeValue attrStringMissingLocal = null; + FunctionArgumentAttributeValue attrStringMissingDomain = null; + FunctionArgumentAttributeValue attrStringEmpty = null; + FunctionArgumentAttributeValue attrStringBadValue = null; + FunctionArgumentAttributeValue attrStringBadType = null; + try { + attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("local@Domain")); + attrStringCapsDomain = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("local@DOMAIN")); + attrStringCapsLocal = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("LOCAL@Domain")); + attrStringMissingAt = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("localDomain")); + attrStringMissingLocal = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("@Domain")); + attrStringMissingDomain = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("local@")); + attrStringEmpty = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); + + attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_RFC822NAME_FROM_STRING; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_RFC822NAME_FROM_STRING, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_RFC822NAME.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrString1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + RFC822Name resValue = (RFC822Name)res.getValue().getValue(); + assertEquals(new RFC822Name("local", "domain"), resValue); + + // caps domain + arguments.clear(); + arguments.add(attrStringCapsDomain); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (RFC822Name)res.getValue().getValue(); + assertEquals(new RFC822Name("local", "domain"), resValue); + + // caps local + arguments.clear(); + arguments.add(attrStringCapsLocal); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (RFC822Name)res.getValue().getValue(); + assertNotEquals(new RFC822Name("local", "domain"), resValue); + + // missing at + arguments.clear(); + arguments.add(attrStringMissingAt); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:rfc822Name-from-string Invalid RFC822Name \"localDomain\": missing local part", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // missing local + arguments.clear(); + arguments.add(attrStringMissingLocal); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:rfc822Name-from-string Invalid RFC822Name \"@Domain\": empty parts", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // missing domain + arguments.clear(); + arguments.add(attrStringMissingDomain); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:rfc822Name-from-string Invalid RFC822Name \"local@\": empty parts", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // empty + arguments.clear(); + arguments.add(attrStringEmpty); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:rfc822Name-from-string Invalid RFC822Name \"\": missing local part", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // bad value + arguments.clear(); + arguments.add(attrStringBadValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:rfc822Name-from-string Invalid RFC822Name \"not valid obj value\": missing local part", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:rfc822Name-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + @Test + public void testString_from_rfc822Name() { + FunctionArgumentAttributeValue attrObj1 = null; + FunctionArgumentAttributeValue attrStringBadType = null; + String objValueString = "local@DOMAIN"; + try { + attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_RFC822NAME.createAttributeValue(objValueString)); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_RFC822NAME; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_FROM_RFC822NAME, fd.getId()); + assertEquals(DataTypes.DT_RFC822NAME.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrObj1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals("local@domain", res.getValue().getValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-from-rfc822Name Expected data type 'rfc822Name' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + + /** + * IPAddress + */ + @Test + public void testIPAddress_from_string() { + FunctionArgumentAttributeValue attrString1 = null; + FunctionArgumentAttributeValue attrStringFull = null; + FunctionArgumentAttributeValue attrStringMissingElement = null; + FunctionArgumentAttributeValue attrStringTooManyElement = null; + FunctionArgumentAttributeValue attrStringIllegalElement = null; + FunctionArgumentAttributeValue attrStringOutOfOrder = null; + + FunctionArgumentAttributeValue attrStringMask = null; + FunctionArgumentAttributeValue attrStringMissingMaskElement = null; + FunctionArgumentAttributeValue attrStringTooManyMaskElement = null; + FunctionArgumentAttributeValue attrStringIllegalMaskElement = null; + FunctionArgumentAttributeValue attrStringMaskNoValue = null; + + FunctionArgumentAttributeValue attrStringMinusPort = null; + FunctionArgumentAttributeValue attrStringPortMinus = null; + FunctionArgumentAttributeValue attrStringPortPort = null; + FunctionArgumentAttributeValue attrStringNoPort = null; + FunctionArgumentAttributeValue attrStringBadPort = null; + FunctionArgumentAttributeValue attrStringTooManyPorts = null; + FunctionArgumentAttributeValue attrStringBadValue = null; + FunctionArgumentAttributeValue attrStringBadType = null; + + // set up for v4 address tests - this setup and the tests are repeated for V6 + short[] addrShorts= {123, 134, 156, 255 }; + short[] addrMaskShorts= {255, 255, 255, 255 }; + try { + attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255")); + attrStringFull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255/255.255.255.255:123-456")); + attrStringMissingElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.255")); + attrStringTooManyElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.255.111.222")); + attrStringIllegalElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.256.255")); + attrStringOutOfOrder = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.256.255:123-456/255.255.255.255")); + + attrStringMask = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255/255.255.255.255")); + attrStringMissingMaskElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255/123.134.255")); + attrStringTooManyMaskElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255/122.134.155.111.222")); + attrStringIllegalMaskElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255/123.134.256.255")); + attrStringMaskNoValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255/")); + // optional mask + // "/" with no mask (fail) + + attrStringMinusPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255:-123")); + attrStringPortMinus = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255:123-")); + attrStringPortPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255:1234567-432")); + attrStringNoPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255:")); + attrStringBadPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255:12.34")); + attrStringTooManyPorts = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("123.134.156.255:-123-456")); + + + + attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_IPADDRESS_FROM_STRING; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_IPADDRESS_FROM_STRING, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_IPADDRESS.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrString1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + IPAddress resValue = (IPAddress)res.getValue().getValue(); + assertEquals(new IPv4Address(addrShorts, null, null), resValue); + + // fully-loaded address + arguments.clear(); + arguments.add(attrStringFull); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (IPAddress)res.getValue().getValue(); + try { + assertEquals(new IPv4Address(addrShorts, addrMaskShorts, PortRange.newInstance("123-456")), resValue); + } catch (Exception e) { + fail("port error e="+e); + } + + // missing element + arguments.clear(); + arguments.add(attrStringMissingElement); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"123.134.255\": invalid address", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many elements + arguments.clear(); + arguments.add(attrStringTooManyElement); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"123.134.255.111.222\": invalid address", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // illegal element + arguments.clear(); + arguments.add(attrStringIllegalElement); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"123.134.256.255\": invalid octet: \"256", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // Out of order + arguments.clear(); + arguments.add(attrStringOutOfOrder); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"123.134.256.255:123-456/255.255.255.255\": out of order components", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // simple mask + arguments.clear(); + arguments.add(attrStringMask); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (IPAddress)res.getValue().getValue(); + try { + assertEquals(new IPv4Address(addrShorts, addrMaskShorts, null), resValue); + } catch (Exception e) { + fail("port error e="+e); + } + + // missing mask element + arguments.clear(); + arguments.add(attrStringMissingMaskElement); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"123.134.255\": invalid address", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many mask elements + arguments.clear(); + arguments.add(attrStringTooManyMaskElement); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"122.134.155.111.222\": invalid address", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // illegal Mask element + arguments.clear(); + arguments.add(attrStringIllegalMaskElement); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"123.134.256.255\": invalid octet: \"256", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + //mask indicator without value + arguments.clear(); + arguments.add(attrStringMaskNoValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"\": invalid address", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // portrange (-port, port-, port-port) + arguments.clear(); + arguments.add(attrStringMinusPort); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (IPAddress)res.getValue().getValue(); + try { + assertEquals(new IPv4Address(addrShorts, null, PortRange.newInstance("-123")), resValue); + } catch (ParseException e) { + fail("port error e="+e); + } + + arguments.clear(); + arguments.add(attrStringPortMinus); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (IPAddress)res.getValue().getValue(); + try { + assertEquals(new IPv4Address(addrShorts, null, PortRange.newInstance("123-")), resValue); + } catch (ParseException e) { + fail("port error e="+e); + } + + arguments.clear(); + arguments.add(attrStringPortPort); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (IPAddress)res.getValue().getValue(); + try { + assertEquals(new IPv4Address(addrShorts, null, PortRange.newInstance("1234567-432")), resValue); + } catch (ParseException e) { + fail("port error e="+e); + } + + // ":" without port + arguments.clear(); + arguments.add(attrStringNoPort); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv4 address string \"123.134.156.255:\": no portrange given after ':'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // bad port number + arguments.clear(); + arguments.add(attrStringBadPort); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid PortRange \"12.34\": invalid port number", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad port range + arguments.clear(); + arguments.add(attrStringTooManyPorts); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid PortRange \"-123-456\": too many ranges", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // bad value + arguments.clear(); + arguments.add(attrStringBadValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Unknown IPAddress type for \"not valid obj value\"", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // + // V6 IP Addresses + // + + // reset the variable for IPv6 tests + FunctionArgumentAttributeValue attrStringAlternateFull = null; + FunctionArgumentAttributeValue attrStringEmptyElement = null; + FunctionArgumentAttributeValue attrString2xEmptyElement = null; + FunctionArgumentAttributeValue attrStringNoStartBracket = null; + FunctionArgumentAttributeValue attrStringNoEndBracket = null; + short[] addrv6Shorts = {(short)0x2001, (short)0xdb8, (short)0x85a3, (short)0x0, (short)0x0, (short)0x8a2e, (short)0x370, (short)0x1}; + Short prefix = new Short((short) 121); + try { + attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]")); + attrStringFull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1/121]:123-456")); + attrStringAlternateFull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]/121:123-456")); + attrStringEmptyElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3::8a2e:370:1]")); + attrString2xEmptyElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3::8a2e::1]")); + attrStringNoStartBracket = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("2002:db8:85a3::8a2e::1]")); + attrStringNoEndBracket = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3::8a2e::1")); + + attrStringMissingElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:1]")); + attrStringTooManyElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1:123]")); + attrStringIllegalElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:mnop:85a3:0:0:8a2e:370:1]")); + attrStringOutOfOrder = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:mnop:85a3:0:0:8a2e:370:1:123-456/121]")); + + attrStringMask = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1/21]")); + attrStringIllegalMaskElement = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1/130]")); + attrStringMaskNoValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1/]")); + + attrStringMinusPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]:-123")); + attrStringPortMinus = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]:123-")); + attrStringPortPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]:1234567-432")); + attrStringNoPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]:")); + attrStringBadPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]:12.34")); + attrStringTooManyPorts = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("[2001:db8:85a3:0:0:8a2e:370:1]:-123-456")); + + attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + + // test normal + arguments.clear(); + arguments.add(attrString1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (IPAddress)res.getValue().getValue(); + assertEquals(new IPv6Address(addrv6Shorts, null, null), resValue); + + // fully-loaded address - "prefix" is inside the brackets (not clear if this is correct) + arguments.clear(); + arguments.add(attrStringFull); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (IPAddress)res.getValue().getValue(); + try { + assertEquals(new IPv6Address(addrv6Shorts, new Short(prefix), PortRange.newInstance("123-456")), resValue); + } catch (Exception e) { + fail("port error e="+e); + } + + // Alternate way of identifying "prefix" - outside the brackets + arguments.clear(); + arguments.add(attrStringAlternateFull); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (IPAddress)res.getValue().getValue(); + try { + assertEquals(new IPv6Address(addrv6Shorts, prefix, PortRange.newInstance("123-456")), resValue); + } catch (Exception e) { + fail("port error e="+e); + } + + + // consecutive zero elements removed + arguments.clear(); + arguments.add(attrStringEmptyElement); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (IPAddress)res.getValue().getValue(); + try { + assertEquals(new IPv6Address(addrv6Shorts, prefix, null), resValue); + } catch (Exception e) { + fail("port error e="+e); + } + + // consecutive zero elements removed in two locations (no-no) + arguments.clear(); + arguments.add(attrString2xEmptyElement); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv6Address string \"2001:db8:85a3::8a2e::1\": multiple zero runs", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // address must have [] on it + arguments.clear(); + arguments.add(attrStringNoStartBracket); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv6Address string \"2002:db8:85a3::8a2e::1]\": missing opening bracket", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrStringNoEndBracket); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv6Address string \"[2001:db8:85a3::8a2e::1\": missing closing bracket", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // missing element + arguments.clear(); + arguments.add(attrStringMissingElement); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv6Address string \"2001:db8:85a3:0:0:8a2e:1\": not enough address fields", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many elements + arguments.clear(); + arguments.add(attrStringTooManyElement); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv6Address string \"2001:db8:85a3:0:0:8a2e:370:1:123\"", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // illegal element + arguments.clear(); + arguments.add(attrStringIllegalElement); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv6Address component \"mnop\": invalid hex", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // Out of order + arguments.clear(); + arguments.add(attrStringOutOfOrder); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv6Address string \"2001:mnop:85a3:0:0:8a2e:370:1:123-456\"", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // simple mask + arguments.clear(); + arguments.add(attrStringMask); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (IPAddress)res.getValue().getValue(); + try { + assertEquals(new IPv6Address(addrv6Shorts, prefix, null), resValue); + } catch (Exception e) { + fail("port error e="+e); + } + + // illegal Mask element + arguments.clear(); + arguments.add(attrStringIllegalMaskElement); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid Ipv6Address string \"[2001:db8:85a3:0:0:8a2e:370:1/130]\": prefix is larger than 128", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + //mask indicator without value + arguments.clear(); + arguments.add(attrStringMaskNoValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid Ipv6Address string \"[2001:db8:85a3:0:0:8a2e:370:1/]\": prefix designation without value", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // portrange (-port, port-, port-port) + arguments.clear(); + arguments.add(attrStringMinusPort); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (IPAddress)res.getValue().getValue(); + try { + assertEquals(new IPv6Address(addrv6Shorts, null, PortRange.newInstance("-123")), resValue); + } catch (ParseException e) { + fail("port error e="+e); + } + + arguments.clear(); + arguments.add(attrStringPortMinus); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (IPAddress)res.getValue().getValue(); + try { + assertEquals(new IPv6Address(addrv6Shorts, null, PortRange.newInstance("123-")), resValue); + } catch (ParseException e) { + fail("port error e="+e); + } + + arguments.clear(); + arguments.add(attrStringPortPort); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (IPAddress)res.getValue().getValue(); + try { + assertEquals(new IPv6Address(addrv6Shorts, null, PortRange.newInstance("1234567-432")), resValue); + } catch (ParseException e) { + fail("port error e="+e); + } + + // ":" without port + arguments.clear(); + arguments.add(attrStringNoPort); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid IPv6 address string \"[2001:db8:85a3:0:0:8a2e:370:1]:\": no portrange given after ':'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // bad port number + arguments.clear(); + arguments.add(attrStringBadPort); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid PortRange \"12.34\": invalid port number", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad port range + arguments.clear(); + arguments.add(attrStringTooManyPorts); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:ipAddress-from-string Invalid PortRange \"-123-456\": too many ranges", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + + + + } + + @Test + public void testString_from_ipAddress() { + FunctionArgumentAttributeValue attrObj1 = null; + FunctionArgumentAttributeValue attrObjV6 = null; + FunctionArgumentAttributeValue attrStringBadType = null; + String objValueString = "123.145.255.255"; + String objValueStringV6 = "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]"; + try { + attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_IPADDRESS.createAttributeValue(objValueString)); + attrObjV6 = new FunctionArgumentAttributeValue(DataTypes.DT_IPADDRESS.createAttributeValue(objValueStringV6)); + + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_IPADDRESS; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_FROM_IPADDRESS, fd.getId()); + assertEquals(DataTypes.DT_IPADDRESS.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal V4 + arguments.clear(); + arguments.add(attrObj1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(objValueString, res.getValue().getValue()); + + // test normal V6 + arguments.clear(); + arguments.add(attrObjV6); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(objValueStringV6.toLowerCase(), res.getValue().getValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-from-ipAddress Expected data type 'ipAddress' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + + + + + + + + /** + * RFC2396DomainName + */ + @Test + public void testRFC2396DomainName_from_string() { + FunctionArgumentAttributeValue attrString1 = null; + FunctionArgumentAttributeValue attrString2 = null; + FunctionArgumentAttributeValue attrStringMinusPort = null; + FunctionArgumentAttributeValue attrStringPortMinus = null; + FunctionArgumentAttributeValue attrStringPortPort = null; + FunctionArgumentAttributeValue attrStringNoPort = null; + FunctionArgumentAttributeValue attrStringBadPort = null; + FunctionArgumentAttributeValue attrStringTooManyPorts = null; + + FunctionArgumentAttributeValue attrStringBadValue = null; + FunctionArgumentAttributeValue attrStringBadType = null; + try { + attrString1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host")); + attrString2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host.host")); + + attrStringMinusPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host.host:-123")); + attrStringPortMinus = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host.host:123-")); + attrStringPortPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host.host:1234567-432")); + attrStringNoPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host.host:")); + attrStringBadPort = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host.host:12.34")); + attrStringTooManyPorts = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("host.host:-123-456")); + + attrStringBadValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("not valid obj value")); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_DNSNAME_FROM_STRING; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_DNSNAME_FROM_STRING, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_DNSNAME.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrString1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + RFC2396DomainName resValue = (RFC2396DomainName)res.getValue().getValue(); + assertEquals(new RFC2396DomainName("host", null), resValue); + + arguments.clear(); + arguments.add(attrString2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (RFC2396DomainName)res.getValue().getValue(); + assertEquals(new RFC2396DomainName("host.host", null), resValue); + + + // portrange (-port, port-, port-port) + arguments.clear(); + arguments.add(attrStringMinusPort); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (RFC2396DomainName)res.getValue().getValue(); + try { + assertEquals(new RFC2396DomainName("host.host", PortRange.newInstance("-123")), resValue); + } catch (ParseException e) { + fail("port error e="+e); + } + + arguments.clear(); + arguments.add(attrStringPortMinus); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (RFC2396DomainName)res.getValue().getValue(); + try { + assertEquals(new RFC2396DomainName("host.host", PortRange.newInstance("123-")), resValue); + } catch (ParseException e) { + fail("port error e="+e); + } + + arguments.clear(); + arguments.add(attrStringPortPort); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (RFC2396DomainName)res.getValue().getValue(); + try { + assertEquals(new RFC2396DomainName("host.host", PortRange.newInstance("1234567-432")), resValue); + } catch (ParseException e) { + fail("port error e="+e); + } + + // ":" without port + arguments.clear(); + arguments.add(attrStringNoPort); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dnsName-from-string Invalid RFC 2396 port range \"host.host:\": no port numbers", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad port number + arguments.clear(); + arguments.add(attrStringBadPort); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dnsName-from-string Invalid RFC 2396 port range \"12.34\"", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad port range + arguments.clear(); + arguments.add(attrStringTooManyPorts); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dnsName-from-string Invalid RFC 2396 port range \"-123-456\"", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad value + arguments.clear(); + arguments.add(attrStringBadValue); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dnsName-from-string Invalid RFC 2396 host name \"not valid obj value\"", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:dnsName-from-string Expected data type 'string' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + @Test + public void testString_from_dnsName() { + FunctionArgumentAttributeValue attrObj1 = null; + FunctionArgumentAttributeValue attrStringBadType = null; + String objValueString = "someName.com"; + try { + attrObj1 = new FunctionArgumentAttributeValue(DataTypes.DT_DNSNAME.createAttributeValue(objValueString)); + attrStringBadType = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(123)); + + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringConversion fd = (FunctionDefinitionStringConversion) StdFunctions.FD_STRING_FROM_DNSNAME; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_FROM_DNSNAME, fd.getId()); + assertEquals(DataTypes.DT_DNSNAME.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + // test normal + arguments.clear(); + arguments.add(attrObj1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(objValueString, res.getValue().getValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrStringBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-from-dnsName Expected data type 'dnsName' saw 'integer' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + } + + + + + + + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringEqualIgnoreCaseTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringEqualIgnoreCaseTest.java new file mode 100644 index 000000000..9c5c8a1e7 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringEqualIgnoreCaseTest.java @@ -0,0 +1,129 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Only one function to test here. Code copy/pasted from FunctionDefinitionEqualityTest + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * In the first implementation of XACML we had separate files for each XACML Function. + * This release combines multiple Functions in fewer files to minimize code duplication. + * This file supports the following XACML codes: + * string-equal-ignore-case + * + * + */ +public class FunctionDefinitionStringEqualIgnoreCaseTest { + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + FunctionArgumentAttributeValue stringAttr1 = null; + FunctionArgumentAttributeValue stringAttr2 = null; + FunctionArgumentAttributeValue stringAttr3 = null; + FunctionArgumentAttributeValue stringAttr4 = null; + + FunctionArgumentAttributeValue intAttr1 = null; + + public FunctionDefinitionStringEqualIgnoreCaseTest() { + try { + stringAttr1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc")); + stringAttr2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("abc")); + stringAttr3 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("ABC")); + stringAttr4 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("def")); + intAttr1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + } + + + /** + * String match even when Case is different + */ + @Test + public void testFunctionDefinitionStringEqualIgnoreCase() { + + FunctionDefinitionEquality fd = (FunctionDefinitionEquality) StdFunctions.FD_STRING_EQUAL_IGNORE_CASE; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_EQUAL_IGNORE_CASE, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + + + // test normal equals and non-equals + // check "abc" with "abc" + arguments.add(stringAttr1); + arguments.add(stringAttr2); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // check "abc" with "ABC" (should be same) + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(stringAttr3); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // test bad args data types? Not needed? + arguments.clear(); + arguments.add(stringAttr1); + arguments.add(intAttr1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + + +//TODO - null in either first or 2nd arg => NullPointerException + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringFunctionsTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringFunctionsTest.java new file mode 100644 index 000000000..c6cba9f67 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringFunctionsTest.java @@ -0,0 +1,1497 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionStringFunctionsTest { + + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + ExpressionResult res; + + + @Test + public void testConcatenate() { + String v1 = new String("abc"); + String v2 = new String("def"); + + FunctionArgumentAttributeValue attrV1 = null; + FunctionArgumentAttributeValue attrV2 = null; + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrBlank = null; + FunctionArgumentAttributeValue attrInteger = null; + try { + attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); + attrV2 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v2)); + attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_STRING_CONCATENATE; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_CONCATENATE, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // match + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrV2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + String resValue = (String)res.getValue().getValue(); + assertEquals(v1 + v2, resValue); + + // empty non-null first arg + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrV2); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + resValue = (String)res.getValue().getValue(); + assertEquals(v2, resValue); + + // empty non-null second arg + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + resValue = (String)res.getValue().getValue(); + assertEquals(v1, resValue); + + // two blanks + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + resValue = (String)res.getValue().getValue(); + assertEquals("", resValue); + + // null firat arg + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-concatenate Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // null second arg + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-concatenate Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrInteger); + arguments.add(attrV2); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-concatenate Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-concatenate Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + @Test + public void testStringStartsWith() { + String v1 = new String("abc"); + String bigger = new String("abc some string"); + String biggerNoMatch = new String(" abc some string"); + String caps = new String("AbC"); + + FunctionArgumentAttributeValue attrV1 = null; + FunctionArgumentAttributeValue attrBigger = null; + FunctionArgumentAttributeValue attrBiggerNoMatch = null; + FunctionArgumentAttributeValue attrCaps = null; + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrBlank = null; + FunctionArgumentAttributeValue attrInteger = null; + try { + attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); + attrBigger = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(bigger)); + attrBiggerNoMatch = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(biggerNoMatch)); + attrCaps = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(caps)); + attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_STRING_STARTS_WITH; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_STARTS_WITH, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // match + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // no match + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBiggerNoMatch); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // caps no match + arguments.clear(); + arguments.add(attrCaps); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // bigger on the inside + arguments.clear(); + arguments.add(attrBigger); + arguments.add(attrV1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // empty non-null first arg + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // empty non-null second arg + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // two blanks + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // null firat arg + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-starts-with Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-starts-with Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // illegal arg type + arguments.clear(); + arguments.add(attrInteger); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-starts-with Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + @Test + public void testAnyuriStartsWith() { + + + FunctionArgumentAttributeValue attrV1 = null; + FunctionArgumentAttributeValue attrBigger = null; + FunctionArgumentAttributeValue attrBiggerNoMatch = null; + FunctionArgumentAttributeValue attrCaps = null; + FunctionArgumentAttributeValue attrBigString = null; + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrBlankString = null; + FunctionArgumentAttributeValue attrBlankURI = null; + FunctionArgumentAttributeValue attrInteger = null; + try { + String v1 = new String("abc"); + URI bigger = new URI("abc.some.string"); + URI biggerNoMatch = new URI("Zabc.some.string"); + String caps = new String("AbC"); + String bigString = "thisIsSomeReallyBigStringToMatch"; + + attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); + attrBigger = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(bigger)); + attrBiggerNoMatch = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(biggerNoMatch)); + attrCaps = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(caps)); + attrBigString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(bigString)); + attrBlankString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); + attrBlankURI = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("")); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_ANYURI_STARTS_WITH; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_ANYURI_STARTS_WITH, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // match + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // no match + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBiggerNoMatch); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // caps no match + arguments.clear(); + arguments.add(attrCaps); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // bigger on the inside + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // empty non-null first arg + arguments.clear(); + arguments.add(attrBlankString); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // empty non-null second arg + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBlankURI); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + + // two blanks + arguments.clear(); + arguments.add(attrBlankString); + arguments.add(attrBlankURI); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // arguments reversed + arguments.clear(); + arguments.add(attrBigger); + arguments.add(attrV1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-starts-with Expected data type 'string' saw 'anyURI'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // null firat arg + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrBlankURI); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-starts-with Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-starts-with Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // illegal arg type + arguments.clear(); + arguments.add(attrInteger); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-starts-with Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + @Test + public void testStringEndsWith() { + String v1 = new String("abc"); + String bigger = new String("abc some string abc"); + String biggerNoMatch = new String(" abc some string abc "); + String caps = new String("AbC"); + + FunctionArgumentAttributeValue attrV1 = null; + FunctionArgumentAttributeValue attrBigger = null; + FunctionArgumentAttributeValue attrBiggerNoMatch = null; + FunctionArgumentAttributeValue attrCaps = null; + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrBlank = null; + FunctionArgumentAttributeValue attrInteger = null; + try { + attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); + attrBigger = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(bigger)); + attrBiggerNoMatch = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(biggerNoMatch)); + attrCaps = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(caps)); + attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_STRING_ENDS_WITH; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_ENDS_WITH, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // match + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // no match + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBiggerNoMatch); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // caps no match + arguments.clear(); + arguments.add(attrCaps); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // bigger on the inside + arguments.clear(); + arguments.add(attrBigger); + arguments.add(attrV1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // empty non-null first arg + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // empty non-null second arg + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // two blanks + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // null firat arg + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-ends-with Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-ends-with Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // illegal arg type + arguments.clear(); + arguments.add(attrInteger); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-ends-with Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + @Test + public void testAnyuriEndsWith() { + + + FunctionArgumentAttributeValue attrV1 = null; + FunctionArgumentAttributeValue attrBigger = null; + FunctionArgumentAttributeValue attrBiggerNoMatch = null; + FunctionArgumentAttributeValue attrCaps = null; + FunctionArgumentAttributeValue attrBigString = null; + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrBlankString = null; + FunctionArgumentAttributeValue attrBlankURI = null; + FunctionArgumentAttributeValue attrInteger = null; + try { + String v1 = new String("abc"); + URI bigger = new URI("abc.some.stringabc"); + URI biggerNoMatch = new URI("Zabc.some.stringabcZ"); + String caps = new String("AbC"); + String bigString = "thisIsSomeReallyBigStringToMatch"; + + attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); + attrBigger = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(bigger)); + attrBiggerNoMatch = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(biggerNoMatch)); + attrCaps = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(caps)); + attrBigString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(bigString)); + attrBlankString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); + attrBlankURI = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("")); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_ANYURI_ENDS_WITH; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_ANYURI_ENDS_WITH, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // match + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // no match + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBiggerNoMatch); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // caps no match + arguments.clear(); + arguments.add(attrCaps); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // bigger on the inside + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // empty non-null first arg + arguments.clear(); + arguments.add(attrBlankString); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // empty non-null second arg + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBlankURI); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + + // two blanks + arguments.clear(); + arguments.add(attrBlankString); + arguments.add(attrBlankURI); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // arguments reversed + arguments.clear(); + arguments.add(attrBigger); + arguments.add(attrV1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-ends-with Expected data type 'string' saw 'anyURI'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // null firat arg + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrBlankURI); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-ends-with Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-ends-with Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // illegal arg type + arguments.clear(); + arguments.add(attrInteger); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-ends-with Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + @Test + public void testStringSubstring() { + String bigString = new String("abc some string abc"); + + FunctionArgumentAttributeValue attrBigString = null; + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrBlank = null; + FunctionArgumentAttributeValue attrDouble = null; + + FunctionArgumentAttributeValue attrInteger0 = null; + FunctionArgumentAttributeValue attrInteger1 = null; + FunctionArgumentAttributeValue attrIntegerM1 = null; + FunctionArgumentAttributeValue attrInteger8 = null; + FunctionArgumentAttributeValue attrInteger19 = null; + FunctionArgumentAttributeValue attrInteger20 = null; + + + + try { + attrBigString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(bigString)); + attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); + attrInteger0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); + attrInteger1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); + attrIntegerM1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(-1)); + attrInteger8 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(8)); + attrInteger19 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(19)); + attrInteger20 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(20)); + attrDouble = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(123.4)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_STRING_SUBSTRING; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_SUBSTRING, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // match + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrInteger1); + arguments.add(attrInteger8); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + String resValue = (String)res.getValue().getValue(); + assertEquals("bc some", resValue); + + // edge: start + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrInteger0); + arguments.add(attrInteger8); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + resValue = (String)res.getValue().getValue(); + assertEquals("abc some", resValue); + + // edge: end + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrInteger8); + arguments.add(attrInteger19); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + resValue = (String)res.getValue().getValue(); + assertEquals(" string abc", resValue); + + // from index to end of string + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrInteger8); + arguments.add(attrIntegerM1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + resValue = (String)res.getValue().getValue(); + assertEquals(" string abc", resValue); + + // first index too low + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrIntegerM1); + arguments.add(attrInteger8); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-substring Start point '-1' out of range 0-19 for string='abc some string abc'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // second index too big + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrInteger8); + arguments.add(attrInteger20); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-substring End point '20' out of range 0-19 for string='abc some string abc'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // indexes reversed + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrInteger8); + arguments.add(attrInteger1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-substring End point '1' less than start point 'null' for string='abc some string abc'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // indexes the same + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrInteger8); + arguments.add(attrInteger8); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + resValue = (String)res.getValue().getValue(); + assertEquals("", resValue); + + // blank string with indexes both 0 + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrInteger0); + arguments.add(attrInteger0); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + resValue = (String)res.getValue().getValue(); + assertEquals("", resValue); + + // non-string first attribute + arguments.clear(); + arguments.add(attrDouble); + arguments.add(attrInteger8); + arguments.add(attrInteger1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-substring Expected data type 'string' saw 'double'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // non-integer 2nd attr + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrDouble); + arguments.add(attrInteger1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-substring Expected data type 'integer' saw 'double'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // non-integer 3rd attr + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrInteger8); + arguments.add(attrDouble); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-substring Expected data type 'integer' saw 'double'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // 4 args + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrInteger8); + arguments.add(attrInteger1); + arguments.add(attrInteger1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-substring Expected 3 arguments, got 4", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // 2 args + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrInteger8); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-substring Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null 1st arg + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrInteger8); + arguments.add(attrInteger1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-substring Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // null 2nd arg + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrNull); + arguments.add(attrInteger1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-substring Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + } + + + + + @Test + public void testAnyURISubstring() { + String bigString = new String("http://company.com:8080/this/is/some/long/uri"); + + FunctionArgumentAttributeValue attrURI = null; + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrBlank = null; + FunctionArgumentAttributeValue attrDouble = null; + + FunctionArgumentAttributeValue attrInteger0 = null; + FunctionArgumentAttributeValue attrInteger1 = null; + FunctionArgumentAttributeValue attrIntegerM1 = null; + FunctionArgumentAttributeValue attrInteger8 = null; + FunctionArgumentAttributeValue attrInteger45 = null; + FunctionArgumentAttributeValue attrInteger46 = null; + + + + try { + attrURI = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(bigString)); + attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("")); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(null)); + attrInteger0 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(0)); + attrInteger1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1)); + attrIntegerM1 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(-1)); + attrInteger8 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(8)); + attrInteger45 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(45)); + attrInteger46 = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(46)); + attrDouble = new FunctionArgumentAttributeValue(DataTypes.DT_DOUBLE.createAttributeValue(123.4)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_ANYURI_SUBSTRING; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_ANYURI_SUBSTRING, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // match + arguments.clear(); + arguments.add(attrURI); + arguments.add(attrInteger1); + arguments.add(attrInteger8); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + String resValue = (String)res.getValue().getValue(); + assertEquals("ttp://c", resValue); + + // edge: start + arguments.clear(); + arguments.add(attrURI); + arguments.add(attrInteger0); + arguments.add(attrInteger8); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + resValue = (String)res.getValue().getValue(); + assertEquals("http://c", resValue); + + // edge: end + arguments.clear(); + arguments.add(attrURI); + arguments.add(attrInteger8); + arguments.add(attrInteger45); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + resValue = (String)res.getValue().getValue(); + assertEquals("ompany.com:8080/this/is/some/long/uri", resValue); + + // from index to end of string + arguments.clear(); + arguments.add(attrURI); + arguments.add(attrInteger8); + arguments.add(attrIntegerM1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + resValue = (String)res.getValue().getValue(); + assertEquals("ompany.com:8080/this/is/some/long/uri", resValue); + + // first index too low + arguments.clear(); + arguments.add(attrURI); + arguments.add(attrIntegerM1); + arguments.add(attrInteger8); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-substring Start point '-1' out of range 0-45 for string='http://company.com:8080/this/is/some/long/uri'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // second index too big + arguments.clear(); + arguments.add(attrURI); + arguments.add(attrInteger8); + arguments.add(attrInteger46); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-substring End point '46' out of range 0-45 for string='http://company.com:8080/this/is/some/long/uri'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // indexes reversed + arguments.clear(); + arguments.add(attrURI); + arguments.add(attrInteger8); + arguments.add(attrInteger1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-substring End point '1' less than start point 'null' for string='http://company.com:8080/this/is/some/long/uri'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // indexes the same + arguments.clear(); + arguments.add(attrURI); + arguments.add(attrInteger8); + arguments.add(attrInteger8); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + resValue = (String)res.getValue().getValue(); + assertEquals("", resValue); + + // blank string with indexes both 0 + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrInteger0); + arguments.add(attrInteger0); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.String.class, res.getValue().getValue().getClass()); + resValue = (String)res.getValue().getValue(); + assertEquals("", resValue); + + // non-string first attribute + arguments.clear(); + arguments.add(attrDouble); + arguments.add(attrInteger8); + arguments.add(attrInteger1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-substring Expected data type 'anyURI' saw 'double'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // non-integer 2nd attr + arguments.clear(); + arguments.add(attrURI); + arguments.add(attrDouble); + arguments.add(attrInteger1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-substring Expected data type 'integer' saw 'double'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // non-integer 3rd attr + arguments.clear(); + arguments.add(attrURI); + arguments.add(attrInteger8); + arguments.add(attrDouble); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-substring Expected data type 'integer' saw 'double'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // 4 args + arguments.clear(); + arguments.add(attrURI); + arguments.add(attrInteger8); + arguments.add(attrInteger1); + arguments.add(attrInteger1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-substring Expected 3 arguments, got 4", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // 2 args + arguments.clear(); + arguments.add(attrURI); + arguments.add(attrInteger8); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-substring Expected 3 arguments, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null 1st arg + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrInteger8); + arguments.add(attrInteger1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-substring Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // null 2nd arg + arguments.clear(); + arguments.add(attrURI); + arguments.add(attrNull); + arguments.add(attrInteger1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-substring Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + + + + + + + + + + + + + + + + + + @Test + public void testStringContains() { + String v1 = new String("abc"); + String bigger = new String("abc some string abc"); + String biggerNoMatch = new String(" abc some string abc "); + String caps = new String("AbC"); + + FunctionArgumentAttributeValue attrV1 = null; + FunctionArgumentAttributeValue attrBigger = null; + FunctionArgumentAttributeValue attrBiggerNoMatch = null; + FunctionArgumentAttributeValue attrCaps = null; + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrBlank = null; + FunctionArgumentAttributeValue attrInteger = null; + try { + attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); + attrBigger = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(bigger)); + attrBiggerNoMatch = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(biggerNoMatch)); + attrCaps = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(caps)); + attrBlank = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_STRING_CONTAINS; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_CONTAINS, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // match + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // no match + arguments.clear(); + arguments.add(attrBiggerNoMatch); + arguments.add(attrV1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // caps no match + arguments.clear(); + arguments.add(attrCaps); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // bigger on the inside + arguments.clear(); + arguments.add(attrBigger); + arguments.add(attrV1); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // empty non-null first arg + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // empty non-null second arg + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // two blanks + arguments.clear(); + arguments.add(attrBlank); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // null firat arg + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrBlank); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-contains Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-contains Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // illegal arg type + arguments.clear(); + arguments.add(attrInteger); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:string-contains Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + @Test + public void testAnyuriContains() { + + + FunctionArgumentAttributeValue attrV1 = null; + FunctionArgumentAttributeValue attrBigger = null; + FunctionArgumentAttributeValue attrBiggerNoMatch = null; + FunctionArgumentAttributeValue attrCaps = null; + FunctionArgumentAttributeValue attrBigString = null; + FunctionArgumentAttributeValue attrNull = null; + FunctionArgumentAttributeValue attrBlankString = null; + FunctionArgumentAttributeValue attrBlankURI = null; + FunctionArgumentAttributeValue attrInteger = null; + try { + String v1 = new String("abc"); + URI bigger = new URI("abc.some.stringabc"); + URI biggerNoMatch = new URI("Zabc.some.stringabcZ"); + String caps = new String("AbC"); + String bigString = "thisIsSomeReallyBigStringToMatch"; + + attrV1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(v1)); + attrBigger = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(bigger)); + attrBiggerNoMatch = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue(biggerNoMatch)); + attrCaps = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(caps)); + attrBigString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(bigString)); + attrBlankString = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); + attrBlankURI = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("")); + attrNull = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(null)); + attrInteger = new FunctionArgumentAttributeValue(DataTypes.DT_INTEGER.createAttributeValue(1234)); + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + FunctionDefinitionStringFunctions fd = (FunctionDefinitionStringFunctions) StdFunctions.FD_ANYURI_CONTAINS; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_ANYURI_CONTAINS, fd.getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // match + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // no match + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrBiggerNoMatch); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // caps no match + arguments.clear(); + arguments.add(attrCaps); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // bigger on the inside + arguments.clear(); + arguments.add(attrBigString); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + // empty non-null first arg + arguments.clear(); + arguments.add(attrBlankString); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // empty non-null second arg + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrBlankURI); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(false, resValue); + + + // two blanks + arguments.clear(); + arguments.add(attrBlankString); + arguments.add(attrBlankURI); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.lang.Boolean.class, res.getValue().getValue().getClass()); + resValue = (Boolean)res.getValue().getValue(); + assertEquals(true, resValue); + + // arguments reversed + arguments.clear(); + arguments.add(attrBigger); + arguments.add(attrV1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-contains Expected data type 'string' saw 'anyURI'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // null firat arg + arguments.clear(); + arguments.add(attrNull); + arguments.add(attrBlankURI); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-contains Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null second arg + arguments.clear(); + arguments.add(attrV1); + arguments.add(attrNull); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-contains Got null attribute", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // illegal arg type + arguments.clear(); + arguments.add(attrInteger); + arguments.add(attrBigger); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:anyURI-contains Expected data type 'string' saw 'integer'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringNormalizeTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringNormalizeTest.java new file mode 100644 index 000000000..2631be06b --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionStringNormalizeTest.java @@ -0,0 +1,118 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionStringNormalizeTest { + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + @Test + public void testString_normalize_space() { + String initialString = " First and last are whitespace "; + FunctionArgumentAttributeValue attr1 = null; + try { + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(initialString)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringNormalize fd = (FunctionDefinitionStringNormalize) StdFunctions.FD_STRING_NORMALIZE_SPACE; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_NORMALIZE_SPACE, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + + // test normal add + arguments.add(attr1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + String resValue = (String)res.getValue().getValue(); + assertEquals(initialString.length() - 4, resValue.length()); + assertTrue(initialString.trim().equals(resValue)); + } + + + @Test + public void testString_normalize_to_lower_case() { + String initialString = " First and last are whitespace "; + FunctionArgumentAttributeValue attr1 = null; + try { + attr1 = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue(initialString)); + } catch (Exception e) { + fail("creating attribute e="+ e); + } + + FunctionDefinitionStringNormalize fd = (FunctionDefinitionStringNormalize) StdFunctions.FD_STRING_NORMALIZE_TO_LOWER_CASE; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_STRING_NORMALIZE_TO_LOWER_CASE, fd.getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_STRING.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + + // test normal add + arguments.add(attr1); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + String resValue = (String)res.getValue().getValue(); + assertTrue(initialString.toLowerCase().equals(resValue)); + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionURIStringConcatenateTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionURIStringConcatenateTest.java new file mode 100644 index 000000000..63ae2072b --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionURIStringConcatenateTest.java @@ -0,0 +1,185 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import com.att.research.xacml.api.XACML2; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionURIStringConcatenateTest { + + /* + * THE FUNCTION BEING TESTED BY THIS CLASS IS DEPRECATED + * uri-string-concatenate has been deprecated in XACML 3.0 + */ + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList<>(); + + + @SuppressWarnings("deprecation") + @Test + public void testURI_string_concatenate() { + + // URI args + FunctionArgumentAttributeValue attrURI1 = null; + + + FunctionArgumentAttributeValue attrStrAbc = null; + FunctionArgumentAttributeValue attrStrSlashMno = null; + FunctionArgumentAttributeValue attrStrSlashInMiddle = null; + FunctionArgumentAttributeValue attrStrWithSpace = null; + + + try { + attrURI1 = new FunctionArgumentAttributeValue(DataTypes.DT_ANYURI.createAttributeValue("http://someplace")); + + + attrStrAbc = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("Abc")); + attrStrSlashMno = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("/Mno")); + attrStrSlashInMiddle = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("hij/pqr")); + attrStrWithSpace = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("x y z")); + + + } catch (Exception e) { + fail("creating attributes e="+ e); + } + + // deprecation marking in the following line is correct - this function IS deprecated but still valid for XACML 3.0 + FunctionDefinitionURIStringConcatenate fd = (FunctionDefinitionURIStringConcatenate) StdFunctions.FD_URI_STRING_CONCATENATE; + + // check identity and type of the thing created + assertEquals(XACML2.ID_FUNCTION_URI_STRING_CONCATENATE, fd.getId()); + assertEquals(DataTypes.DT_ANYURI.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + + + // add one string to uri + arguments.clear(); + arguments.add(attrURI1); + arguments.add(attrStrAbc); + ExpressionResult res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.net.URI.class, res.getValue().getValue().getClass()); + URI resValue = (URI)res.getValue().getValue(); + assertEquals("http://someplaceAbc", resValue.toString()); + + + // add 2 strings to uri + arguments.clear(); + arguments.add(attrURI1); + arguments.add(attrStrAbc); + arguments.add(attrStrSlashMno); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.net.URI.class, res.getValue().getValue().getClass()); + resValue = (URI)res.getValue().getValue(); + assertEquals("http://someplaceAbc/Mno", resValue.toString()); + + // slash in middle of string + arguments.clear(); + arguments.add(attrURI1); + arguments.add(attrStrSlashInMiddle); + arguments.add(attrStrSlashMno); + res = fd.evaluate(null, arguments); + assertTrue(res.isOk()); + assertEquals(java.net.URI.class, res.getValue().getValue().getClass()); + resValue = (URI)res.getValue().getValue(); + assertEquals("http://someplacehij/pqr/Mno", resValue.toString()); + + // create bad uri + arguments.clear(); + arguments.add(attrURI1); + arguments.add(attrStrWithSpace); + arguments.add(attrStrSlashMno); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:uri-string-concatenate Final string 'http://someplacex y z/Mno' not URI, Illegal character in authority at index 7: http://someplacex y z/Mno", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // no args + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:uri-string-concatenate Expected 2 or more arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // one arg + arguments.clear(); + arguments.add(attrURI1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:uri-string-concatenate Expected 2 or more arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // first arg not uri + arguments.clear(); + arguments.add(attrStrAbc); + arguments.add(attrURI1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:uri-string-concatenate Expected data type 'anyURI' saw 'string' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // 2nd arg not string + arguments.clear(); + arguments.add(attrURI1); + arguments.add(attrURI1); + res = fd.evaluate(null, arguments); + assertFalse(res.isOk()); + assertEquals("function:uri-string-concatenate Expected data type 'string' saw 'anyURI' at arg index 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionXPathTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionXPathTest.java new file mode 100644 index 000000000..b174c4205 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/FunctionDefinitionXPathTest.java @@ -0,0 +1,1127 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathFactory; + +import org.junit.Test; + +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdRequest; +import com.att.research.xacml.std.StdStatus; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacml.std.datatypes.XPathExpressionWrapper; +import com.att.research.xacml.std.dom.DOMRequest; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionArgumentAttributeValue; +import com.att.research.xacmlatt.pdp.std.StdEvaluationContext; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.*; + +/** + * Test of PDP Functions (See XACML core spec section A.3) + * + * TO RUN - use jUnit + * In Eclipse select this file or the enclosing directory, right-click and select Run As/JUnit Test + * + * + */ +public class FunctionDefinitionXPathTest { + + // + // Strings for the Request contents + // + + String reqStrMainStart = "" + + "" + + " " + + " " + + " Julius Hibbert" + + " " + + " " + + " This is IT! " + + " " + + " " + + " This is IT! " + + " " + + ""; + + String reqStrResourceStart = ""; + + String reqStrContentMdRecord = + " " + + "" + + "" + + "ABC Hospital" + + "Surgery" + + "" + + "" + + "Bart Simpson" + + "60" + + "male" + + "123456" + + "" + + "" + + "" + + "Gastric Cancer" + + "Hyper tension" + + "" + + "" + + "" + + "Well differentiated adeno carcinoma" + + "" + + "2000-10-05" + + "" + + "" + + " " + + " " + + ""; + String reqStrMalformedContent = + " " + + "" + + "" + + "ABC Hospital" + + "" + + ""; + String reqStrResourceEnd = " " + + " http://medico.com/record/patient/BartSimpson" + + " " + + " "; + String reqStrActionStart = ""; + + String reqStrActionEnd = "" + + "read" + + "" + + " "; + String reqStrEnvironmentStartEnd = " "; + String reqStrMainEnd = " "; + + + // combined strings for convenience + String reqStrMainResourceStart = reqStrMainStart + reqStrResourceStart; + String reqStrResourceAllEnd = reqStrResourceEnd + reqStrActionStart + reqStrActionEnd + reqStrEnvironmentStartEnd + reqStrMainEnd; + + + /* + * variables useful in the following tests + */ + List arguments = new ArrayList(); + + + + // Name Spaces used in the XML as part of these examples (copied from the Conformance tests) - needed for compiling XPaths + NamespaceContext nameSpaceContext = new NamespaceContext() { + @Override + public Iterator getPrefixes(String arg0) { return null;} + + @Override + public String getPrefix(String arg0) {return null;} + + @Override + public String getNamespaceURI(String arg0) { + if("md".equals(arg0)) { + return "http://www.medico.com/schemas/record"; + } else if ("xacml-context".equals(arg0)) { + return "urn:oasis:names:tc:xacml:3.0:context:schema:os"; + } else if ("xsi".equals(arg0)) { + return "http://www.w3.org/2001/XMLSchema-instance"; + } + return null; + } + }; + + + + // + // XPath Function Attributes available for use in tests (representing appropriate fragment of Policy) + // + + FunctionArgumentAttributeValue attrXnull = null; + FunctionArgumentAttributeValue attrXEmpty = null; + FunctionArgumentAttributeValue attrXNoCategory = null; + FunctionArgumentAttributeValue attrXNoValue = null; + FunctionArgumentAttributeValue attrXSlashSlashMdRecord = null; + FunctionArgumentAttributeValue attrXSlashSlashStar = null; + FunctionArgumentAttributeValue attrXSlashSlashMdName = null; + FunctionArgumentAttributeValue attrXSlashSlashMdMalignancy = null; + FunctionArgumentAttributeValue attrXNotInRequest = null; + FunctionArgumentAttributeValue attrXSlashSlashMdRecordSlashStar = null; + FunctionArgumentAttributeValue attrXMdPatientInfo = null; + + FunctionArgumentAttributeValue attrBadType = null; + + // String version of attrs for use in Deprecated functions + FunctionArgumentAttributeValue attrStrnull = null; + FunctionArgumentAttributeValue attrStrEmpty = null; + FunctionArgumentAttributeValue attrStrNoCategory = null; + FunctionArgumentAttributeValue attrStrNoValue = null; + FunctionArgumentAttributeValue attrStrSlashSlashMdRecord = null; + FunctionArgumentAttributeValue attrStrSlashSlashStar = null; + FunctionArgumentAttributeValue attrStrSlashSlashMdName = null; + FunctionArgumentAttributeValue attrStrSlashSlashMdMalignancy = null; + FunctionArgumentAttributeValue attrStrNotInRequest = null; + FunctionArgumentAttributeValue attrStrSlashSlashMdRecordSlashStar = null; + FunctionArgumentAttributeValue attrStrMdPatientInfo = null; + + + // + // REQUEST objects available for use in tests + // + Request requestEmpty = new StdRequest(StdStatus.STATUS_OK); + Request requestMdRecord = null; + Request requestDoubleResources = null; + Request requestResourceActionContent = null; + Request requestContentInAction = null; + + + + + /** + * Set up all variables in one place because it is complicated (lots of steps needed for each attribute) + */ + public FunctionDefinitionXPathTest() { + try { + XPathFactory xPathFactory = XPathFactory.newInstance(); + XPath xpath = xPathFactory.newXPath(); + xpath.setNamespaceContext(nameSpaceContext); + + // Create XPaths to use in expressions + XPathExpressionWrapper xEmpty = new XPathExpressionWrapper(""); + XPathExpressionWrapper xSlashSlashMdRecord = new XPathExpressionWrapper(xpath.compile("//md:record")); + XPathExpressionWrapper xSlashSlashStar = new XPathExpressionWrapper(xpath.compile("//*")); + XPathExpressionWrapper xSlashSlashMdName = new XPathExpressionWrapper(xpath.compile("//md:name")); + XPathExpressionWrapper xSlashSlashMdMalignancy = new XPathExpressionWrapper(xpath.compile("//md:malignancy")); + XPathExpressionWrapper xNotInRequest = new XPathExpressionWrapper(xpath.compile("value_Not_in_request")); + XPathExpressionWrapper xSlashSlashMdRecordSlashStar = new XPathExpressionWrapper(xpath.compile("//md:record/*")); + XPathExpressionWrapper xMdPatientInfo = new XPathExpressionWrapper(xpath.compile("md:patient_info")); + + + + // create Function Attributes out of the XPathExpressions + attrXnull = new FunctionArgumentAttributeValue(null); + attrXEmpty = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xEmpty)); + attrXNoCategory = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xSlashSlashMdRecord)); + attrXNoValue = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xEmpty, + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + attrXSlashSlashMdRecord = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xSlashSlashMdRecord, + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + attrXSlashSlashStar = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xSlashSlashStar, + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + attrXSlashSlashMdName = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xSlashSlashMdName, + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + attrXSlashSlashMdMalignancy = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xSlashSlashMdMalignancy, + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + attrXNotInRequest = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xNotInRequest, + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + + attrXSlashSlashMdRecordSlashStar = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xSlashSlashMdRecordSlashStar, + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + attrXMdPatientInfo = new FunctionArgumentAttributeValue(DataTypes.DT_XPATHEXPRESSION.createAttributeValue(xMdPatientInfo, + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + + + // Deprecated versions of args + attrStrnull = new FunctionArgumentAttributeValue(null); + attrStrEmpty = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("")); + attrStrNoCategory = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("//md:record")); + attrStrNoValue = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("", + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + attrStrSlashSlashMdRecord = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("//md:record", + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + attrStrSlashSlashStar = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("//*", + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + attrStrSlashSlashMdName = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("//md:name", + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + attrStrSlashSlashMdMalignancy = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("//md:malignancy", + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + attrStrNotInRequest = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("value_Not_in_request", + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + + attrStrSlashSlashMdRecordSlashStar = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("//md:record/*", + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + attrStrMdPatientInfo = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("md:patient_info", + new IdentifierImpl("urn:oasis:names:tc:xacml:3.0:attribute-category:resource" ))); + + + + + attrBadType = new FunctionArgumentAttributeValue(DataTypes.DT_STRING.createAttributeValue("some string")); + + + + // Request objects + // to create a Request object the easiest way is to put the xml into a file and use the DOMRequest to load it. + + // single Content in the Resources section (normal valid request) + String reqString = reqStrMainResourceStart + reqStrContentMdRecord + reqStrResourceAllEnd; + File tFile = File.createTempFile("functionJunit", "request"); + BufferedWriter bw = new BufferedWriter(new FileWriter(tFile)); + bw.append(reqString); + bw.flush(); + bw.close(); + requestMdRecord = DOMRequest.load(tFile); + tFile.delete(); + + // Resources included twice + reqString = reqStrMainResourceStart + reqStrContentMdRecord + reqStrResourceEnd + reqStrResourceStart + reqStrContentMdRecord +reqStrResourceAllEnd; + tFile = File.createTempFile("functionJunit", "request"); + bw = new BufferedWriter(new FileWriter(tFile)); + bw.append(reqString); + bw.flush(); + bw.close(); + requestDoubleResources = DOMRequest.load(tFile); + tFile.delete(); + + + // content included in both Resource and Action - ok + reqString = reqStrMainResourceStart + reqStrContentMdRecord + reqStrResourceEnd + reqStrActionStart + reqStrContentMdRecord + reqStrActionEnd + reqStrMainEnd; + tFile = File.createTempFile("functionJunit", "request"); + bw = new BufferedWriter(new FileWriter(tFile)); + bw.append(reqString); + bw.flush(); + bw.close(); + requestResourceActionContent = DOMRequest.load(tFile); + tFile.delete(); + + // Content included only in Action - missing content produces non-error result according to spec + reqString = reqStrMainResourceStart + reqStrResourceEnd + reqStrActionStart + reqStrContentMdRecord + reqStrActionEnd + reqStrMainEnd; + tFile = File.createTempFile("functionJunit", "request"); + bw = new BufferedWriter(new FileWriter(tFile)); + bw.append(reqString); + bw.flush(); + bw.close(); + requestContentInAction = DOMRequest.load(tFile); + tFile.delete(); + + + + // Test that Bad XML is caught + @SuppressWarnings("unused") + Request requestContentMisplaced = null; + @SuppressWarnings("unused") + Request requestMalformedContent = null; + @SuppressWarnings("unused") + Request requestDoubleContent = null; + + + // Content included twice - error + reqString = reqStrMainResourceStart + reqStrContentMdRecord + reqStrContentMdRecord +reqStrResourceAllEnd; + tFile = File.createTempFile("functionJunit", "request"); + bw = new BufferedWriter(new FileWriter(tFile)); + bw.append(reqString); + bw.flush(); + bw.close(); + try { + requestDoubleContent = DOMRequest.load(tFile); + tFile.delete(); + } catch (com.att.research.xacml.std.dom.DOMStructureException e) { + // this is what it should do, so just continue + } catch (Exception e) { + fail("Unexpected exception for bad XML, e="+e); + } + + // Bad XML - Content not under a Category + reqString = reqStrMainStart + reqStrContentMdRecord + reqStrResourceStart + reqStrResourceEnd + reqStrActionStart + reqStrActionEnd + reqStrMainEnd; + tFile = File.createTempFile("functionJunit", "request"); + bw = new BufferedWriter(new FileWriter(tFile)); + bw.append(reqString); + bw.flush(); + bw.close(); + try { + requestContentMisplaced = DOMRequest.load(tFile); + tFile.delete(); + } catch (com.att.research.xacml.std.dom.DOMStructureException e) { + // this is what it should do, so just continue + } catch (Exception e) { + fail("Unexpected exception for bad XML, e="+e); + } + + // Bad XML - Content is not valid XML + reqString = reqStrMainResourceStart + reqStrMalformedContent + reqStrResourceAllEnd; + tFile = File.createTempFile("functionJunit", "request"); + bw = new BufferedWriter(new FileWriter(tFile)); + bw.append(reqString); + bw.flush(); + bw.close(); + try { + requestMalformedContent = DOMRequest.load(tFile); + tFile.delete(); + } catch (com.att.research.xacml.std.dom.DOMStructureException e) { + // this is what it should do, so just continue + } catch (Exception e) { + fail("Unexpected exception for bad XML, e="+e); + } + + } catch (Exception e) { + fail("Constructor initializing variables, e="+ e + " cause="+e.getCause()); + } + + } + + + + + + + + + @Test + public void testXpath_node_count() { + + + + FunctionDefinitionXPath fd = (FunctionDefinitionXPath) StdFunctions.FD_XPATH_NODE_COUNT; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_XPATH_NODE_COUNT, fd.getId()); + assertEquals(DataTypes.DT_XPATHEXPRESSION.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_INTEGER.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(1), fd.getNumArgs()); + + + // match all elements within context + arguments.clear(); + arguments.add(attrXSlashSlashStar); + ExpressionResult res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + BigInteger resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("18"), resValue); + + // match exactly 1 element + arguments.clear(); + arguments.add(attrXSlashSlashMdMalignancy); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("1"), resValue); + + // match a few but not all + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("2"), resValue); + + + // verify variables using in other tests: count nodes immediately under md:record + arguments.clear(); + arguments.add(attrXSlashSlashMdRecordSlashStar); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("3"), resValue); + + // verify variables using in other tests: count number of records containing patient_info + arguments.clear(); + arguments.add(attrXMdPatientInfo); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("1"), resValue); + + // verify variables using in other tests: count number of records containing md:name + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("2"), resValue); + + // verify variables using in other tests: count number of records containing md:malignancy + arguments.clear(); + arguments.add(attrXSlashSlashMdMalignancy); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("1"), resValue); + + + + + // match no element + arguments.clear(); + arguments.add(attrXNotInRequest); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("0"), resValue); + + // Resources included twice + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestDoubleResources, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-count More than one Content section for id 'urn:oasis:names:tc:xacml:3.0:attribute-category:resource'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // Content in both Resource and Action categories (ok) + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestResourceActionContent, null, null), arguments); + assertTrue(res.isOk()); + resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("2"), resValue); + + // Content only in Action category (missing in Resources -> 0 according to spec) + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestContentInAction, null, null), arguments); + assertTrue(res.isOk()); + resValue = (BigInteger)res.getValue().getValue(); + assertEquals(new BigInteger("0"), resValue); + + + + +//TODO - any other tests???? + + // null Evaluation Context + arguments.clear(); + arguments.add(attrXEmpty); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-count Got null EvaluationContext", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null Request + arguments.clear(); + arguments.add(attrXSlashSlashMdRecord); + res = fd.evaluate(new StdEvaluationContext(null, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-count Got null Request in EvaluationContext", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null attribute + arguments.clear(); + arguments.add(attrXnull); + res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-count Got null attribute at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // no value + arguments.clear(); + arguments.add(attrXNoValue); + res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-count XPathExpression returned null at index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // no category + arguments.clear(); + arguments.add(attrXNoCategory); + res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-count Got null Category at index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // too many args + arguments.clear(); + arguments.add(attrXEmpty); + arguments.add(attrXEmpty); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-count Expected 1 arguments, got 2", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too few args + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-count Expected 1 arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-count Expected data type 'xpathExpression' saw 'string' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null args + arguments.clear(); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-count Got null argument at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + @Test + public void testXpath_node_equal() { + + + FunctionDefinitionXPath fd = (FunctionDefinitionXPath) StdFunctions.FD_XPATH_NODE_EQUAL; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_XPATH_NODE_EQUAL, fd.getId()); + assertEquals(DataTypes.DT_XPATHEXPRESSION.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + + // test normal success - exactly the same set + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + arguments.add(attrXSlashSlashMdName); + ExpressionResult res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // success - second list is subset of first list + arguments.clear(); + arguments.add(attrXSlashSlashMdRecordSlashStar); + arguments.add(attrXMdPatientInfo); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // success - first list is subset of second list + arguments.clear(); + arguments.add(attrXMdPatientInfo); + arguments.add(attrXSlashSlashMdRecordSlashStar); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // success - second list contains children of first list + arguments.clear(); + arguments.add(attrXSlashSlashMdRecord); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // success - first list contains children of second list + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + arguments.add(attrXSlashSlashMdRecord); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + + + // two non-overlapping sets + arguments.clear(); + arguments.add(attrXSlashSlashMdMalignancy); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first list contains nothing + arguments.clear(); + arguments.add(attrXNotInRequest); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // second list contains nothing + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + arguments.add(attrXNotInRequest); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + + +//TODO + //????? + ///??????? add real tests + ////// + + + // Resources included twice + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestDoubleResources, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal More than one Content section for id 'urn:oasis:names:tc:xacml:3.0:attribute-category:resource'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + + // Content in both Resource and Action categories (ok) + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestResourceActionContent, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // Content only in Action category (missing in Resources -> 0 according to spec) + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestContentInAction, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + + // null Evaluation Context + arguments.clear(); + arguments.add(attrXSlashSlashMdRecord); + arguments.add(attrXSlashSlashMdRecord); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal Got null EvaluationContext", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null Request + arguments.clear(); + arguments.add(attrXSlashSlashMdRecord); + arguments.add(attrXSlashSlashMdRecord); + res = fd.evaluate(new StdEvaluationContext(null, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal Got null Request in EvaluationContext", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null attribute + arguments.clear(); + arguments.add(attrXnull); + arguments.add(attrXSlashSlashMdRecord); + res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal Got null attribute at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrXSlashSlashMdRecord); + arguments.add(attrXnull); + res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal Got null attribute at arg index 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // no value + arguments.clear(); + arguments.add(attrXNoValue); + arguments.add(attrXSlashSlashMdRecord); + res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal XPathExpression returned null at index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrXSlashSlashMdRecord); + arguments.add(attrXNoValue); + res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal XPathExpression returned null at index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // no category + arguments.clear(); + arguments.add(attrXNoCategory); + arguments.add(attrXSlashSlashMdRecord); + res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal Got null Category at index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrXSlashSlashMdRecord); + arguments.add(attrXNoCategory); + res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal XPathExpression returned null at index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many args + arguments.clear(); + arguments.add(attrXEmpty); + arguments.add(attrXEmpty); + arguments.add(attrXEmpty); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too few args + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrXEmpty); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrBadType); + arguments.add(attrXEmpty); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal Expected data type 'xpathExpression' saw 'string' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrXEmpty); + arguments.add(attrBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal Expected data type 'xpathExpression' saw 'string' at arg index 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null args + arguments.clear(); + arguments.add(attrXEmpty); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal Got null argument at arg index 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(null); + arguments.add(attrXEmpty); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-equal Got null argument at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + } + + + + + @Test + public void testXpath_node_match() { + + + FunctionDefinitionXPath fd = (FunctionDefinitionXPath) StdFunctions.FD_XPATH_NODE_MATCH; + + // check identity and type of the thing created + assertEquals(XACML3.ID_FUNCTION_XPATH_NODE_MATCH, fd.getId()); + assertEquals(DataTypes.DT_XPATHEXPRESSION.getId(), fd.getDataTypeArgs().getId()); + assertEquals(DataTypes.DT_BOOLEAN.getId(), fd.getDataTypeId()); + + // just to be safe... If tests take too long these can probably be eliminated + assertFalse(fd.returnsBag()); + assertEquals(new Integer(2), fd.getNumArgs()); + + + // test normal success - exactly the same set + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + arguments.add(attrXSlashSlashMdName); + ExpressionResult res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + Boolean resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // success - second list is subset of first list + arguments.clear(); + arguments.add(attrXSlashSlashMdRecordSlashStar); + arguments.add(attrXMdPatientInfo); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // success - first list is subset of second list + arguments.clear(); + arguments.add(attrXMdPatientInfo); + arguments.add(attrXSlashSlashMdRecordSlashStar); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // success - second list contains children of first list + arguments.clear(); + arguments.add(attrXSlashSlashMdRecord); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // success - first list contains children of second list + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + arguments.add(attrXSlashSlashMdRecord); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + + + // two non-overlapping sets + arguments.clear(); + arguments.add(attrXSlashSlashMdMalignancy); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // first list contains nothing + arguments.clear(); + arguments.add(attrXNotInRequest); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + // second list contains nothing + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + arguments.add(attrXNotInRequest); + res = fd.evaluate(new StdEvaluationContext(requestMdRecord, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + +//TODO + //????? + ///??????? add real tests + ////// + + + // Resources included twice + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestDoubleResources, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match More than one Content section for id 'urn:oasis:names:tc:xacml:3.0:attribute-category:resource'", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + // Content in both Resource and Action categories (ok) + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestResourceActionContent, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertTrue(resValue); + + // Content only in Action category (missing in Resources -> 0 according to spec) + arguments.clear(); + arguments.add(attrXSlashSlashMdName); + arguments.add(attrXSlashSlashMdName); + res = fd.evaluate(new StdEvaluationContext(requestContentInAction, null, null), arguments); + assertTrue(res.isOk()); + resValue = (Boolean)res.getValue().getValue(); + assertFalse(resValue); + + + // null Evaluation Context + arguments.clear(); + arguments.add(attrXSlashSlashMdRecord); + arguments.add(attrXSlashSlashMdRecord); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match Got null EvaluationContext", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null Request + arguments.clear(); + arguments.add(attrXSlashSlashMdRecord); + arguments.add(attrXSlashSlashMdRecord); + res = fd.evaluate(new StdEvaluationContext(null, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match Got null Request in EvaluationContext", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null attribute + arguments.clear(); + arguments.add(attrXnull); + arguments.add(attrXSlashSlashMdRecord); + res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match Got null attribute at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrXSlashSlashMdRecord); + arguments.add(attrXnull); + res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match Got null attribute at arg index 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // no value + arguments.clear(); + arguments.add(attrXNoValue); + arguments.add(attrXSlashSlashMdRecord); + res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match XPathExpression returned null at index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrXSlashSlashMdRecord); + arguments.add(attrXNoValue); + res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match XPathExpression returned null at index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // no category + arguments.clear(); + arguments.add(attrXNoCategory); + arguments.add(attrXSlashSlashMdRecord); + res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match Got null Category at index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:syntax-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrXSlashSlashMdRecord); + arguments.add(attrXNoCategory); + res = fd.evaluate(new StdEvaluationContext(requestEmpty, null, null), arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match XPathExpression returned null at index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too many args + arguments.clear(); + arguments.add(attrXEmpty); + arguments.add(attrXEmpty); + arguments.add(attrXEmpty); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match Expected 2 arguments, got 3", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // too few args + arguments.clear(); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match Expected 2 arguments, got 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrXEmpty); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match Expected 2 arguments, got 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // bad arg type + arguments.clear(); + arguments.add(attrBadType); + arguments.add(attrXEmpty); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match Expected data type 'xpathExpression' saw 'string' at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(attrXEmpty); + arguments.add(attrBadType); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match Expected data type 'xpathExpression' saw 'string' at arg index 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + // null args + arguments.clear(); + arguments.add(attrXEmpty); + arguments.add(null); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match Got null argument at arg index 1", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + arguments.clear(); + arguments.add(null); + arguments.add(attrXEmpty); + res = fd.evaluate(null, arguments); + assertFalse(res.getStatus().isOk()); + assertEquals( "function:xpath-node-match Got null argument at arg index 0", res.getStatus().getStatusMessage()); + assertEquals("urn:oasis:names:tc:xacml:1.0:status:processing-error", res.getStatus().getStatusCode().getStatusCodeValue().stringValue()); + + + + } + + + + // + // DEPRECATED versions that use String arguments rather than XPATHEXPRESSIONs + // are NOT supported due to ambiguity in the semantics between 2.0 ( is root and has only one in resources) + // and 3.0 ( is root and there are multiple sections in any category) + // + + + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/PDPTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/PDPTest.java new file mode 100644 index 000000000..6442d7a12 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/PDPTest.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + + +import static org.junit.Assert.assertNull; +//import static org.junit.Assert.fail; + +import org.junit.Test; + +public class PDPTest { + + @Test + public void testDummy() { + assertNull(null); + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/TestRunner.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/TestRunner.java new file mode 100644 index 000000000..b131964d4 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/TestRunner.java @@ -0,0 +1,46 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test; + +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; + +public class TestRunner { + private static Result results; + + public static void main(String[] args) { + Result result = JUnitCore.runClasses(PDPTest.class); + for(Failure failure: result.getFailures()) { + System.out.println("Failed Test: " + failure.toString()); + } + results = null; + if(result.wasSuccessful()) { + System.out.println("Test Results... "); + System.out.println("Stats: \nRun Time: " + (results.getRunTime()+result.getRunTime()) + "\nTotal Tests:" + results.getRunCount()+ result.getRunCount() + + "\nFailures: " + results.getFailureCount()+ result.getFailureCount()); + System.exit(1); + } + System.out.println("Tests Failed..."); + System.out.println("Stats: \nRun Time: " + result.getRunTime() + "\nTests:" + result.getRunCount() + + "\nFailures: " + result.getFailureCount()); + } +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/Conformance.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/Conformance.java new file mode 100644 index 000000000..d7af8b008 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/Conformance.java @@ -0,0 +1,634 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.conformance; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import com.att.research.xacml.api.Advice; +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeAssignment; +import com.att.research.xacml.api.AttributeCategory; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.IdReference; +import com.att.research.xacml.api.Obligation; +import com.att.research.xacml.api.Response; +import com.att.research.xacml.api.Result; + +/** + * Conformance is an application that runs a ConformanceTestSet and dumps results comparing the actual and + * expected results. + * + * TO RUN in Eclipse: + * This is run as a Java Application. + * You must first create a Run/Debug Configuration: + * Under the Argument tab, in Program Arguments you must set the -i or --input command line argument. + * You should also direct the output to a file using -o or --output. (default is Console) + * See the init() method in this file for other useful arguments. + * Example for a Windows machine: + * -i testsets/conformance/xacml3.0-ct-v.0.4 + * -o \Users\yourLogin\Downloads\conformance.txt + * You must also set the VM arguments: + * -Dxacml.properties=testsets/conformance/xacml.properties . + * -Dlog4j.configuration=.\logging.properties + * + * @version $Revision: 1.2 $ + */ +public class Conformance { + private ConformanceScopeResolver scopeResolver; + private ConformanceTestEngine testEngine; + private ConformanceTestSet testSet = new ConformanceTestSet(); + private File outputFile; + private PrintWriter outputFileWriter; + + private List testNamesToRun = new ArrayList(); + + private boolean verbose; + private boolean failuresOnly; + private boolean strict; + private boolean stopOnFirstError; + + private int testsRun; + private int decisionsMatch; + private int statusCodesMatch; + private int attributesMatch; + private int policyIdsMatch; + private int policySetIdsMatch; + private int associatedAdviceMatch; + private int obligationsMatch; + private int unknownFunctions; + + + + + protected synchronized ConformanceScopeResolver getScopeResolver() { + if (this.scopeResolver == null) { + this.scopeResolver = new ConformanceScopeResolver(); + + /* + * TODO: + * Add the known scopes for the 2.0 conformance test. This could be made more general by allowing loading + * from a properties file eventually. + */ + try { + URI ID_SCOPE_ROOT = new URI("urn:root"); + URI ID_SCOPE_CHILD1 = new URI("urn:root:child1"); + URI ID_SCOPE_CHILD2 = new URI("urn:root:child2"); + URI ID_SCOPE_C1D1 = new URI("urn:root:child1:descendant1"); + URI ID_SCOPE_C1D2 = new URI("urn:root:child1:descendant2"); + URI ID_SCOPE_C2D1 = new URI("urn:root:child2:descendant1"); + URI ID_SCOPE_C2D2 = new URI("urn:root:child2:descendant2"); + + this.scopeResolver.add(ID_SCOPE_ROOT, ID_SCOPE_CHILD1); + this.scopeResolver.add(ID_SCOPE_CHILD1, ID_SCOPE_C1D1); + this.scopeResolver.add(ID_SCOPE_CHILD1, ID_SCOPE_C1D2); + this.scopeResolver.add(ID_SCOPE_ROOT, ID_SCOPE_CHILD2); + this.scopeResolver.add(ID_SCOPE_CHILD2, ID_SCOPE_C2D1); + this.scopeResolver.add(ID_SCOPE_CHILD2, ID_SCOPE_C2D2); + } catch (Exception ex) { + ex.printStackTrace(System.err); + } + + } + return this.scopeResolver; + } + + private void close() throws IOException { + if (this.outputFileWriter != null) { + this.outputFileWriter.close(); + } + } + + private boolean init(String[] args) { + boolean lenientRequests = true; + boolean lenientPolicies = false; + // default is to not run any non-first-time iterations + int iterations = -1; + String testSetDirectoryNames = ""; + for (int i = 0 ; i < args.length ; ) { + + if (args[i].equals("-h") || args[i].equals("--help") || args[i].equals("-help")) { + printHelp(); + return false; + } + + + // where the XML Request/Response files are located + if (args[i].equals("-i") || args[i].equals("--input")) { + i++; + while (i < args.length && !args[i].startsWith("-")) { + testSetDirectoryNames += " " + args[i]; + try { + testSet.addConformanceTestSet(ConformanceTestSet.loadDirectory(new File(args[i]))); + } catch (Exception ex) { + ex.printStackTrace(System.err); + return false; + } + i++; + } + + // File path name where output will be put - default is stdout == Console + } else if (args[i].equals("-o") || args[i].equals("--output")) { + if (i+1 < args.length) { + this.outputFile = new File(args[i+1]); + i += 2; + } else { + System.err.println("Missing argument to " + args[i] + " command line option"); + return false; + } + // A list of specific test names (e.g.: -t IIA001 IIA007 IIIE301) - default is to run all tests + } else if (args[i].equals("-t") || args[i].equals("--tests")) { + i++; + while (i < args.length && !args[i].startsWith("-")) { + testNamesToRun.add(args[i]); + i++; + } + if (testNamesToRun.size() == 0) { + System.err.println("Missing test names after -t or --tests argument"); + return false; + } + // Include full details in the response, both the expected reqsponse (from file) and the actual response + } else if (args[i].equals("-v") || args[i].equals("--verbose")) { + this.verbose = true; + i++; + // Report only failures (success is silent) + } else if (args[i].equals("-f") || args[i].equals("--failures")) { + this.failuresOnly = true; + i++; + // When set, the XML must not contain extra attibutes/elements. Default is "lenient" where unexpected entries are ignored + } else if (args[i].equals("-s") || args[i].equals("--strict")) { + this.strict = true; + i++; + // (self explanatory) + } else if (args[i].equals("--stop-on-error")) { + this.stopOnFirstError = true; + i++; + } else if (args[i].equals("--lenient")) { + lenientPolicies = true; + lenientRequests = true; + i++; + } else if (args[i].equals("--lenient-policies")) { + lenientPolicies = true; + i++; + } else if (args[i].equals("--lenient-requests")) { + lenientRequests = true; + i++; + } else if (args[i].equals("--strict-policies")) { + lenientPolicies = false; + i++; + } else if (args[i].equals("--strict-requests")) { + lenientRequests = false; + i++; + } else if (args[i].equals("--iterations")) { + // this is a count of how many ADDITIONAL times the decide() should be called. + // The first time decide() is called it takes a long time to set up, + // so to get an accurate number for how fast a single Request is handled we need to ignore the time for the first run + // and timings for 1 or more non-first-time calls to decide(). + if (i+1 < args.length) { + try { + iterations = Integer.parseInt(args[i+1]); + i += 2; + } catch (NumberFormatException ex) { + System.err.println("Invalid iteration count '" + args[i+1] + "'"); + return false; + } + } else { + System.err.println("Missing argument to " + args[i] + " command line option"); + return false; + } + if (iterations < 1) { + System.err.println("Cannot use --iterations " + iterations + ". Must use an integer greater than 0"); + return false; + } + } else { + System.err.println("Unknown command line option " + args[i]); + return false; + } + } + + this.testEngine = new ConformanceTestEngine(this.getScopeResolver(), lenientRequests, lenientPolicies, iterations); + + if (testSetDirectoryNames.length() == 0) { + System.err.println("No test set directory given (need -i or --iniput command line option)"); + return false; + } + if (testSet.getListConformanceTests().size() == 0) { + System.err.println("No tests in given directories: " + testSetDirectoryNames); + } + + if (testNamesToRun.size() > 0) { + String s = ""; + for (String name : testNamesToRun) { + s += ", " + name; + } + System.out.println("Tests limited to: " + s.substring(1)); + } + + if (this.outputFile == null) { + this.outputFileWriter = new PrintWriter(System.out); + } else { + try { + this.outputFileWriter = new PrintWriter(new FileOutputStream(this.outputFile)); + } catch (IOException ex) { + System.err.println("Cannot open " + this.outputFile.getAbsolutePath() + " for writing."); + return false; + } + } + + return true; + } + + private void printHelp() { + System.out.println("usage: Conformance --input OPTIONS"); + System.out.println(""); + System.out.println(" -f, --failures Only include failed tests in the output. \n"+ + " Default is to include all test's results in the output file."); + System.out.println(""); + System.out.println(" -h, --help Prints help."); + + System.out.println(""); + System.out.println(" -i, --input Directory containing the XML Request/Response files. \n"+ + " This may be multiple space-separated directory paths. REQUIRED"); + + System.out.println(""); + System.out.println(" --iterations The number of times to run through the set of tests in the input directory."); + + System.out.println(""); + System.out.println(" --lenient Allow both Requests and Policies to have unexpected elements, no data in , etc. \n"+ + " Default is to not allow anything that is not explicitly listed in the XACML spec."); + + System.out.println(""); + System.out.println(" --lenient-policies Allow Policies to have unexpected elements, no data in , etc. \n" + + " Default is to not allow anything that is not explicitly listed in the XACML spec."); + + System.out.println(""); + System.out.println(" --lenient-requests Allow Requests to have unexpected elements, no data in , etc. \n" + + " Default is to not allow anything that is not explicitly listed in the XACML spec."); + + System.out.println(""); + System.out.println(" -o, --output Directory where the output results file will be put."); + + System.out.println(""); + System.out.println(" -s, --strict Check both the Decision and all other parts of the Response (Attributes, Obligations and Advice). \n "+ + " Default is to check just the Decision."); + + System.out.println(""); + System.out.println(" --stop-on-error Stop running conformance tests the first time one fails. Default is to continue through all tests."); + + System.out.println(""); + System.out.println(" --strict-policies Require Policies to have no unexpected elements, data in , etc. \n" + + " This is the default, but can be used to override Policies when option --lenient is used."); + + System.out.println(""); + System.out.println(" --strict-requests Require Requests to have no unexpected elements, data in , etc. \n" + + " This is the default, but can be used to override Requests when option --lenient is used."); + + System.out.println(""); + System.out.println(" -t, --tests A space-separated list of specific tests to be run. \n" + + " These are just the names of the tests as in 'IIA001 IIC178'. \n" + + " Default is to run all tests in the input directory."); + + System.out.println(""); + System.out.println(" -v, --verbose The entire expected and actual Response objects in the output. \n"+ + " Default is just a summary line."); + + } + + private boolean failed(ConformanceTestResult conformanceTestResult) { + ResponseMatchResult responseMatchResult = conformanceTestResult.getResponseMatchResult(); + if (responseMatchResult == null) { + return true; + } + if (!responseMatchResult.decisionsMatch() || !responseMatchResult.statusCodesMatch()) { + return true; + } else if (this.strict) { + if (!responseMatchResult.associatedAdviceMatches() || + !responseMatchResult.attributesMatch() || + !responseMatchResult.obligationsMatch() || + !responseMatchResult.policyIdentifiersMatch() || + !responseMatchResult.policySetIdentifiersMatch() + ) { + return true; + } + } + return false; + } + + private void dump(AttributeAssignment attributeAssignment) { + this.outputFileWriter.println("\t\t\t\tAttributeAssignment:"); + if (attributeAssignment.getCategory() != null) { + this.outputFileWriter.println("\t\t\t\t\tCategory: " + attributeAssignment.getCategory().stringValue()); + } + if (attributeAssignment.getAttributeId() != null) { + this.outputFileWriter.println("\t\t\t\t\tAttributeId: " + attributeAssignment.getAttributeId().stringValue()); + } + if (attributeAssignment.getDataTypeId() != null) { + this.outputFileWriter.println("\t\t\t\t\tDataType: " + attributeAssignment.getDataTypeId().stringValue()); + } + if (attributeAssignment.getIssuer() != null) { + this.outputFileWriter.println("\t\t\t\t\tIssuer: " + attributeAssignment.getIssuer()); + } + if (attributeAssignment.getAttributeValue() != null && attributeAssignment.getAttributeValue().getValue() != null) { + this.outputFileWriter.println("\t\t\t\t\tValue: " + attributeAssignment.getAttributeValue().getValue().toString()); + } + } + + private void dump(Attribute attribute) { + this.outputFileWriter.println("\t\t\t\t\tAttribute: " + (attribute.getAttributeId() == null ? "" : attribute.getAttributeId().stringValue())); + if (attribute.getIssuer() != null) { + this.outputFileWriter.println("\t\t\t\t\t\tIssuer: " + attribute.getIssuer()); + } + Iterator> iterAttributeValues = attribute.getValues().iterator(); + if (iterAttributeValues.hasNext()) { + this.outputFileWriter.println("\t\t\t\t\t\tValues: "); + while (iterAttributeValues.hasNext()) { + this.outputFileWriter.print("\t\t\t\t\t\t\t"); + AttributeValue attributeValue = iterAttributeValues.next(); + if (attributeValue.getDataTypeId() != null) { + this.outputFileWriter.print("DataType: " + attributeValue.getDataTypeId().stringValue() + " "); + } + if (attributeValue.getValue() != null) { + this.outputFileWriter.print("Value: " + attributeValue.getValue().toString()); + } + this.outputFileWriter.println(); + } + } + } + + private void dump(AttributeCategory attributeCategory) { + this.outputFileWriter.println("\t\t\tAttributeCategory: " + (attributeCategory.getCategory() == null ? "" : attributeCategory.getCategory().stringValue())); + Collection listAttributes = attributeCategory.getAttributes(); + if (listAttributes.size() > 0) { + this.outputFileWriter.println("\t\t\t\tAttributes:"); + for (Attribute attribute: listAttributes) { + this.dump(attribute); + } + } + } + + private void dump(Result result) { + this.outputFileWriter.println("\t\t======== Result =========="); + this.outputFileWriter.println("\t\tDecision: " + (result.getDecision() == null ? "null" : result.getDecision().name())); + if (result.getStatus() == null) { + this.outputFileWriter.println("\t\tStatus: null"); + } else { + this.outputFileWriter.println("\t\tStatus:"); + if (result.getStatus().getStatusCode() != null) { + this.outputFileWriter.println("\t\t\tStatusCode: " + result.getStatus().getStatusCode().toString()); + } + if (result.getStatus().getStatusMessage() != null) { + this.outputFileWriter.println("\t\t\tStatusMessage: " + result.getStatus().getStatusMessage()); + } + if (result.getStatus().getStatusDetail() != null) { + this.outputFileWriter.println("\t\t\tStatusDetail: " + result.getStatus().getStatusDetail().toString()); + } + } + Collection listAdvice = result.getAssociatedAdvice(); + if (listAdvice.size() > 0) { + this.outputFileWriter.println("\t\tAdvice:"); + for (Advice advice : listAdvice) { + if (advice.getId() != null) { + this.outputFileWriter.println("\t\t\tId: " + advice.getId().stringValue()); + } + Collection attributeAssignments = advice.getAttributeAssignments(); + if (attributeAssignments.size() > 0) { + this.outputFileWriter.println("\t\t\tAttributeAssignments:"); + for (AttributeAssignment attributeAssignment: attributeAssignments) { + this.dump(attributeAssignment); + } + } + } + } + Collection listObligations = result.getObligations(); + if (listObligations.size() > 0) { + for (Obligation obligation: listObligations) { + if (obligation.getId() != null) { + this.outputFileWriter.println("\t\t\tId: " + obligation.getId().stringValue()); + } + Collection attributeAssignments = obligation.getAttributeAssignments(); + if (attributeAssignments.size() > 0) { + this.outputFileWriter.println("\t\t\tAttributeAssignments:"); + for (AttributeAssignment attributeAssignment : attributeAssignments) { + this.dump(attributeAssignment); + } + } + } + } + Collection listAttributeCategories = result.getAttributes(); + if (listAttributeCategories.size() > 0) { + this.outputFileWriter.println("\t\tAttributes:"); + for (AttributeCategory attributeCategory : listAttributeCategories) { + this.dump(attributeCategory); + } + } + Collection listIdReferences; + if ((listIdReferences = result.getPolicyIdentifiers()).size() > 0) { + this.outputFileWriter.println("\t\tPolicyIds:"); + for (IdReference idReference : listIdReferences) { + this.outputFileWriter.println("\t\t\t" + idReference.toString()); + } + } + if ((listIdReferences = result.getPolicySetIdentifiers()).size() > 0) { + this.outputFileWriter.println("\t\tPolicySetIds:"); + for (IdReference idReference : listIdReferences) { + this.outputFileWriter.println("\t\t\t" + idReference.toString()); + } + } + } + + private void dump(String label, Response response) { + this.outputFileWriter.println("\t========== " + label + "=========="); + if (response == null) { + this.outputFileWriter.println("null"); + return; + } + + for (Result result : response.getResults()) { + this.dump(result); + } + } + + private void dump(ConformanceTestResult conformanceTestResult) { + + ResponseMatchResult responseMatchResult = conformanceTestResult.getResponseMatchResult(); + if (this.verbose) { + this.outputFileWriter.println("========== Test " + conformanceTestResult.getConformanceTest().getTestName() + " =========="); + this.dump("Expected Response", conformanceTestResult.getExpectedResponse()); + this.dump("Actual Response", conformanceTestResult.getActualResponse()); + if (responseMatchResult != null) { + this.outputFileWriter.println("\t========== Matching =========="); + this.outputFileWriter.println("\tDecisions Match? " + responseMatchResult.decisionsMatch()); + this.outputFileWriter.println("\tStatus Codes Match? " + responseMatchResult.statusCodesMatch()); + this.outputFileWriter.println("\tAttributes Match? " + responseMatchResult.attributesMatch()); + this.outputFileWriter.println("\tPolicyIds Match? " + responseMatchResult.policyIdentifiersMatch()); + this.outputFileWriter.println("\tPolicySetIds Match? " + responseMatchResult.policySetIdentifiersMatch()); + this.outputFileWriter.println("\tAssociated Advice Match? " + responseMatchResult.associatedAdviceMatches()); + this.outputFileWriter.println("\tObligations Match? " + responseMatchResult.obligationsMatch()); + this.outputFileWriter.println("========== End =========="); + } + } else { + String testName = conformanceTestResult.getConformanceTest().getTestName(); + if (responseMatchResult != null) { + Iterator iterResultMatches = responseMatchResult.getResultMatchResults(); + if (iterResultMatches == null || !iterResultMatches.hasNext()) { + this.outputFileWriter.println(testName); + } else { + while (iterResultMatches.hasNext()) { + ResultMatchResult resultMatchResult = iterResultMatches.next(); + this.outputFileWriter.printf("%s,%s,%s,%s,%s,%s,%s,%s,%d,%d\n", + testName, + resultMatchResult.decisionsMatch(), + resultMatchResult.statusCodesMatch(), + resultMatchResult.attributesMatch(), + resultMatchResult.policyIdentifiersMatch(), + resultMatchResult.policySetIdentifiersMatch(), + resultMatchResult.associatedAdviceMatches(), + resultMatchResult.obligationsMatch(), + conformanceTestResult.getFirstCallTime(), + conformanceTestResult.getAverageTotalLoopTime() + ); + } + } + } + } + this.outputFileWriter.flush(); + } + + private boolean run(ConformanceTest conformanceTest) throws Exception { + this.testsRun++; + ConformanceTestResult conformanceTestResult = this.testEngine.run(conformanceTest); + boolean bFailed = true; + if (conformanceTestResult != null) { + ResponseMatchResult responseMatchResult = conformanceTestResult.getResponseMatchResult(); + if (responseMatchResult != null) { + if (responseMatchResult.decisionsMatch()) { + this.decisionsMatch++; + this.statusCodesMatch += (responseMatchResult.statusCodesMatch() ? 1 : 0); + this.attributesMatch += (responseMatchResult.attributesMatch() ? 1 : 0); + this.policyIdsMatch += (responseMatchResult.policyIdentifiersMatch() ? 1 : 0); + this.policySetIdsMatch += (responseMatchResult.policySetIdentifiersMatch() ? 1 : 0); + this.associatedAdviceMatch += (responseMatchResult.associatedAdviceMatches() ? 1 : 0); + this.obligationsMatch += (responseMatchResult.obligationsMatch() ? 1 : 0); + } + this.unknownFunctions += (responseMatchResult.unknownFunction() ? 1 : 0); + bFailed = this.failed(conformanceTestResult); + if (bFailed || !this.failuresOnly) { + this.dump(conformanceTestResult); + } + } else if (conformanceTestResult.getError() != null) { + this.outputFileWriter.println(conformanceTestResult.getError()); + } + } + return (!bFailed || !this.stopOnFirstError); + } + + private void run() throws Exception { + long tStart = System.currentTimeMillis(); + + if (!this.verbose) { + this.outputFileWriter.println("Test,Decision,Status,Attributes,PolicyIds,PolicySetIds,Advice,Obligations"); + } + Iterator iterConformanceTests = this.testSet.getConformanceTests(); + boolean bContinue = true; + while (bContinue && iterConformanceTests.hasNext()) { +// bContinue = this.run(iterConformanceTests.next()); + ConformanceTest test = iterConformanceTests.next(); + if (testNamesToRun.size() > 0) { + if ( ! testNamesToRun.contains(test.getTestName())) { + continue; + } + } + bContinue = this.run(test); + } + + long tElapsed = System.currentTimeMillis() - tStart; + + if (this.verbose) { + this.outputFileWriter.println("Tests run = " + this.testsRun); + this.outputFileWriter.println("Decisions match = " + this.decisionsMatch); + this.outputFileWriter.println("Status Codes match = " + this.statusCodesMatch); + this.outputFileWriter.println("Attributes match = " + this.attributesMatch); + this.outputFileWriter.println("PolicyIds match = " + this.policyIdsMatch); + this.outputFileWriter.println("PolicySetIds match = " + this.policySetIdsMatch); + this.outputFileWriter.println("Associated Advice match = " + this.associatedAdviceMatch); + this.outputFileWriter.println("Obligations match = " + this.obligationsMatch); + this.outputFileWriter.println("Unknown functions = " + this.unknownFunctions); + } else { + this.outputFileWriter.printf("Total (%d),%d,%d,%d,%d,%d,%d,%d,%d\n", + this.testsRun, + this.decisionsMatch, + this.statusCodesMatch, + this.attributesMatch, + this.policyIdsMatch, + this.policySetIdsMatch, + this.associatedAdviceMatch, + this.obligationsMatch, + this.unknownFunctions); + } + + if (tElapsed > 0) { + long tHours = tElapsed / (60*60*1000); + tElapsed = tElapsed - tHours * 60 * 60 *1000; + long tMinutes = tElapsed / (60*1000); + tElapsed = tElapsed - tMinutes * 60 * 1000; + long tSeconds = tElapsed / 1000; + tElapsed = tElapsed - tSeconds * 1000; + + this.outputFileWriter.printf("Elapsed time = %02d:%02d:%02d.%03d\n", tHours, tMinutes, tSeconds, tElapsed); + this.outputFileWriter.printf("First decide time in nano-seconds %d\n", this.testEngine.getFirstDecideTime()); + this.outputFileWriter.printf("Total Multiple decide time in nano-seconds %d\n", this.testEngine.getDecideTimeMultiple()); + + this.outputFileWriter.printf("\nAverage First decide time in nano-seconds %d\n", this.testEngine.getAvgFirstDecideTime()); + this.outputFileWriter.printf("Average decide time after first call in nano-seconds %d\n", this.testEngine.getAvgDecideTimeMultiple()); + } + } + + public Conformance() { + } + + public static void main(String[] args) { + Conformance conformance = new Conformance(); + try { + if (conformance.init(args)) { + conformance.run(); + } + + } catch (Exception ex) { + ex.printStackTrace(System.err); + System.exit(1); + } finally { + try { + conformance.close(); + } catch (IOException ex) { + ex.printStackTrace(System.err); + } + } + System.exit(0); + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformancePIPEngine.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformancePIPEngine.java new file mode 100644 index 000000000..e81024159 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformancePIPEngine.java @@ -0,0 +1,242 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.conformance; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.DataType; +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.api.DataTypeFactory; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.pip.PIPException; +import com.att.research.xacml.api.pip.PIPFinder; +import com.att.research.xacml.api.pip.PIPRequest; +import com.att.research.xacml.api.pip.PIPResponse; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdMutableAttribute; +import com.att.research.xacml.std.pip.StdPIPResponse; +import com.att.research.xacml.std.pip.engines.ConfigurableEngine; +import com.att.research.xacml.util.FactoryException; + +/** + * ConformancePIPEngine implements the {@link com.att.research.xacml.api.pip.PIPFinder} interface to find attributes + * loaded from a text file containing the following fields: + * category-id,attribute-id,datatype-id,issuer,value + * + * @version $Revision: 1.1 $ + */ +public class ConformancePIPEngine implements ConfigurableEngine { + public static final String PROP_DESCRIPTION = ".description"; + public static final String PROP_FILE = ".file"; + + private static final Logger logger = FlexLogger.getLogger(ConformancePIPEngine.class); + + private String name; + private String description; + private Map cache = new HashMap<>(); + private List listAttributes = new ArrayList<>(); + private DataTypeFactory dataTypeFactory; + + public ConformancePIPEngine() { + + } + + protected DataTypeFactory getDataTypeFactory() throws FactoryException { + if (this.dataTypeFactory == null) { + this.dataTypeFactory = DataTypeFactory.newInstance(); + } + return this.dataTypeFactory; + } + + protected static String generateKey(PIPRequest pipRequest) { + StringBuilder stringBuilder = new StringBuilder(pipRequest.getCategory().toString()); + stringBuilder.append('+'); + stringBuilder.append(pipRequest.getAttributeId().toString()); + stringBuilder.append('+'); + stringBuilder.append(pipRequest.getDataTypeId().toString()); + String issuer = pipRequest.getIssuer(); + if (issuer != null) { + stringBuilder.append('+'); + stringBuilder.append(issuer); + } + return stringBuilder.toString(); + } + + protected void store(String[] fields) throws FactoryException { + DataTypeFactory thisDataTypeFactory = this.getDataTypeFactory(); + Identifier identifierCategory = new IdentifierImpl(fields[0]); + Identifier identifierAttribute = new IdentifierImpl(fields[1]); + Identifier identifierDataType = new IdentifierImpl(fields[2]); + String issuer = (fields.length == 5 ? fields[3] : null); + String value = fields[fields.length - 1]; + + DataType dataType = thisDataTypeFactory.getDataType(identifierDataType); + if (dataType == null) { + logger.error("Unknown data type " + identifierDataType.stringValue()); + return; + } + + AttributeValue attributeValue = null; + try { + attributeValue = dataType.createAttributeValue(value); + } catch (DataTypeException ex) { + throw new FactoryException("DataTypeException creating AttributeValue", ex); + } + Attribute attribute = new StdMutableAttribute(identifierCategory, identifierAttribute, attributeValue, issuer, false); + this.listAttributes.add(attribute); + } + + public void loadAttributes(File fileAttributes) throws IOException, ParseException, FactoryException { + if (fileAttributes != null) { + if (!fileAttributes.exists()) { + throw new FileNotFoundException("Attributes file " + fileAttributes.getAbsolutePath() + " not found."); + } else if (!fileAttributes.canRead()) { + throw new IOException("Attributes file " + fileAttributes.getAbsolutePath() + " is not readable."); + } + + BufferedReader bufferedReader = null; + try { + bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fileAttributes))); + String line; + while ((line = bufferedReader.readLine()) != null) { + if (line.length() > 0) { + String[] fields = line.split("[|]",-1); + if (fields.length < 4) { + logger.warn("Not enough fields in record \"" + line + "\""); + continue; + } + this.store(fields); + + } + } + } finally { + if (bufferedReader != null) { + bufferedReader.close(); + } + } + } + } + + protected Attribute findAttribute(PIPRequest pipRequest) { + Attribute attributeResult = null; + Iterator iterAttributes = this.listAttributes.iterator(); + while ((attributeResult == null) && iterAttributes.hasNext()) { + Attribute attributeTest = iterAttributes.next(); + if (pipRequest.getCategory().equals(attributeTest.getCategory()) && + pipRequest.getAttributeId().equals(attributeTest.getAttributeId()) && + (pipRequest.getIssuer() == null || pipRequest.getIssuer().equals(attributeTest.getIssuer()))) { + attributeResult = attributeTest; + } + } + return attributeResult; + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { + String pipRequestKey = generateKey(pipRequest); + PIPResponse pipResponse = this.cache.get(pipRequestKey); + if (pipResponse != null) { + return pipResponse; + } + Attribute attributeMatch = this.findAttribute(pipRequest); + if (attributeMatch == null) { + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } + /* + * Iterate through the values and only return the ones that match the requested data type + */ + List> matchingValues = new ArrayList<>(); + Iterator> iterAttributeValues = attributeMatch.getValues().iterator(); + while (iterAttributeValues.hasNext()) { + AttributeValue attributeValue = iterAttributeValues.next(); + if (pipRequest.getDataTypeId().equals(attributeValue.getDataTypeId())) { + matchingValues.add(attributeValue); + } + } + if (matchingValues.size() > 0) { + Attribute attributeResponse = new StdMutableAttribute(attributeMatch.getCategory(), attributeMatch.getAttributeId(), matchingValues, attributeMatch.getIssuer(), false); + pipResponse = new StdPIPResponse(attributeResponse); + this.cache.put(pipRequestKey, pipResponse); + } + return pipResponse; + } + + @Override + public String getName() { + return this.name; + } + + @Override + public String getDescription() { + return this.description; + } + + @Override + public void configure(String id, Properties properties) throws PIPException { + this.name = id; + this.description = properties.getProperty(id + PROP_DESCRIPTION); + if (this.description == null) { + this.description = "PIPEngine for the Conformance tests that loads attributes from a CSV file"; + } + String pipFile = properties.getProperty(id + PROP_FILE); + if (pipFile != null) { + try { + this.loadAttributes(new File(pipFile)); + } catch (Exception ex) { + logger.error("Exception loading PIP file " + pipFile, ex); + throw new PIPException("Exception loading PIP file " + pipFile, ex); + } + } + } + + @Override + public Collection attributesRequired() { + return Collections.emptyList(); + } + + @Override + public Collection attributesProvided() { + // + // We could return everything in our list + // + return Collections.emptyList(); + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceRepository.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceRepository.java new file mode 100644 index 000000000..995537ecd --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceRepository.java @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.conformance; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Properties; + +import com.att.research.xacml.util.StringUtils; +import com.att.research.xacml.util.XACMLProperties; +import com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory; + +/** + * ConformanceRepository represents one or more policies for a single policy test, which will include one or more root policies, and + * zero or more referenced policies. + * + * @version $Revision$ + */ +public class ConformanceRepository { + private List rootPolicies = new ArrayList<>(); + private List referencedPolicies = new ArrayList<>(); + + private void setXACMLProperty(String propertyName, List listFiles) { + Iterator iterFiles = listFiles.iterator(); + StringBuilder stringBuilderIdList = new StringBuilder(); + while (iterFiles.hasNext()) { + File file = iterFiles.next(); + if (stringBuilderIdList.length() > 0) { + stringBuilderIdList.append(','); + } + stringBuilderIdList.append(file.getName()); + + XACMLProperties.setProperty(file.getName() + StdPolicyFinderFactory.PROP_FILE, file.getAbsolutePath()); + } + XACMLProperties.setProperty(propertyName, stringBuilderIdList.toString()); + } + + public ConformanceRepository() { + } + + public void setXACMLProperties() { + if (this.rootPolicies.size() > 0) { + this.setXACMLProperty(XACMLProperties.PROP_ROOTPOLICIES, this.rootPolicies); + } + if (this.referencedPolicies.size() > 0) { + this.setXACMLProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, this.referencedPolicies); + } + } + + private void loadProperty(File fileDir, Properties properties, String propertyName, List listFiles) { + String fileNameList = properties.getProperty(propertyName); + if (fileNameList != null) { + String[] fileNameArray = fileNameList.split("[,]",0); + if (fileNameArray != null && fileNameArray.length > 0) { + for (String fileName : fileNameArray) { + File file = new File(fileDir, fileName); + if (file.exists() && file.canRead()) { + listFiles.add(file); + } + } + } + } + } + + public void load(File fileRepository) throws IOException { + Properties propertiesRepository = new Properties(); + try (InputStream is = new FileInputStream(fileRepository)) { + propertiesRepository.load(is); + } + this.loadProperty(fileRepository.getParentFile(), propertiesRepository, XACMLProperties.PROP_ROOTPOLICIES, this.rootPolicies); + this.loadProperty(fileRepository.getParentFile(), propertiesRepository, XACMLProperties.PROP_REFERENCEDPOLICIES, this.referencedPolicies); + } + + public void addRootPolicy(File filePolicy) { + this.rootPolicies.add(filePolicy); + } + + public boolean hasRootPolicy() { + return (this.rootPolicies.size() > 0); + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder("{"); + boolean needComma = false; + + if (this.rootPolicies != null && this.rootPolicies.size() > 0) { + stringBuilder.append("rootPolicies="); + stringBuilder.append(StringUtils.toString(this.rootPolicies.iterator())); + needComma = true; + } + if (this.referencedPolicies != null && this.referencedPolicies.size() > 0) { + if (needComma) { + stringBuilder.append(','); + } + stringBuilder.append("referencedPolicies="); + stringBuilder.append(StringUtils.toString(this.referencedPolicies.iterator())); + needComma = true; + } + stringBuilder.append('}'); + return stringBuilder.toString(); + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceScopeResolver.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceScopeResolver.java new file mode 100644 index 000000000..654145424 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceScopeResolver.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.conformance; + +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +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 com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.pdp.ScopeQualifier; +import com.att.research.xacml.api.pdp.ScopeResolver; +import com.att.research.xacml.api.pdp.ScopeResolverException; +import com.att.research.xacml.api.pdp.ScopeResolverResult; +import com.att.research.xacml.std.StdMutableAttribute; +import com.att.research.xacml.std.StdScopeResolverResult; +import com.att.research.xacml.std.StdStatus; +import com.att.research.xacml.std.StdStatusCode; +import com.att.research.xacml.std.datatypes.DataTypes; + +/** + * ConformanceScopeResolver implements {@link com.att.research.xacml.pdp.ScopeResolver} for the conformance tests + * using a fixed set of hierarchical resources defined in a map. + * + * @version $Revision$ + */ +public class ConformanceScopeResolver implements ScopeResolver { + private Logger logger = FlexLogger.getLogger(ConformanceScopeResolver.class); + private Map> mapIdentifierToChildren = new HashMap<>(); + + public ConformanceScopeResolver() { + } + + public void add(URI identifierRoot, URI identifierChild) { + List listChildrenRoot = this.mapIdentifierToChildren.get(identifierRoot); + if (listChildrenRoot == null) { + listChildrenRoot = new ArrayList<>(); + this.mapIdentifierToChildren.put(identifierRoot, listChildrenRoot); + } + listChildrenRoot.add(identifierChild); + } + + private void addChildren(Attribute attributeResourceId, URI urnResourceIdValue, boolean bDescendants, List listAttributes) { + List listChildren = this.mapIdentifierToChildren.get(urnResourceIdValue); + if (listChildren != null) { + for (URI uriChild : listChildren) { + AttributeValue attributeValueURI = null; + try { + attributeValueURI = DataTypes.DT_ANYURI.createAttributeValue(uriChild); + if (attributeValueURI != null) { + listAttributes.add(new StdMutableAttribute(attributeResourceId.getCategory(), attributeResourceId.getAttributeId(), attributeValueURI, attributeResourceId.getIssuer(), attributeResourceId.getIncludeInResults())); + } + } catch (Exception ex) { + this.logger.error("Exception converting URI to an AttributeValue"); + } + if (bDescendants) { + this.addChildren(attributeResourceId, uriChild, bDescendants, listAttributes); + } + } + } + } + + private void addChildren(Attribute attributeResourceId, boolean bDescendants, List listAttributes) { + /* + * Iterate over the values that are URNs + */ + Iterator> iterAttributeValueURNs = attributeResourceId.findValues(DataTypes.DT_ANYURI); + if (iterAttributeValueURNs != null) { + while (iterAttributeValueURNs.hasNext()) { + this.addChildren(attributeResourceId, iterAttributeValueURNs.next().getValue(), bDescendants, listAttributes); + } + } + } + + @Override + public ScopeResolverResult resolveScope(Attribute attributeResourceId, ScopeQualifier scopeQualifier) throws ScopeResolverException { + List listAttributes = new ArrayList<>(); + switch(scopeQualifier) { + case CHILDREN: + listAttributes.add(attributeResourceId); + this.addChildren(attributeResourceId, false, listAttributes); + break; + case DESCENDANTS: + listAttributes.add(attributeResourceId); + this.addChildren(attributeResourceId, true, listAttributes); + break; + case IMMEDIATE: + listAttributes.add(attributeResourceId); + break; + default: + this.logger.error("Unknown ScopeQualifier: " + scopeQualifier.name()); + return new StdScopeResolverResult(new StdStatus(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, "Unknown ScopeQualifier " + scopeQualifier.name())); + } + return new StdScopeResolverResult(listAttributes); + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTest.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTest.java new file mode 100644 index 000000000..a37d1c155 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTest.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.conformance; + +import java.io.File; + +/** + * ConformanceTest represents a collection of XACML files with a root Policy document, optional referenced Policy documents, a Request, and a Response. + * + * @version $Revision: 1.2 $ + */ +public class ConformanceTest { + private String testName; + private File request; + private File response; + private ConformanceRepository repository; + + public ConformanceTest(String name, ConformanceRepository conformanceRepository, File fileRequest, File fileResponse) { + this.testName = name; + this.request = fileRequest; + this.response = fileResponse; + this.repository = conformanceRepository; + } + + public ConformanceTest(String name) { + this.testName = name; + } + + public String getTestName() { + return this.testName; + } + public void setTestName(String s) { + this.testName = s; + } + public ConformanceRepository getRepository() { + if (this.repository == null) { + this.repository = new ConformanceRepository(); + } + return this.repository; + } + public File getRequest() { + return this.request; + } + public void setRequest(File f) { + this.request = f; + } + public File getResponse() { + return this.response; + } + public void setResponse(File f) { + this.response = f; + } + + public boolean isComplete() { + return this.getTestName() != null && this.getRepository() != null && this.getRepository().hasRootPolicy() && this.getRequest() != null && this.getResponse() != null; + } + + @Override + public String toString() { + StringBuilder stringBuilder = new StringBuilder(); + boolean needColon = false; + if (this.getTestName() != null) { + stringBuilder.append(this.getTestName()); + needColon = true; + } + if (this.getRepository() != null) { + + } + if (this.getRequest() != null) { + if (needColon) { + stringBuilder.append(':'); + } + stringBuilder.append(this.getRequest().getName()); + needColon = true; + } + if (this.getResponse() != null) { + if (needColon) { + stringBuilder.append(':'); + } + stringBuilder.append(this.getResponse().getName()); + needColon = true; + } + return stringBuilder.toString(); + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTestEngine.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTestEngine.java new file mode 100644 index 000000000..91e96cf1a --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTestEngine.java @@ -0,0 +1,219 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.conformance; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.Response; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.api.pdp.PDPEngineFactory; +import com.att.research.xacml.api.pdp.ScopeResolver; +import com.att.research.xacml.std.dom.DOMProperties; +import com.att.research.xacml.std.dom.DOMRequest; +import com.att.research.xacml.std.dom.DOMResponse; +import com.att.research.xacml.util.FactoryException; + +/** + * ConformanceTestEngine handles the creation of the PDPEngine for a ConformanceTest instance. + * + * @version $Revision: 1.2 $ + */ +public class ConformanceTestEngine { + private Logger logger = FlexLogger.getLogger(ConformanceTestEngine.class); + + private PDPEngineFactory pdpEngineFactory; + private ScopeResolver scopeResolver; + private boolean lenientRequests; + private boolean lenientPolicies; + private int iterations = 1; + + // total of all first calls to decide() + private long firstDecideTime; + private int numberOfFirstDecides = 0; + + // total of all non-first-calls to decide() + private long decideTimeMultiple; + + // total of average time each test case uses for a Request + // (sum of : for each test case, average of all non-first-call calls to decide() ) + private long avgDecideTimeMultiple = 0; + + protected PDPEngineFactory getPDPEngineFactory() throws FactoryException { + if (this.pdpEngineFactory == null) { + this.pdpEngineFactory = PDPEngineFactory.newInstance(); + this.pdpEngineFactory.setScopeResolver(this.scopeResolver); + } + return this.pdpEngineFactory; + } + + public ConformanceTestEngine(ScopeResolver scopeResolverIn, boolean lenientRequestsIn, boolean lenientPoliciesIn, int iterationsIn) { + this.scopeResolver = scopeResolverIn; + this.lenientRequests = lenientRequestsIn; + this.lenientPolicies = lenientPoliciesIn; + this.iterations = iterationsIn; + } + + public ConformanceTestResult run(ConformanceTest conformanceTest) { + if (conformanceTest.getRequest() == null || conformanceTest.getResponse() == null || conformanceTest.getRepository() == null) { + logger.error("Incomplete Conformance Test: " + conformanceTest.getTestName()); + } + PDPEngineFactory thisPDPEngineFactory = null; + try { + thisPDPEngineFactory = this.getPDPEngineFactory(); + } catch (FactoryException ex) { + return new ConformanceTestResult(conformanceTest, ex); + } + + ConformanceTestResult conformanceTestResult = new ConformanceTestResult(conformanceTest, iterations); + + /* + * Load the request + */ + Request request = null; + boolean isLenient = DOMProperties.isLenient(); + try { + DOMProperties.setLenient(this.lenientRequests); + try { + request = DOMRequest.load(conformanceTest.getRequest()); + conformanceTestResult.setRequest(request); + } catch (Exception ex) { + logger.error("Exception loading Request file " + conformanceTest.getRequest().getAbsolutePath(), ex); + conformanceTestResult.setError(ex); + return conformanceTestResult; + + } + + /* + * Load the expected response + */ + Response response = null; + try { + response = DOMResponse.load(conformanceTest.getResponse()); + conformanceTestResult.setExpectedResponse(response); + } catch (Exception ex) { + logger.error("Exception loading Response file " + conformanceTest.getResponse().getAbsolutePath(), ex); + conformanceTestResult.setError(ex); + return conformanceTestResult; + } + + /* + * Set up the configuration for the policy finder + */ + conformanceTest.getRepository().setXACMLProperties(); + DOMProperties.setLenient(this.lenientPolicies); + + /* + * Create the engine + */ + PDPEngine pdpEngine = null; + try { + // pdpEngine = thisPDPEngineFactory.newEngine(conformanceTest.getRootPolicy(), conformanceTest.getReferencedPolicies(), pipFinderEngine); + pdpEngine = thisPDPEngineFactory.newEngine(); + } catch (Exception ex) { + logger.error("Exception getting PDP engine instance", ex); + conformanceTestResult.setError(ex); + return conformanceTestResult; + } + if (pdpEngine == null) { + logger.error("Null PDP engine"); + conformanceTestResult.setError(new NullPointerException("Null engine")); + return conformanceTestResult; + } + + /* + * Run the request + */ + long startTime, endTime; + long curDecideTime = this.firstDecideTime; + try { + startTime = System.nanoTime(); + response = pdpEngine.decide(request); + endTime = System.nanoTime(); +//System.out.println(endTime - startTime); + // add to total + this.firstDecideTime += endTime - startTime; + this.numberOfFirstDecides++; + // remember just this test + conformanceTestResult.setFirstCallTime(endTime - startTime); + conformanceTestResult.setActualResponse(response); + } catch (Exception ex) { + logger.error("Exception in decide", ex); + conformanceTestResult.setError(ex); + return conformanceTestResult; + } + if (response == null) { + logger.error("Null Response"); + conformanceTestResult.setError(new NullPointerException("Null Response")); + return conformanceTestResult; + } + + long localLoopTime = 0; + try { + // if user requested non-first-call calls to decide() to get performance info, run them now. + // We can ignore the result since we are only interested in how long they take to process the Request. + for (int i = 0 ; i < this.iterations ; i++) { + startTime = System.nanoTime(); + pdpEngine.decide(request); + endTime = System.nanoTime(); +//System.out.println(endTime - startTime); + // add to the global total for all tests + this.decideTimeMultiple += (endTime - startTime); + // remember just this one test's info + localLoopTime += (endTime - startTime); + } + } catch (Exception ex) { + logger.error("Exception in iterated decide", ex); + return conformanceTestResult; + } + + // add to total average for non-first-call times for all test cases + avgDecideTimeMultiple += (localLoopTime / iterations); +//System.out.println("localLoop="+localLoopTime + " it="+iterations + " avg=" + (localLoopTime / iterations) ); + // remember average time for just this test + conformanceTestResult.setAverageTotalLoopTime(localLoopTime/iterations); + + long elapsedDecideTime = this.firstDecideTime - curDecideTime; + logger.info("Decide Time: " + elapsedDecideTime + "ns"); + + return conformanceTestResult; + } finally { + DOMProperties.setLenient(isLenient); + } + } + + public long getFirstDecideTime() { + return this.firstDecideTime; + } + + public long getDecideTimeMultiple() { + return this.decideTimeMultiple; + } + + + public long getAvgFirstDecideTime() { + return this.firstDecideTime / numberOfFirstDecides; + } + public long getAvgDecideTimeMultiple() { + return this.avgDecideTimeMultiple / numberOfFirstDecides; + } +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTestResult.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTestResult.java new file mode 100644 index 000000000..65cfd55fe --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTestResult.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.conformance; + +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.Response; + +/** + * ConformanceTestResult holds all of the objects for a single conformance test run. + * + * @version $Revision: 1.1 $ + */ +public class ConformanceTestResult { + private ConformanceTest conformanceTest; + private Request request; + private Response expectedResponse; + private Response actualResponse; + private ResponseMatchResult responseMatchResult; + private Exception error; + + // performance timings + private long firstCallTime; + private long averageTotalLoopTime; + + // how many non-first-call times the decide() was called + private int iterations; + + public ConformanceTestResult(ConformanceTest conformanceTestIn, int iterations) { + this.conformanceTest = conformanceTestIn; + this.iterations = iterations; + } + + public ConformanceTestResult(ConformanceTest conformanceTestIn, Exception errorIn) { + this.conformanceTest = conformanceTestIn; + this.error = errorIn; + } + + public int getIterations() { + return this.iterations; + } + + public ConformanceTest getConformanceTest() { + return this.conformanceTest; + } + public void setConformanceTest(ConformanceTest conformanceTestIn) { + this.conformanceTest = conformanceTestIn; + } + + public Request getRequest() { + return this.request; + } + public void setRequest(Request requestIn) { + this.request = requestIn; + } + + public Response getExpectedResponse() { + return this.expectedResponse; + } + public void setExpectedResponse(Response response) { + this.expectedResponse = response; + this.responseMatchResult = null; + } + + public Response getActualResponse() { + return this.actualResponse; + } + public void setActualResponse(Response response) { + this.actualResponse = response; + this.responseMatchResult = null; + } + + public ResponseMatchResult getResponseMatchResult() { + if (this.responseMatchResult == null && (this.actualResponse != null && this.expectedResponse != null)) { + this.computeResponseMatchResult(); + } + return this.responseMatchResult; + } + public void computeResponseMatchResult() { + if (this.expectedResponse != null && this.actualResponse != null) { + this.responseMatchResult = ResponseMatchResult.newInstance(this.expectedResponse, this.actualResponse); + } + } + public Exception getError() { + return this.error; + } + public void setError(Exception ex) { + this.error = ex; + } + + public long getFirstCallTime() { + return firstCallTime; + } + public void setFirstCallTime(long t) { + firstCallTime = t; + } + public long getAverageTotalLoopTime(){ + return averageTotalLoopTime; + } + public void setAverageTotalLoopTime(long t) { + averageTotalLoopTime = t; + } + + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTestSet.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTestSet.java new file mode 100644 index 000000000..6fc6e8d3d --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ConformanceTestSet.java @@ -0,0 +1,180 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.conformance; + +import java.io.File; +import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.FileVisitor; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +/** + * ConformanceTestSet represents a collection of ConformanceTests ordered by the test name. It has methods for + * scanning a directory to generate an ordered set. + * + * @version $Revision: 1.1 $ + */ +public class ConformanceTestSet { + private static final Logger logger = FlexLogger.getLogger(ConformanceTestSet.class); + private List listConformanceTests = new ArrayList<>(); + + protected List getListConformanceTests() { + return this.listConformanceTests; + } + + protected ConformanceTestSet() { + + } + + private static String getTestName(String fileName, int itemPos) { + return (itemPos == 0 ? "NULL" : fileName.substring(0, itemPos)); + } + + private static String getTestName(File file) { + String fileName = file.getName(); + int itemPos = fileName.indexOf("Policy"); + if (itemPos >= 0) { + return getTestName(fileName, itemPos); + } else if ((itemPos = fileName.indexOf("Request")) >= 0) { + return getTestName(fileName, itemPos); + } else if ((itemPos = fileName.indexOf("Response")) >= 0) { + return getTestName(fileName, itemPos); + } else if ((itemPos = fileName.indexOf("Repository")) >= 0) { + return getTestName(fileName, itemPos); + } else { + return null; + } + } + + public static ConformanceTestSet loadDirectory(File fileDir) throws IOException { + final Map mapConformanceTests = new HashMap(); + + Files.walkFileTree(fileDir.toPath(), new FileVisitor() { + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + logger.info("Scanning directory " + dir.getFileName()); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + File fileVisited = file.toFile(); + String fileName = fileVisited.getName(); + if (fileName.endsWith(".xml") || fileName.endsWith(".properties")) { + String testName = getTestName(fileVisited); + if (testName != null) { + ConformanceTest conformanceTest = mapConformanceTests.get(testName); + if (conformanceTest == null) { + logger.info("Added test " + testName); + conformanceTest = new ConformanceTest(testName); + mapConformanceTests.put(testName, conformanceTest); + } + if (fileName.endsWith("Policy.xml")) { + conformanceTest.getRepository().addRootPolicy(fileVisited); + } else if (fileName.endsWith("Repository.properties")) { + conformanceTest.getRepository().load(fileVisited); + } else if (fileName.endsWith("Request.xml")) { + conformanceTest.setRequest(fileVisited); + } else if (fileName.endsWith("Response.xml")) { + conformanceTest.setResponse(fileVisited); + } + } + } + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { + logger.warn("Skipped " + file.getFileName()); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + return FileVisitResult.CONTINUE; + } + }); + + /* + * Sort the keyset and pull out the tests that have the required components + */ + List listTestNames = new ArrayList<>(); + listTestNames.addAll(mapConformanceTests.keySet()); + Collections.sort(listTestNames); + + ConformanceTestSet conformanceTestSet = new ConformanceTestSet(); + Iterator iterTestNames = listTestNames.iterator(); + while (iterTestNames.hasNext()) { + ConformanceTest conformanceTest = mapConformanceTests.get(iterTestNames.next()); + if (conformanceTest.isComplete()) { + conformanceTestSet.addConformanceTest(conformanceTest); + logger.debug("Added conformance test " + conformanceTest.getTestName()); + } else { + logger.warn("Incomplete conformance test " + conformanceTest.getTestName()); + } + } + + return conformanceTestSet; + + } + + public Iterator getConformanceTests() { + return this.listConformanceTests.iterator(); + } + + public void addConformanceTest(ConformanceTest conformanceTest) { + this.listConformanceTests.add(conformanceTest); + } + + public void addConformanceTestSet(ConformanceTestSet conformanceTestSet) { + this.listConformanceTests.addAll(conformanceTestSet.getListConformanceTests()); + } + + public static void main(String[] args) { + for (String dir : args) { + try { + ConformanceTestSet conformanceTestSet = ConformanceTestSet.loadDirectory(new File(dir)); + Iterator iterConformanceTests = conformanceTestSet.getConformanceTests(); + if (iterConformanceTests == null) { + System.out.println("No tests found in " + dir); + } else { + System.out.println("Tests found in " + dir); + while (iterConformanceTests.hasNext()) { + System.out.println(iterConformanceTests.next().toString()); + } + } + } catch (Exception ex) { + ex.printStackTrace(System.err); + } + } + } +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ResponseMatchResult.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ResponseMatchResult.java new file mode 100644 index 000000000..4c7423022 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ResponseMatchResult.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.conformance; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +import com.att.research.xacml.api.Response; +import com.att.research.xacml.api.Result; + +/** + * ResponseMatchResult provides information about how a {@link com.att.research.xacml.api.Response} object matches + * another Response object. + * + * @version $Revision: 1.1 $ + */ +public class ResponseMatchResult { + private List resultMatchResults = new ArrayList<>(); + + private boolean bAssociatedAdviceMatches = true; + private boolean bAttributesMatch = true; + private boolean bDecisionsMatch = true; + private boolean bStatusCodesMatch = true; + private boolean bObligationsMatch = true; + private boolean bPolicyIdentifiersMatch = true; + private boolean bPolicySetIdentifiersMatch = true; + private boolean bNumResultsMatch = true; + private boolean bUnknownFunction; + + protected void addResultMatchResult(ResultMatchResult resultMatchResult) { + this.resultMatchResults.add(resultMatchResult); + this.bAssociatedAdviceMatches = resultMatchResult.associatedAdviceMatches() && this.bAssociatedAdviceMatches; + this.bAttributesMatch = resultMatchResult.attributesMatch() && this.bAttributesMatch; + this.bDecisionsMatch = resultMatchResult.decisionsMatch() && this.bDecisionsMatch; + this.bStatusCodesMatch = resultMatchResult.statusCodesMatch() && this.bStatusCodesMatch; + this.bObligationsMatch = resultMatchResult.obligationsMatch() && this.bObligationsMatch; + this.bPolicyIdentifiersMatch = resultMatchResult.policyIdentifiersMatch() && this.bPolicyIdentifiersMatch; + this.bPolicySetIdentifiersMatch = resultMatchResult.policySetIdentifiersMatch() && this.bPolicySetIdentifiersMatch; + this.bUnknownFunction = resultMatchResult.unknownFunction() || this.bUnknownFunction; + } + + protected void setNumResultsMatch(boolean b) { + this.bNumResultsMatch = b; + } + + public ResponseMatchResult() { + } + + public static ResponseMatchResult newInstance(Response response1, Response response2) { + ResponseMatchResult responseMatchResult = new ResponseMatchResult(); + + Collection listResultsResponse1 = response1.getResults(); + Collection listResultsResponse2 = response2.getResults(); + if (listResultsResponse1.size() == 1 && listResultsResponse2.size() == 1) { + /* + * Just add a single ResultMatchResult comparing the results in the two responses + */ + responseMatchResult.addResultMatchResult(ResultMatchResult.newInstance(listResultsResponse1.iterator().next(), listResultsResponse2.iterator().next())); + } else { + /* + * Iterate over all of the results in the two responses and match them + */ + Iterator iterResponse1Results = listResultsResponse1.iterator(); + Iterator iterResponse2Results = listResultsResponse2.iterator(); + while ((iterResponse1Results != null && iterResponse1Results.hasNext()) || (iterResponse2Results != null && iterResponse2Results.hasNext())) { + Result result1 = (iterResponse1Results != null && iterResponse1Results.hasNext() ? iterResponse1Results.next() : null); + Result result2 = (iterResponse2Results != null && iterResponse2Results.hasNext() ? iterResponse2Results.next() : null); + if ((result1 == null || result2 == null) && responseMatchResult.numResultsMatch()) { + responseMatchResult.setNumResultsMatch(false); + } + responseMatchResult.addResultMatchResult(ResultMatchResult.newInstance(result1, result2)); + } + } + return responseMatchResult; + } + + public Iterator getResultMatchResults() { + return this.resultMatchResults.iterator(); + } + + public boolean numResultsMatch() { + return this.bNumResultsMatch; + } + + public boolean associatedAdviceMatches() { + return this.bAssociatedAdviceMatches; + } + + public boolean attributesMatch() { + return this.bAttributesMatch; + } + + public boolean decisionsMatch() { + return this.bDecisionsMatch; + } + + public boolean obligationsMatch() { + return this.bObligationsMatch; + } + + public boolean policyIdentifiersMatch() { + return this.bPolicyIdentifiersMatch; + } + + public boolean policySetIdentifiersMatch() { + return this.bPolicySetIdentifiersMatch; + } + + public boolean statusCodesMatch() { + return this.bStatusCodesMatch; + } + + public boolean unknownFunction() { + return this.bUnknownFunction; + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ResultMatchResult.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ResultMatchResult.java new file mode 100644 index 000000000..fd6bf7103 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/conformance/ResultMatchResult.java @@ -0,0 +1,136 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.conformance; + +import com.att.research.xacml.api.Result; +import com.att.research.xacml.std.StdStatusCode; +import com.att.research.xacml.util.ListUtil; + +/** + * ResultMatchResult provides information about how well a {@link com.att.research.xacml.api.Result} object matches + * another Result object. + * + * @version $Revision: 1.1 $ + */ +public class ResultMatchResult { + private boolean bAssociatedAdviceMatches = true; + private boolean bAttributesMatch = true; + private boolean bDecisionsMatch = true; + private boolean bObligationsMatch = true; + private boolean bPolicyIdentifiersMatch = true; + private boolean bPolicySetIdentifiersMatch = true; + private boolean bStatusCodesMatch = true; + private boolean bUnknownFunction = false; + + protected void setAssociatedAdviceMatches(boolean b) { + this.bAssociatedAdviceMatches = b; + } + protected void setAttributesMatch(boolean b) { + this.bAttributesMatch = b; + } + protected void setDecisionsMatch(boolean b) { + this.bDecisionsMatch = b; + } + protected void setObligationsMatch(boolean b) { + this.bObligationsMatch = b; + } + protected void setPolicyIdentifiersMatch(boolean b) { + this.bPolicyIdentifiersMatch = b; + } + protected void setPolicySetIdentifiersMatch(boolean b) { + this.bPolicySetIdentifiersMatch = b; + } + protected void setStatusCodesMatch(boolean b) { + this.bStatusCodesMatch = b; + } + protected void setUnknownFunction(boolean b) { + this.bUnknownFunction = b; + } + + public ResultMatchResult() { + } + + public static ResultMatchResult newInstance(Result result1, Result result2) { + ResultMatchResult resultMatchResult = new ResultMatchResult(); + if (result2 != null && result2.getStatus() != null && + result2.getStatus().getStatusCode().equals(StdStatusCode.STATUS_CODE_PROCESSING_ERROR) && + result2.getStatus().getStatusMessage() != null && + result2.getStatus().getStatusMessage().contains("Unknown Function") + ) { + resultMatchResult.setUnknownFunction(true); + } + if (result1 == null || result2 == null) { + resultMatchResult.setAssociatedAdviceMatches(false); + resultMatchResult.setAttributesMatch(false); + resultMatchResult.setDecisionsMatch(false); + resultMatchResult.setObligationsMatch(false); + resultMatchResult.setPolicyIdentifiersMatch(false); + resultMatchResult.setPolicySetIdentifiersMatch(false); + resultMatchResult.setStatusCodesMatch(false); + } else { + resultMatchResult.setAssociatedAdviceMatches(ListUtil.equalsAllowNulls(result1.getAssociatedAdvice(), result2.getAssociatedAdvice())); + resultMatchResult.setAttributesMatch(ListUtil.equalsAllowNulls(result1.getAttributes(), result2.getAttributes())); + resultMatchResult.setDecisionsMatch(result1.getDecision() == result2.getDecision()); + resultMatchResult.setObligationsMatch(ListUtil.equalsAllowNulls(result1.getObligations(), result2.getObligations())); + resultMatchResult.setPolicyIdentifiersMatch(ListUtil.equalsAllowNulls(result1.getPolicyIdentifiers(), result2.getPolicyIdentifiers())); + resultMatchResult.setPolicySetIdentifiersMatch(ListUtil.equalsAllowNulls(result1.getPolicySetIdentifiers(), result2.getPolicySetIdentifiers())); + if (result1.getStatus() == null || result1.getStatus().getStatusCode() == null || result2.getStatus() == null || result2.getStatus().getStatusCode() == null) { + resultMatchResult.setStatusCodesMatch(false); + } else { + resultMatchResult.setStatusCodesMatch(result1.getStatus().getStatusCode().equals(result2.getStatus().getStatusCode())); + } + } + return resultMatchResult; + } + + public boolean associatedAdviceMatches() { + return this.bAssociatedAdviceMatches; + } + + public boolean attributesMatch() { + return this.bAttributesMatch; + } + + public boolean decisionsMatch() { + return this.bDecisionsMatch; + } + + public boolean obligationsMatch() { + return this.bObligationsMatch; + } + + public boolean policyIdentifiersMatch() { + return this.bPolicyIdentifiersMatch; + } + + public boolean policySetIdentifiersMatch() { + return this.bPolicySetIdentifiersMatch; + } + + public boolean statusCodesMatch() { + return this.bStatusCodesMatch; + } + + public boolean unknownFunction() { + return this.bUnknownFunction; + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/CustomDataTypeFactory.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/CustomDataTypeFactory.java new file mode 100644 index 000000000..82a2e3ec5 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/CustomDataTypeFactory.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.custom; + +import java.util.HashMap; +import java.util.Map; + +import com.att.research.xacml.api.DataType; +import com.att.research.xacml.api.DataTypeFactory; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.std.datatypes.DataTypes; + +public class CustomDataTypeFactory extends DataTypeFactory { + private static final Map> mapIdentifiersToDataTypes = new HashMap<>(); + private static boolean mapNeedsInit = true; + + public static final DataTypePrivateKey DT_PRIVATEKEY = DataTypePrivateKey.newInstance(); + public static final DataTypePublicKey DT_PUBLICKEY = DataTypePublicKey.newInstance(); + + private static void registerDataType(DataType dataType) { + if (dataType != null && dataType.getId() != null) { + mapIdentifiersToDataTypes.put(dataType.getId(), dataType); + } + } + + private static void initMap() { + if (mapNeedsInit) { + synchronized(mapIdentifiersToDataTypes) { + if (mapNeedsInit) { + registerDataType(DataTypes.DT_ANYURI); + registerDataType(DataTypes.DT_BASE64BINARY); + registerDataType(DataTypes.DT_BOOLEAN); + registerDataType(DataTypes.DT_DATE); + registerDataType(DataTypes.DT_DATETIME); + registerDataType(DataTypes.DT_DAYTIMEDURATION); + registerDataType(DataTypes.DT_DNSNAME); + registerDataType(DataTypes.DT_DOUBLE); + registerDataType(DataTypes.DT_HEXBINARY); + registerDataType(DataTypes.DT_INTEGER); + registerDataType(DataTypes.DT_IPADDRESS); + registerDataType(DataTypes.DT_RFC822NAME); + registerDataType(DataTypes.DT_STRING); + registerDataType(DataTypes.DT_TIME); + registerDataType(DataTypes.DT_X500NAME); + registerDataType(DataTypes.DT_XPATHEXPRESSION); + registerDataType(DataTypes.DT_YEARMONTHDURATION); + // + // These are the custom data types! + // + registerDataType(DT_PRIVATEKEY); + registerDataType(DT_PUBLICKEY); + // + // Done + // + mapNeedsInit = false; + } + } + } + } + + public CustomDataTypeFactory() { + initMap(); + } + + @Override + public DataType getDataType(Identifier dataTypeId) { + return mapIdentifiersToDataTypes.get(dataTypeId); + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/CustomFunctionDefinitionFactory.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/CustomFunctionDefinitionFactory.java new file mode 100644 index 000000000..017edad1a --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/CustomFunctionDefinitionFactory.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.custom; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.util.HashMap; +import java.util.Map; + +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacmlatt.pdp.policy.FunctionDefinition; +import com.att.research.xacmlatt.pdp.policy.FunctionDefinitionFactory; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.FunctionDefinitionBagOneAndOnly; + +public class CustomFunctionDefinitionFactory extends FunctionDefinitionFactory { + private static Map mapFunctionDefinitions = new HashMap<>(); + private static boolean needMapInit = true; + + public static final Identifier ID_FUNCTION_PRIVATEKEY_ONE_AND_ONLY = new IdentifierImpl("urn:com:att:research:xacml:custom:function:3.0:rsa:privatekey-one-and-only"); + public static final Identifier ID_FUNCTION_PUBLICKEY_ONE_AND_ONLY = new IdentifierImpl("urn:com:att:research:xacml:custom:function:3.0:rsa:publickey-one-and-only"); + + public static final FunctionDefinition FD_PRIVATEKEY_ONE_AND_ONLY = new FunctionDefinitionBagOneAndOnly(ID_FUNCTION_PRIVATEKEY_ONE_AND_ONLY, DataTypePrivateKey.newInstance()); + public static final FunctionDefinition FD_PUBLICKEY_ONE_AND_ONLY = new FunctionDefinitionBagOneAndOnly(ID_FUNCTION_PUBLICKEY_ONE_AND_ONLY, DataTypePublicKey.newInstance()); + + private static void register(FunctionDefinition functionDefinition) { + mapFunctionDefinitions.put(functionDefinition.getId(), functionDefinition); + } + + private static void initMap() { + if (needMapInit) { + synchronized(mapFunctionDefinitions) { + if (needMapInit) { + needMapInit = false; + Field[] declaredFields = StdFunctions.class.getDeclaredFields(); + for (Field field : declaredFields) { + if (Modifier.isStatic(field.getModifiers()) && + field.getName().startsWith(StdFunctions.FD_PREFIX) && + FunctionDefinition.class.isAssignableFrom(field.getType()) && + Modifier.isPublic(field.getModifiers()) + ) { + try { + register((FunctionDefinition)(field.get(null))); + } catch (IllegalAccessException ex) { + + } + } + } + // + // Our custom function + // + register(FunctionDefinitionDecrypt.newInstance()); + register(FD_PRIVATEKEY_ONE_AND_ONLY); + register(FD_PUBLICKEY_ONE_AND_ONLY); + } + } + } + } + + public CustomFunctionDefinitionFactory() { + initMap(); + } + + @Override + public FunctionDefinition getFunctionDefinition(Identifier functionId) { + return mapFunctionDefinitions.get(functionId); + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/DataTypePrivateKey.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/DataTypePrivateKey.java new file mode 100644 index 000000000..36fd9e725 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/DataTypePrivateKey.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.custom; + +import java.security.PrivateKey; + +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.datatypes.DataTypeBase; + +public class DataTypePrivateKey extends DataTypeBase { + public static final Identifier DT_PRIVATEKEY = new IdentifierImpl("urn:com:att:research:xacml:custom:3.0:rsa:private"); + private static final DataTypePrivateKey singleInstance = new DataTypePrivateKey(); + + private DataTypePrivateKey() { + super(DT_PRIVATEKEY, PrivateKey.class); + } + + public static DataTypePrivateKey newInstance() { + return singleInstance; + } + + @Override + public PrivateKey convert(Object source) throws DataTypeException { + if (source == null || (source instanceof PrivateKey) ) { + return (PrivateKey) source; + } else if (source instanceof byte[]) { + return (PrivateKey) source; + } else if (source instanceof String) { + return (PrivateKey) (Object) ((String) source).getBytes(); + } + throw new DataTypeException(this, "Failed to convert \"" + source.getClass().getCanonicalName()); + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/DataTypePublicKey.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/DataTypePublicKey.java new file mode 100644 index 000000000..b73274785 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/DataTypePublicKey.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.custom; + +import java.security.PublicKey; + +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.datatypes.DataTypeBase; + +public class DataTypePublicKey extends DataTypeBase { + public static final Identifier DT_PUBLICKEY = new IdentifierImpl("urn:com:att:research:xacml:custom:3.0:rsa:public"); + private static final DataTypePublicKey singleInstance = new DataTypePublicKey(); + + public DataTypePublicKey() { + super(DT_PUBLICKEY, PublicKey.class); + } + + public static DataTypePublicKey newInstance() { + return singleInstance; + } + + @Override + public PublicKey convert(Object source) throws DataTypeException { + if (source == null || (source instanceof PublicKey) ) { + return (PublicKey) source; + } else if (source instanceof byte[]) { + return (PublicKey) source; + } else if (source instanceof String) { + return (PublicKey) (Object) ((String) source).getBytes(); + } + throw new DataTypeException(this, "Failed to convert \"" + source.getClass().getCanonicalName()); + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/FunctionDefinitionDecrypt.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/FunctionDefinitionDecrypt.java new file mode 100644 index 000000000..6d34e6334 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/FunctionDefinitionDecrypt.java @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.custom; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.util.List; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; + +import com.att.research.xacml.api.DataType; +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdStatus; +import com.att.research.xacml.std.StdStatusCode; +import com.att.research.xacml.std.datatypes.DataTypeHexBinary; +import com.att.research.xacml.std.datatypes.DataTypeString; +import com.att.research.xacml.std.datatypes.HexBinary; +import com.att.research.xacmlatt.pdp.eval.EvaluationContext; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionDefinition; +import com.att.research.xacmlatt.pdp.std.functions.ConvertedArgument; + +public class FunctionDefinitionDecrypt implements FunctionDefinition { + public static final Identifier FD_RSA_DECRYPT = new IdentifierImpl("urn:com:att:research:xacml:custom:function:3.0:rsa:decrypt"); + private static final FunctionDefinitionDecrypt singleInstance = new FunctionDefinitionDecrypt(); + + public static FunctionDefinitionDecrypt newInstance() { + return singleInstance; + } + + @Override + public Identifier getId() { + return FD_RSA_DECRYPT; + } + + @Override + public Identifier getDataTypeId() { + return XACML3.ID_DATATYPE_STRING; + } + + @Override + public boolean returnsBag() { + return false; + } + + @Override + public ExpressionResult evaluate(EvaluationContext evaluationContext, List arguments) { + if (arguments == null || arguments.size() < 2) { + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, expecting 2 arguments.")); + } + // + // What is the first argument? + // + FunctionArgument arg0 = arguments.get(0); + if (arg0.isBag()) { + // + // We don't support bags right now + // + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, not expecting a bag for argument 0.")); + } + if (arg0.getValue().getDataTypeId().equals(XACML3.ID_DATATYPE_HEXBINARY) == false) { + // + // Should be a String + // + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, expected a Hex Binary for argument 0.")); + } + // + // Convert the argument + // + ConvertedArgument data = new ConvertedArgument(arg0, DataTypeHexBinary.newInstance(), false); + if (! data.isOk()) { + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, argument 0 failed to convert to Hex Binary.")); + } + // + // Ok - check the 2nd argument + // + FunctionArgument arg1 = arguments.get(1); + if (arg1.isBag()) { + // + // We don't support bags right now + // + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, not expecting a bag for argument 1.")); + } + if (arg1.getValue().getDataTypeId().equals(DataTypePrivateKey.DT_PRIVATEKEY) || + arg1.getValue().getDataTypeId().equals(DataTypePublicKey.DT_PUBLICKEY)) { + // + // Ok - let's try to decrypt + // + Cipher cipher; + try { + cipher = Cipher.getInstance("RSA"); + if (arg1.getValue().getDataTypeId().equals(DataTypePrivateKey.DT_PRIVATEKEY)) { + // + // Using the private key + // + DataType pkDatatype = DataTypePrivateKey.newInstance(); + ConvertedArgument privateKey = new ConvertedArgument(arg1, pkDatatype, false); + if ( ! privateKey.isOk()) { + return ExpressionResult.newError(new StdStatus(privateKey.getStatus().getStatusCode(), "Decrypt: " + privateKey.getStatus().getStatusMessage())); + } + // + // Setup decryption + // + cipher.init(Cipher.DECRYPT_MODE, privateKey.getValue()); + } else if (arg1.getValue().getDataTypeId().equals(DataTypePublicKey.DT_PUBLICKEY)) { + // + // Using the private key + // + DataType pkDatatype = DataTypePublicKey.newInstance(); + ConvertedArgument publicKey = new ConvertedArgument(arg1, pkDatatype, false); + if ( ! publicKey.isOk()) { + return ExpressionResult.newError(new StdStatus(publicKey.getStatus().getStatusCode(), "Decrypt: " + publicKey.getStatus().getStatusMessage())); + } + // + // Setup decryption + // + cipher.init(Cipher.DECRYPT_MODE, publicKey.getValue()); + } + // + // Do the decryption + // + byte[] decryptedData = cipher.doFinal(data.getValue().getData()); + String decryptedString = new String(decryptedData); + // + // All good, return the decrypted string + // + return ExpressionResult.newSingle(DataTypeString.newInstance().createAttributeValue(decryptedString)); + } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | DataTypeException e) { + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed: " + e.getLocalizedMessage())); + } + } + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, expecting public/private key datatype for argument 1.")); + } + +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/TestBase.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/TestBase.java new file mode 100644 index 000000000..2ccf15682 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/TestBase.java @@ -0,0 +1,1082 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.custom; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.GnuParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.apache.commons.io.IOUtils; +import org.apache.http.entity.ContentType; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.DataType; +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.api.DataTypeFactory; +import com.att.research.xacml.api.Decision; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.RequestAttributes; +import com.att.research.xacml.api.Response; +import com.att.research.xacml.api.Result; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.api.pdp.PDPEngineFactory; +import com.att.research.xacml.api.pdp.PDPException; +import com.att.research.xacml.api.pep.PEPException; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdAttributeValue; +import com.att.research.xacml.std.StdMutableAttribute; +import com.att.research.xacml.std.StdMutableRequest; +import com.att.research.xacml.std.StdMutableRequestAttributes; +import com.att.research.xacml.std.dom.DOMRequest; +import com.att.research.xacml.std.dom.DOMResponse; +import com.att.research.xacml.std.dom.DOMStructureException; +import com.att.research.xacml.std.json.JSONRequest; +import com.att.research.xacml.std.json.JSONResponse; +import com.att.research.xacml.std.json.JSONStructureException; +import com.att.research.xacml.util.FactoryException; +import com.att.research.xacml.util.XACMLProperties; +import com.google.common.base.Splitter; +import com.google.common.collect.Lists; + +/** + * This is a base class for setting up a test environment. Using properties files, it contains the + * necessary information for + * 1. defining and providing attributes + * 2. defining and instantiating the PDP engine + * 3. creating PEP requests and calling the PDP engine + * + * + */ +public class TestBase extends SimpleFileVisitor { + private static final Logger logger = FlexLogger.getLogger(TestBase.class); + + public class HelpException extends Exception { + private static final long serialVersionUID = 1L; + + } + + /** + * This private class holds information for properties defined for attribute + * generation. The user can configure the properties file such that attributes + * can be automatically generated and added into each request. + * + * + */ + class Generator { + Path file; + InputStream is; + BufferedReader reader; + List attributes = new ArrayList<>(); + + public Generator(Path path) { + this.file = path; + } + + /** + * read - reads in the next line of data + * + * @return String - a line from the csv containing attribute data + */ + public String read() { + String str = null; + if (is == null) { + try { + is = Files.newInputStream(file); + } catch (IOException e) { + logger.error(e); + return null; + } + } + if (reader == null) { + reader = new BufferedReader(new InputStreamReader(this.is)); + } + try { + str = reader.readLine(); + if (str == null) { + // + // No more strings, close up + // + this.close(); + } + if (logger.isDebugEnabled()) { + logger.debug(str); + } + } catch (IOException e) { + logger.error(e); + } + return str; + } + + public void close() { + if (this.reader != null) { + try { + this.reader.close(); + } catch (IOException idontcare) { + } finally { + this.reader = null; + this.is = null; + } + } + } + + } + + public static final String PROP_GENERATOR = "xacml.attribute.generator"; + + public static final String OPTION_HELP = "help"; + public static final String OPTION_TESTDIR = "dir"; + public static final String OPTION_TESTREST = "rest"; + public static final String OPTION_TESTURL = "url"; + public static final String OPTION_TESTOUTPUT = "output"; + public static final String OPTION_LOOP = "loop"; + public static final String OPTION_TESTNUMBERS = "testNumbers"; + + public static final String DEFAULT_RESTURL = "https://localhost:8080/pdp/"; // Modified for test purpose. Port no. 8443 to 8080 + + public static Options options = new Options(); + static { + options.addOption(new Option(OPTION_HELP, false, "Prints help.")); + options.addOption(new Option(OPTION_TESTDIR, true, "Directory path where all the test properties and data are located.")); + options.addOption(new Option(OPTION_TESTREST, false, "Test against RESTful PDP.")); + options.addOption(new Option(OPTION_TESTURL, true, "URL to the RESTful PDP. Default is " + DEFAULT_RESTURL)); + options.addOption(new Option(OPTION_TESTOUTPUT, true, "Specify a different location for dumping responses.")); + options.addOption(new Option(OPTION_LOOP, true, "Number of times to loop through the tests. Default is 1. A value of -1 runs indefinitely.")); + options.addOption(new Option(OPTION_TESTNUMBERS, true, "Comma-separated list of numbers found in the names of the test files to be run. Numbers must exactly match the file name, e.g. '02'. Used to limit testing to specific set of tests.")); + } + + protected String directory = null; + protected Path output = null; + protected boolean isREST; + protected URL restURL = null; + protected int loop = 1; + protected PDPEngine engine = null; + protected List generators = new ArrayList<>(); + protected static DataTypeFactory dataTypeFactory = null; + + private long permits = 0; + private long denies = 0; + private long notapplicables = 0; + private long indeterminates = 0; + + private long expectedPermits = 0; + private long expectedDenies = 0; + private long expectedNotApplicables = 0; + private long expectedIndeterminates = 0; + + private long generatedpermits = 0; + private long generateddenies = 0; + private long generatednotapplicables = 0; + private long generatedindeterminates = 0; + + private long responseMatches = 0; + private long responseNotMatches = 0; + + private String[] testNumbersArray = null; + + protected final Pattern pattern = Pattern.compile("Request[.]\\d+[.](Permit|Deny|NA|Indeterminate|Generate|Unknown)\\.(json|xml)"); + + public static boolean isJSON(Path file) { + return file.toString().endsWith(".json"); + } + + public static boolean isXML(Path file) { + return file.toString().endsWith(".xml"); + } + + public TestBase(String[] args) throws ParseException, MalformedURLException, HelpException { + // + // Finish Initialization + // + this.restURL = new URL(DEFAULT_RESTURL); + // + // Parse arguments + // + this.parseCommands(args); + } + + /** + * Parse in the command line arguments that the following parameters: + * + * @param args - command line arguments + * @throws ParseException + * @throws MalformedURLException + * @throws HelpException + */ + protected void parseCommands(String[] args) throws ParseException, MalformedURLException, HelpException { + // + // Parse the command line options + // + CommandLine cl; + cl = new GnuParser().parse(options, args); + // + // Check for what we have + // + if (cl.hasOption(OPTION_HELP)) { + new HelpFormatter().printHelp("Usage: -dir testdirectory OPTIONS", + options); + throw new HelpException(); + } + if (cl.hasOption(OPTION_TESTDIR)) { + this.directory = cl.getOptionValue(OPTION_TESTDIR); + } else { + throw new IllegalArgumentException("You must specify a test directory. -dir path/to/some/where"); + } + if (cl.hasOption(OPTION_TESTREST)) { + this.isREST = true; + } else { + this.isREST = false; + } + if (cl.hasOption(OPTION_TESTURL)) { + this.restURL = new URL(cl.getOptionValue(OPTION_TESTURL)); + } + if (cl.hasOption(OPTION_TESTOUTPUT)) { + this.output = Paths.get(cl.getOptionValue(OPTION_TESTOUTPUT)); + } else { + this.output = Paths.get(this.directory, "results"); + } + if (cl.hasOption(OPTION_LOOP)) { + this.loop = Integer.parseInt(cl.getOptionValue(OPTION_LOOP)); + } + if (cl.hasOption(OPTION_TESTNUMBERS)) { + String testNumberString = cl.getOptionValue(OPTION_TESTNUMBERS); + testNumbersArray = testNumberString.split(","); + // + // reset strings to include dots so they exactly match pattern in file name + // + for (int i = 0; i < testNumbersArray.length; i++) { + testNumbersArray[i] = "." + testNumbersArray[i] + "."; + } + } + } + + /** + * Using the command line options that were parsed, configures our test instance. + * + * @throws FactoryException + */ + protected void configure() throws FactoryException { + // + // Setup the xacml.properties file + // + if (this.directory == null) { + throw new IllegalArgumentException("Must supply a path to a test directory."); + } + Path pathDir = Paths.get(this.directory, "xacml.properties"); + if (Files.notExists(pathDir)) { + throw new IllegalArgumentException(pathDir.toString() + " does not exist."); + } + // + // Set it as the System variable so the XACML factories know where the properties are + // loaded from. + // + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, pathDir.toString()); + // + // Now we can create the data type factory + // + dataTypeFactory = DataTypeFactory.newInstance(); + // + // Load in what generators we are to create + // + String generators = XACMLProperties.getProperty(PROP_GENERATOR); + if (generators != null) { + // + // Parse the generators + // + for (String generator : Splitter.on(',').trimResults().omitEmptyStrings().split(generators)) { + this.configureGenerator(generator); + } + } + // + // If we are embedded, create our engine + // + if (this.isREST == false) { + PDPEngineFactory factory = PDPEngineFactory.newInstance(); + this.engine = factory.newEngine(); + } + // + // Remove all the responses from the results directory + // + this.removeResults(); + } + + /** + * Removes all the Response* files from the results directory. + * + */ + public void removeResults() { + try { + // + // Determine where the results are supposed to be written to + // + Path resultsPath; + if (this.output != null) { + resultsPath = this.output; + } else { + resultsPath = Paths.get(this.directory.toString(), "results"); + } + // + // Walk the files + // + Files.walkFileTree(resultsPath, new SimpleFileVisitor() { + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + if (file.getFileName().toString().startsWith("Response")) { + Files.delete(file); + } + return super.visitFile(file, attrs); + } + }); + } catch (IOException e) { + logger.error("Failed to removeRequests from " + this.directory + " " + e); + } + } + + /** + * Configure's a specific generator instance from the properties file. + * + * @param generator + */ + protected void configureGenerator(String generator) { + String prefix = PROP_GENERATOR + "." + generator; + String file = XACMLProperties.getProperty(prefix + ".file"); + // + // Create a generator object + // + Generator gen = new Generator(Paths.get(this.directory, file)); + this.generators.add(gen); + // + // Grab attributes + // + String attributes = XACMLProperties.getProperty(prefix + ".attributes"); + for (String attribute : Splitter.on(',').trimResults().omitEmptyStrings().split(attributes)) { + String attributePrefix = prefix + ".attributes." + attribute; + // + // Create an attribute value. It is simply a placeholder for the field within + // the CSV that contains the actual attribute value. It mainly holds the data type + // + Identifier datatype = new IdentifierImpl(XACMLProperties.getProperty(attributePrefix + ".datatype")); + Integer field = Integer.parseInt(XACMLProperties.getProperty(attributePrefix + ".field")); + StdAttributeValue value = new StdAttributeValue<>(datatype, field); + // + // Get the rest of the attribute properties + // + Identifier category = new IdentifierImpl(XACMLProperties.getProperty(attributePrefix + ".category")); + Identifier id = new IdentifierImpl(XACMLProperties.getProperty(attributePrefix + ".id")); + String issuer = XACMLProperties.getProperty(attributePrefix + ".issuer"); + boolean include = Boolean.parseBoolean(XACMLProperties.getProperty(attributePrefix + ".include", "false")); + // + // Now we have a skeleton attribute + // + gen.attributes.add(new StdMutableAttribute(category, id, value, issuer, include)); + } + } + + /** + * This runs() the test instance. It first configure's itself and then walks the + * requests directory issue each request to the PDP engine. + * + * @throws IOException + * @throws FactoryException + * + */ + public void run() throws IOException, FactoryException { + // + // Configure ourselves + // + this.configure(); + // + // Loop and run + // + int runs = 1; + do { + long lTimeStart = System.currentTimeMillis(); + logger.info("Run number: " + runs); + // + // Walk the request directory + // + Files.walkFileTree(Paths.get(this.directory.toString(), "requests"), this); + long lTimeEnd = System.currentTimeMillis(); + logger.info("Run elapsed time: " + (lTimeEnd - lTimeStart) + "ms"); + // + // Dump the stats + // + this.dumpStats(); + this.resetStats(); + // + // Increment + // + runs++; + } while ((this.loop == -1 ? true : runs <= this.loop)); + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + // + // Sanity check the file name + // + Matcher matcher = this.pattern.matcher(file.getFileName().toString()); + if (matcher.matches()) { + // + // if user has limited which files to use, check that here + // + if (testNumbersArray != null) { + String fileNameString = file.getFileName().toString(); + boolean found = false; + for (String numberString : testNumbersArray) { + if (fileNameString.contains(numberString)) { + found = true; + break; + } + } + if (found == false) { + // + // this test is not in the list to be run, so skip it + // + return super.visitFile(file, attrs); + } + } + try { + // + // Pull what this request is supposed to be + // + String group = null; + int count = matcher.groupCount(); + if (count >= 1) { + group = matcher.group(count-1); + } + // + // Send it + // + this.sendRequest(file, group); + } catch (Exception e) { + logger.error(e); + logger.error("Exception Occured"+e); + } + } + return super.visitFile(file, attrs); + } + + /** + * When a request file is encountered, this method is called send the request to the PDP engine. It will also dump + * the response object. If the group equals "Generate", then it will loop and send the request with generated attributes + * until that list is empty. + * + * @param file - Request file. Eg. Request-01-Permit.json + * @param group - This is the parsed out string of the request file that defines if it is a Permit/Deny/Generate etc. + * @throws Exception + */ + protected void sendRequest(Path file, String group) throws Exception { + logger.info(file.toString()); + int requestCount = 0; + do { + // + // Generate the request + // + Request request = this.generateRequest(file, group); + // + // Was something generated? + // + if (request == null) { + // + // Get out of the loop + // + logger.info("NULL request generated."); + break; + } + logger.info(request); + // + // Call the PDP + // + Response response = this.callPDP(request); + // + // Process the response + // + this.processResponse(file, request, response, group, requestCount); + // + // Is this a generated request? + // + if (group.equals("Generate")) { + // + // Yes, increment counter and move + // on to the next generated request. + // + requestCount++; + } else { + // + // Nope, exit the loop + // + break; + } + } while (group.equals("Generate")); + } + + /** + * Sends the request object to the PDP engine. Either the embedded engine or the RESTful engine. + * + * @param request - XACML request object + * @return Response - returns the XACML response object + */ + protected Response callPDP(Request request) { + // + // Send it to the PDP + // + Response response = null; + if (this.isREST) { + try { + String jsonString = JSONRequest.toString(request, false); + // + // Call RESTful PDP + // + response = this.callRESTfulPDP(new ByteArrayInputStream(jsonString.getBytes())); + } catch (Exception e) { + logger.error("Error in sending RESTful request: " + e, e); + } + } else { + // + // Embedded call to PDP + // + long lTimeStart = System.currentTimeMillis(); + try { + response = this.engine.decide(request); + } catch (PDPException e) { + logger.error(e); + } + long lTimeEnd = System.currentTimeMillis(); + logger.info("Elapsed Time: " + (lTimeEnd - lTimeStart) + "ms"); + } + return response; + } + + /** + * Reads the request file into a Request object based on its type. + * + * If the request has "Generate" in its filename, then this function will add + * generated attributes into the request. + * + * @param file - Request file. Eg. Request-01-Permit.json + * @param group - This is the parsed out string of the request file that defines if it is a Permit/Deny/Generate etc. + * @return + * @throws JSONStructureException + * @throws DOMStructureException + * @throws PEPException + */ + protected Request generateRequest(Path file, String group) throws JSONStructureException, DOMStructureException, PEPException { + // + // Convert to a XACML Request Object + // + Request request = null; + if (TestBase.isJSON(file)) { + request = JSONRequest.load(file.toFile()); + } else if (TestBase.isXML(file)) { + request = DOMRequest.load(file.toFile()); + } + if (request == null) { + throw new PEPException("Invalid Request File: " + file.toString()); + } + // + // Only if this request has "Generate" + // Request.XX.Generate.[json|xml] + // + if (group.equals("Generate")) { + // + // Add attributes to it + // + request = this.onNextRequest(request); + } + // + // Done + // + return request; + } + + /** + * Called to add in generated attributes into the request. + * + * @param request + * @return + */ + protected Request onNextRequest(Request request) { + // + // If we have no generators, just return + // + if (this.generators.isEmpty()) { + return request; + } + // + // Copy the request attributes + // + List attributes = new ArrayList<>(); + for (RequestAttributes a : request.getRequestAttributes()) { + attributes.add(new StdMutableRequestAttributes(a)); + } + // + // Iterate the generators + // + for (Generator generator : this.generators) { + // + // Read a row in + // + String line = generator.read(); + // + // Was something read? + // + if (line == null) { + // + // No more rows to read, return null + // + return null; + } + // + // Split the line + // + List fields = Lists.newArrayList(Splitter.on(',').trimResults().split(line)); + // + // Now work on the attributes + // + for (StdMutableAttribute attribute : generator.attributes) { + // + // Grab the attribute holder, which holds the datatype and field. There should + // be only ONE object in the collection. + // + AttributeValue value = attribute.getValues().iterator().next(); + Integer field = (Integer) value.getValue(); + // + // Is the field number valid? + // + if (field >= fields.size()) { + logger.error("Not enough fields: " + field + "(" + fields.size() + ")"); + return null; + } + // + // Determine what datatype it is + // + DataType dataTypeExtended = dataTypeFactory.getDataType(value.getDataTypeId()); + if (dataTypeExtended == null) { + logger.error("Failed to determine datatype"); + return null; + } + // + // Create the attribute value + // + try { + AttributeValue attributeValue = dataTypeExtended.createAttributeValue(fields.get(field)); + // + // Create the attribute + // + StdMutableAttribute newAttribute = new StdMutableAttribute(attribute.getCategory(), + attribute.getAttributeId(), + attributeValue, + attribute.getIssuer(), + attribute.getIncludeInResults()); + boolean added = false; + for (StdMutableRequestAttributes a : attributes) { + // + // Does the category exist? + // + if (a.getCategory().equals(attribute.getCategory())) { + // + // Yes - add in the new attribute value + // + a.add(newAttribute); + added = true; + break; + } + } + if (added == false) { + // + // New category - create it and add it in + // + StdMutableRequestAttributes a = new StdMutableRequestAttributes(); + a.setCategory(newAttribute.getCategory()); + a.add(newAttribute); + attributes.add(a); + } + } catch (DataTypeException e) { + logger.error(e); + return null; + } + } + } + // + // Now form our final request + // + StdMutableRequest newRequest = new StdMutableRequest(); + newRequest.setCombinedDecision(request.getCombinedDecision()); + newRequest.setRequestDefaults(request.getRequestDefaults()); + newRequest.setReturnPolicyIdList(request.getReturnPolicyIdList()); + newRequest.setStatus(request.getStatus()); + for (StdMutableRequestAttributes a : attributes) { + newRequest.add(a); + } + return newRequest; + } + + /** + * This makes an HTTP POST call to a running PDP RESTful servlet to get a decision. + * + * @param file + * @return + */ + protected Response callRESTfulPDP(InputStream is) { + Response response = null; + HttpURLConnection connection = null; + try { + + // + // Open up the connection + // + connection = (HttpURLConnection) this.restURL.openConnection(); + connection.setRequestProperty("Content-Type", "application/json"); + // + // Setup our method and headers + // + connection.setRequestMethod("POST"); + 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); + // + // Send the request + // + try (OutputStream os = connection.getOutputStream()) { + IOUtils.copy(is, os); + } + // + // Do the connect + // + connection.connect(); + if (connection.getResponseCode() == 200) { + // + // Read the response + // + ContentType contentType = null; + try { + contentType = ContentType.parse(connection.getContentType()); + + if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_JSON.getMimeType())) { + response = JSONResponse.load(connection.getInputStream()); + } else if (contentType.getMimeType().equalsIgnoreCase(ContentType.APPLICATION_XML.getMimeType()) || + contentType.getMimeType().equalsIgnoreCase("application/xacml+xml") ) { + response = DOMResponse.load(connection.getInputStream()); + } else { + logger.error("unknown content-type: " + contentType); + } + + } catch (Exception e) { + String message = "Parsing Content-Type: " + connection.getContentType() + ", error=" + e.getMessage(); + logger.error(message, e); + } + + } else { + logger.error(connection.getResponseCode() + " " + connection.getResponseMessage()); + } + } catch (Exception e) { + logger.error(e); + } + + return response; + } + + /** + * This processes a response. Saves the response out to disk. If there is a corresponding response file for the request located + * in the "responses" sub-directory, then this method will compare that response file with what the engine returned to see if it + * matched. + * + * @param requestFile + * @param request + * @param response + * @param group + * @param count + * @throws Exception + */ + protected void processResponse(Path requestFile, Request request, Response response, String group, int count) throws Exception { + // + // Construct the output filename + // + Path responseFile = null; + Path resultFile = null; + int num = requestFile.getNameCount(); + if (num < 2) { + logger.error("Too few dir's in request filename."); + throw new Exception("Too few dir's in request filename. Format should be Request.[0-9]+.{Permit|Deny|NA|Indeterminate}.{json|xml}"); + } + String filename = requestFile.getFileName().toString(); + if (group.equals("Generate")) { + // + // Using count variable, construct a filename + // + // i.e. Response.03.Generate.{count}.json + // + filename = "Response" + filename.substring(filename.indexOf('.'), filename.lastIndexOf('.')) + String.format("%03d", count) + filename.substring(filename.lastIndexOf('.')); + } else { + // + // Construct filename + // + filename = "Response" + filename.substring(filename.indexOf('.')); + } + // + // Determine equivalent response file path + // + responseFile = Paths.get(requestFile.subpath(0, num - 2).toString(), "responses"); + if (Files.notExists(responseFile)) { + // + // Create it + // + logger.warn(responseFile.toString() + " does NOT exist, creating..."); + try { + Files.createDirectories(responseFile); + } catch (IOException e) { + logger.error(e); + throw new Exception("Cannot proceed without an output directory."); + } + } + responseFile = Paths.get(responseFile.toString(), filename); + // + // Determine path to write result file + // + if (this.output != null) { + // + // User specified an output path + // + resultFile = this.output; + } else { + // + // Default path + // + resultFile = Paths.get(requestFile.subpath(0, num - 2).toString(), "results"); + } + // + // Check if the path exists + // + if (Files.notExists(resultFile)) { + // + // Create it + // + logger.warn(resultFile.toString() + " does NOT exist, creating..."); + try { + Files.createDirectories(resultFile); + } catch (IOException e) { + logger.error(e); + throw new Exception("Cannot proceed without an output directory."); + } + } + // + // Add the filename to the path + // + resultFile = Paths.get(resultFile.toString(), filename); + // + // Check if there is an equivalent response in the response + // directory. If so, compare our response result with that one. + // + boolean succeeded = true; + if (responseFile != null && Files.exists(responseFile)) { + // + // Do comparison + // + Response expectedResponse = null; + if (TestBase.isJSON(responseFile)) { + expectedResponse = JSONResponse.load(responseFile); + } else if (TestBase.isXML(responseFile)) { + expectedResponse = DOMResponse.load(responseFile); + } + if (expectedResponse != null) { + // + // Do the compare + // + if (response == null) { + logger.error("NULL response returned."); + this.responseNotMatches++; + succeeded = false; + } else { + if (response.equals(expectedResponse)) { + logger.info("Response matches expected response."); + this.responseMatches++; + } else { + logger.error("Response does not match expected response."); + logger.error("Expected: "); + logger.error(expectedResponse.toString()); + this.responseNotMatches++; + succeeded = false; + } + } + } + } + // + // Write the response to the result file + // + logger.info("Request: " + requestFile.getFileName() + " response is: " + (response == null ? "null" : response.toString())); + if (resultFile != null && response != null) { + if (TestBase.isJSON(resultFile)) { + Files.write(resultFile, JSONResponse.toString(response, true).getBytes()); + } else if (TestBase.isXML(resultFile)) { + Files.write(resultFile, DOMResponse.toString(response, true).getBytes()); + } + } + // + // Stats + // + if (group.equals("Permit")) { + this.expectedPermits++; + } else if (group.equals("Deny")) { + this.expectedDenies++; + } else if (group.equals("NA")) { + this.expectedNotApplicables++; + } else if (group.equals("Indeterminate")) { + this.expectedIndeterminates++; + } + if (response != null) { + for (Result result : response.getResults()) { + Decision decision = result.getDecision(); + if (group.equals("Generate")) { + if (decision.equals(Decision.PERMIT)) { + this.generatedpermits++; + } else if (decision.equals(Decision.DENY)) { + this.generateddenies++; + } else if (decision.equals(Decision.NOTAPPLICABLE)) { + this.generatednotapplicables++; + } else if (decision.equals(Decision.INDETERMINATE)) { + this.generatedindeterminates++; + } + continue; + } + if (decision.equals(Decision.PERMIT)) { + this.permits++; + if (group.equals("Permit") == false) { + succeeded = false; + logger.error("Expected " + group + " got " + decision); + } + } else if (decision.equals(Decision.DENY)) { + this.denies++; + if (group.equals("Deny") == false) { + succeeded = false; + logger.error("Expected " + group + " got " + decision); + } + } else if (decision.equals(Decision.NOTAPPLICABLE)) { + this.notapplicables++; + if (group.equals("NA") == false) { + succeeded = false; + logger.error("Expected " + group + " got " + decision); + } + } else if (decision.equals(Decision.INDETERMINATE)) { + this.indeterminates++; + if (group.equals("Indeterminate") == false) { + succeeded = false; + logger.error("Expected " + group + " got " + decision); + } + } + } + } + if (succeeded) { + logger.info("REQUEST SUCCEEDED"); + } else { + logger.info("REQUEST FAILED"); + } + } + + protected void dumpStats() { + StringBuilder dump = new StringBuilder(); + dump.append(System.lineSeparator()); + dump.append("Permits: " + this.permits + " Expected: " + this.expectedPermits); + dump.append(System.lineSeparator()); + dump.append("Denies: " + this.denies + " Expected: " + this.expectedDenies); + dump.append(System.lineSeparator()); + dump.append("NA: " + this.notapplicables + " Expected: " + this.expectedNotApplicables); + dump.append(System.lineSeparator()); + dump.append("Indeterminates: " + this.indeterminates + " Expected: " + this.expectedIndeterminates); + dump.append(System.lineSeparator()); + dump.append("Generated Permits: " + this.generatedpermits); + dump.append(System.lineSeparator()); + dump.append("Generated Denies: " + this.generateddenies); + dump.append(System.lineSeparator()); + dump.append("Generated NA: " + this.generatednotapplicables); + dump.append(System.lineSeparator()); + dump.append("Generated Indeterminates: " + this.generatedindeterminates); + dump.append(System.lineSeparator()); + dump.append("Responses Matched: " + this.responseMatches); + dump.append(System.lineSeparator()); + dump.append("Responses NOT Matched: " + this.responseNotMatches); + + if (this.permits != this.expectedPermits || + this.denies != this.expectedDenies || + this.notapplicables != this.expectedNotApplicables || + this.indeterminates != this.expectedIndeterminates || + this.responseNotMatches > 0) { + logger.error(dump.toString()); + } else { + logger.info(dump.toString()); + } + } + + protected void resetStats() { + this.permits = 0; + this.denies = 0; + this.notapplicables = 0; + this.indeterminates = 0; + this.generatedpermits = 0; + this.generateddenies = 0; + this.generatednotapplicables = 0; + this.generatedindeterminates = 0; + this.responseMatches = 0; + this.responseNotMatches = 0; + } + + public static void main(String[] args) { + try { + new TestBase(args).run(); + } catch (ParseException | IOException | FactoryException e) { + logger.error(e); + } catch (HelpException e) { + } + } +} diff --git a/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/TestCustom.java b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/TestCustom.java new file mode 100644 index 000000000..e7a038814 --- /dev/null +++ b/ONAP-PDP/src/test/java/org/onap/policy/pdp/test/custom/TestCustom.java @@ -0,0 +1,392 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PDP + * ================================================================================ + * 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.pdp.test.custom; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.net.MalformedURLException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.InvalidKeyException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.util.ArrayList; +import java.util.List; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.GnuParser; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.ParseException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.DataType; +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.RequestAttributes; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.api.pep.PEPException; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdMutableAttribute; +import com.att.research.xacml.std.StdMutableRequest; +import com.att.research.xacml.std.StdMutableRequestAttributes; +import com.att.research.xacml.std.dom.DOMStructureException; +import com.att.research.xacml.std.json.JSONStructureException; +import com.att.research.xacml.util.FactoryException; + +/** + * TestCustom is an application that tests the extensibility and configurability of the AT&T XACML API. + * + * It creates a custom datatype definition factory that adds in custom data types for RSA + * PublicKey and PrivateKey. + * + * It creates a custom function definition factory that adds in custom decryption function for decrypting data. It + * also derives and loads custom functions for the RSA public/private key datatypes for the bag function: one-and-only. + * + * + */ +public class TestCustom extends TestBase { + private static final Logger logger = FlexLogger.getLogger(TestCustom.class); + + // + // Our public's + // + public static final String ALGORITHM = "RSA"; + public static final String PRIVATEKEY_FILE = "PrivateKey.key"; + public static final String PUBLICKEY_FILE = "PublicKey.key"; + + public static final String DECRYPTION_INPUT_STRING = "This is the SECRET value!"; + + public static final String DECRYPTION_INPUT_ID = "com:att:research:xacml:test:custom:encrypted-data"; + // + // Our keys + // + protected PublicKey publicKey = null; + protected PrivateKey privateKey = null; + // + // Our command line parameters + // + public static final String OPTION_GENERATE = "generate"; + + static { + options.addOption(new Option(OPTION_GENERATE, false, "Generate a private/public key pair.")); + } + + /** + * This function generates the public/private key pair. Should never have to call this again, this was + * called once to generate the keys. They were saved into the testsets/custom/datatype-function sub-directory. + */ + public void generateKeyPair() { + // + // Generate a RSA private/public key pair + // + KeyPairGenerator keyGen; + try { + keyGen = KeyPairGenerator.getInstance(ALGORITHM); + } catch (NoSuchAlgorithmException e) { + logger.error("failed to generate keypair: " + e); + return; + } + keyGen.initialize(1024); + final KeyPair key = keyGen.generateKeyPair(); + // + // Save the keys to disk + // + Path file = Paths.get(this.directory, PRIVATEKEY_FILE); + try (ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(file))) { + os.writeObject(key.getPrivate()); + } catch (IOException e) { + logger.error("Exception Occured"+e); + } + file = Paths.get(this.directory, PUBLICKEY_FILE); + try (ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(file))) { + os.writeObject(key.getPublic()); + } catch (IOException e) { + logger.error("Exception Occured"+e); + } + } + + public TestCustom(String[] args) throws ParseException, MalformedURLException, HelpException { + super(args); + } + + /* (non-Javadoc) + * + * Simply look for command line option: -generate + * This generates the public/private key. Shouldn't need to call it again, the keys have + * already been generated and saved. + * + * @see org.onap.policy.pdp.test.TestBase#parseCommands(java.lang.String[]) + */ + @Override + protected void parseCommands(String[] args) throws ParseException, MalformedURLException, HelpException { + // + // Have our parent class parse its options out + // + super.parseCommands(args); + // + // Parse the command line options + // + CommandLine cl; + cl = new GnuParser().parse(options, args); + if (cl.hasOption(OPTION_GENERATE)) { + // + // Really only need to do this once to setup the test. + // + this.generateKeyPair(); + } + } + + /* (non-Javadoc) + * + * After our parent class configure's itself, all this needs to do is read in + * the public/private key's into objects. + * + * @see org.onap.policy.pdp.test.TestBase#configure() + */ + @Override + protected void configure() throws FactoryException { + // + // Have our super do its thing + // + super.configure(); + // + // Read in the public key + // + try { + this.publicKey = (PublicKey) new ObjectInputStream(Files.newInputStream(Paths.get(this.directory, PUBLICKEY_FILE))).readObject(); + } catch (ClassNotFoundException | IOException e) { + logger.error(e); + } + // + // Read in the private key + // + try { + this.privateKey = (PrivateKey) new ObjectInputStream(Files.newInputStream(Paths.get(this.directory, PRIVATEKEY_FILE))).readObject(); + } catch (ClassNotFoundException | IOException e) { + logger.error(e); + } + } + + /* (non-Javadoc) + * + * Here we add 2 attributes into the request: 1) the private key, and 2) a String that was encrypted using the public key. + * + * The goal is to have the custom decrypt function use the private key to decrypt that string. + * + * @see org.onap.policy.pdp.test.TestBase#generateRequest(java.nio.file.Path, java.lang.String) + */ + @Override + protected Request generateRequest(Path file, String group) throws JSONStructureException, DOMStructureException, PEPException { + // + // Have our super class do its work + // + Request oldRequest = super.generateRequest(file, group); + // + // Copy the request attributes + // + List attributes = new ArrayList<>(); + for (RequestAttributes a : oldRequest.getRequestAttributes()) { + attributes.add(new StdMutableRequestAttributes(a)); + } + // + // We are supplying the private key as an attribute for the decryption function to use: + // + // (NOTE: Ideally this would be provided by a custom PIP provider, not the PEP) + // + // ID=com:att:research:xacml:test:custom:privatekey + // Issuer=com:att:research:xacml:test:custom + // Category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject + // Datatype=urn:com:att:research:xacml:custom:3.0:rsa:private + // + DataType dtExtended = dataTypeFactory.getDataType(DataTypePrivateKey.DT_PRIVATEKEY); + if (dtExtended == null) { + logger.error("Failed to get private key datatype."); + return null; + } + // + // Create the attribute value + // + try { + AttributeValue attributeValue = dtExtended.createAttributeValue(this.privateKey); + // + // Create the attribute + // + StdMutableAttribute newAttribute = new StdMutableAttribute(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT, + new IdentifierImpl("com:att:research:xacml:test:custom:privatekey"), + attributeValue, + "com:att:research:xacml:test:custom", + false); + boolean added = false; + for (StdMutableRequestAttributes a : attributes) { + // + // Does the category exist? + // + if (a.getCategory().equals(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT)) { + // + // Yes - add in the new attribute value + // + a.add(newAttribute); + added = true; + break; + } + } + if (added == false) { + // + // New category - create it and add it in + // + StdMutableRequestAttributes a = new StdMutableRequestAttributes(); + a.setCategory(newAttribute.getCategory()); + a.add(newAttribute); + attributes.add(a); + } + } catch (DataTypeException e) { + logger.error(e); + return null; + } + // + // We are also supplying this attribute which is the secret text encrypted with + // the public key. + // + // ID=com:att:research:xacml:test:custom:encrypted-data + // Issuer= + // Category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject + // Datatype=http://www.w3.org/2001/XMLSchema#hexBinary + // + // Encrypt it + // + byte[] encryptedData = null; + try { + Cipher cipher = Cipher.getInstance(ALGORITHM); + cipher.init(Cipher.ENCRYPT_MODE, this.publicKey); + // + // This is just a hack to test a decryption of the wrong value. + // + if (group.equals("Permit")) { + encryptedData = cipher.doFinal(DECRYPTION_INPUT_STRING.getBytes()); + } else { + encryptedData = cipher.doFinal("This is NOT the secret".getBytes()); + } + } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { + logger.error(e); + return null; + } + // + // Sanity check (for the Permit request) + // + try { + if (group.equals("Permit")) { + Cipher cipher = Cipher.getInstance(ALGORITHM); + cipher.init(Cipher.DECRYPT_MODE, this.privateKey); + byte[] decryptedData = cipher.doFinal(encryptedData); + if (new String(decryptedData).equals(DECRYPTION_INPUT_STRING)) { + logger.info("Sanity check passed: decrypted the encrypted data."); + } else { + logger.error("Sanity check failed to decrypt the encrypted data."); + return null; + } + } + } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { + logger.error(e); + } + // + // Get our datatype factory + // + dtExtended = dataTypeFactory.getDataType(XACML3.ID_DATATYPE_HEXBINARY); + if (dtExtended == null) { + logger.error("Failed to get hex binary datatype."); + return null; + } + // + // Create the attribute value + // + try { + AttributeValue attributeValue = dtExtended.createAttributeValue(encryptedData); + // + // Create the attribute + // + StdMutableAttribute newAttribute = new StdMutableAttribute(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT, + new IdentifierImpl("com:att:research:xacml:test:custom:encrypted-data"), + attributeValue, + null, + false); + boolean added = false; + for (StdMutableRequestAttributes a : attributes) { + // + // Does the category exist? + // + if (a.getCategory().equals(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT)) { + // + // Yes - add in the new attribute value + // + a.add(newAttribute); + added = true; + break; + } + } + if (added == false) { + // + // New category - create it and add it in + // + StdMutableRequestAttributes a = new StdMutableRequestAttributes(); + a.setCategory(newAttribute.getCategory()); + a.add(newAttribute); + attributes.add(a); + } + } catch (DataTypeException e) { + logger.error(e); + return null; + } + // + // Now form our final request + // + StdMutableRequest newRequest = new StdMutableRequest(); + newRequest.setCombinedDecision(oldRequest.getCombinedDecision()); + newRequest.setRequestDefaults(oldRequest.getRequestDefaults()); + newRequest.setReturnPolicyIdList(oldRequest.getReturnPolicyIdList()); + newRequest.setStatus(oldRequest.getStatus()); + for (StdMutableRequestAttributes a : attributes) { + newRequest.add(a); + } + return newRequest; + } + + public static void main(String[] args) { + try { + new TestCustom(args).run(); + } catch (ParseException | IOException | FactoryException e) { + logger.error(e); + } catch (HelpException e) { + } + } + +} diff --git a/ONAP-PDP/src/test/resources/CSVPolicy.xml b/ONAP-PDP/src/test/resources/CSVPolicy.xml new file mode 100644 index 000000000..10bb8579f --- /dev/null +++ b/ONAP-PDP/src/test/resources/CSVPolicy.xml @@ -0,0 +1,205 @@ + + + + + This Policy handles the Take action and Advice action operations. + + + + + Check the CPU Utilization or Network Load + + Load + + + + 95 + + + + CPU + + + + 95 + + + + + + Permit to create a new VM with Obligation + + + + + If the Requirement has met create the VM + + true + + + + + + Action_Info + + + + + Create_NEW_VM + + + + + + Permit to create a new VM with Advice + + + + + create_adviceAction + + + + + + + + If the Requirement has met create the VM + + true + + + + + + Action_Info + + + + + Created New VM + + + http://localhost:8080/pdp/?type=hb + + + + + + + + + + + + + + + + Permit to remove a VM with Obligation + + + + + remove_Action + + + + + + + + If the resource usage is low then remove the VM + + true + + + + + + Action_Info + + + + + Remove_VM + + + + + + Permit to remove a VM with Advice + + + + + remove_adviceAction + + + + + + + + If the resource usage is low then remove the VM + + true + + + + + + Action_Info + + + + + Removed VM + + + http://localhost:8080/pdp/?type=hb + + + + + diff --git a/ONAP-PDP/src/test/resources/log4j.properties b/ONAP-PDP/src/test/resources/log4j.properties new file mode 100644 index 000000000..e498777bb --- /dev/null +++ b/ONAP-PDP/src/test/resources/log4j.properties @@ -0,0 +1,42 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP +# ================================================================================ +# 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========================================================= +### + +# +# Use this properties for debugging and development. +# +# +# Set root logger level to DEBUG and its only appender to A1. +log4j.rootLogger=INFO, MAIN_LOG + +# A1 is set to be a ConsoleAppender. +log4j.appender.MAIN_LOG=org.apache.log4j.ConsoleAppender + +# A1 uses PatternLayout. +log4j.appender.MAIN_LOG.layout=org.apache.log4j.PatternLayout +log4j.appender.MAIN_LOG.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n + +# +# This is specifically for Xacml request/response logging +# +log4j.logger.xacml.request=INFO, REQUEST_LOG + +log4j.appender.REQUEST_LOG=org.apache.log4j.ConsoleAppender +log4j.appender.REQUEST_LOG.layout=org.apache.log4j.PatternLayout +log4j.appender.REQUEST_LOG.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} %m%n diff --git a/ONAP-PDP/src/test/resources/logback.xml b/ONAP-PDP/src/test/resources/logback.xml new file mode 100644 index 000000000..03e9c0442 --- /dev/null +++ b/ONAP-PDP/src/test/resources/logback.xml @@ -0,0 +1,253 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + --> + + + + + + + + + + + + + + + + + + + + ${defaultPattern} + + + + + + + + + + + + + ${logDirectory}/${auditLogName}.log + + ${logDirectory}/${auditLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + ${defaultAuditPattern} + + + + + 256 + + + + + + + + ${logDirectory}/${metricsLogName}.log + + ${logDirectory}/${metricsLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + + ${defaultMetricPattern} + + + + + 256 + + + + + + + + ${logDirectory}/${errorLogName}.log + + ${logDirectory}/${errorLogName}.%i.log.zip + + 1 + 9 + + + ERROR + + + 5MB + + + ${defaultErrorPattern} + + + + + 256 + + + + + + + ${debugLogDirectory}/${debugLogName}.log + + ${debugLogDirectory}/${debugLogName}.%i.log.zip + + 1 + 9 + + + DEBUG + + + 5MB + + + ${debugLoggerPattern} + + + + + 256 + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ONAP-PDP/src/test/resources/logging.properties b/ONAP-PDP/src/test/resources/logging.properties new file mode 100644 index 000000000..699369639 --- /dev/null +++ b/ONAP-PDP/src/test/resources/logging.properties @@ -0,0 +1,32 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP +# ================================================================================ +# 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========================================================= +### + +handlers = java.util.logging.ConsoleHandler, java.util.logging.FileHandler + +.level = FINE + +java.util.logging.SimpleFormatter.format=%4$s: %5$s %n + +java.util.logging.ConsoleHandler.level = FINEST +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter + +java.util.logging.FileHandler.level = SEVERE +java.util.logging.FileHandler.pattern=%h/xacml_log%u.log +java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter diff --git a/ONAP-PDP/src/test/resources/xacml.pip.properties b/ONAP-PDP/src/test/resources/xacml.pip.properties new file mode 100644 index 000000000..728a48281 --- /dev/null +++ b/ONAP-PDP/src/test/resources/xacml.pip.properties @@ -0,0 +1,23 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP +# ================================================================================ +# 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========================================================= +### + +# +#Fri Mar 06 12:06:30 EST 2015 +xacml.pip.engines= diff --git a/ONAP-PDP/src/test/resources/xacml.policy.properties b/ONAP-PDP/src/test/resources/xacml.policy.properties new file mode 100644 index 000000000..20e77188b --- /dev/null +++ b/ONAP-PDP/src/test/resources/xacml.policy.properties @@ -0,0 +1,25 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP +# ================================================================================ +# 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========================================================= +### + +# +#Fri Mar 06 12:06:30 EST 2015 +xacml.referencedPolicies= +xacml.rootPolicies= + diff --git a/ONAP-PDP/testclient.properties b/ONAP-PDP/testclient.properties new file mode 100644 index 000000000..908bae01c --- /dev/null +++ b/ONAP-PDP/testclient.properties @@ -0,0 +1,21 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP +# ================================================================================ +# 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========================================================= +### + +test=test,MASTER diff --git a/ONAP-PDP/testpdp.properties b/ONAP-PDP/testpdp.properties new file mode 100644 index 000000000..f99e93517 --- /dev/null +++ b/ONAP-PDP/testpdp.properties @@ -0,0 +1,21 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP +# ================================================================================ +# 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========================================================= +### + +PDP_URL= , test, test diff --git a/ONAP-PDP/xacml.pap.properties b/ONAP-PDP/xacml.pap.properties new file mode 100644 index 000000000..9e7f92a11 --- /dev/null +++ b/ONAP-PDP/xacml.pap.properties @@ -0,0 +1,107 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP +# ================================================================================ +# 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========================================================= +### + +# +# This is our factory that will create our engine +# +xacml.PAP.papEngineFactory=org.onap.policy.xacml.std.pap.StdEngineFactory + +# +# Where we store our PAP PDP Group/Node information +# +xacml.pap.pdps=pdps +# +# Need the PAP's url (how PDPs will reach it) configured here +# because we need it to generate the URLs of the Policy Files +# sent to the PDPs in the configuration when the PAP is first brought up. +# (In other cases, such as the PDP calling the PAP, we could generate this URL, +# but for startup there is no other way to get it.) +# +# + +xacml.rest.pap.url=http://localhost:8070/pap/ + +# +# Upon startup, have the PAP servlet send latest configuration information to all +# the PDP nodes it knows about. +# +xacml.rest.pap.initiate.pdp=true +# +# Heartbeat from PAP to PDPs +# +# How much time (in milliseconds) between heartbeats +# (i.e. the time between completing the heartbeat with all PDPs and starting the next cycle) +# +xacml.rest.pap.heartbeat.interval=10000 +# +# Heartbeat connection timeout (in milliseconds) +# +xacml.rest.pap.heartbeat.timeout=10000 + +################################################################################################ +# Adding properties for getting properties previously used by PAP-ADMIN for creating Policies +# THis is part of the Policy Creation API project +################################################################################################ + +# Set your domain here: +xacml.rest.pap.domain=com + +# Location where all the user workspaces are located. +xacml.rest.pap.workspace=workspace + +# Location where the GIT repository is located +xacml.rest.pap.repository=repository + +# new Property Please mention your PAP-REST webapps Location here. +xacml.rest.config.webapps=C:\\Second Tomcat\\apache-tomcat-8.0.23\\webapps\\ConfigPAP\\ + +#Turn the audit on to synchronize the DB/file system +#xacml.rest.pap.run.audit.flag=true +#Turn the audit off to not synchronize the DB/file system +#xacml.rest.pap.run.audit.flag=false +xacml.rest.pap.run.audit.flag=false + +#Audit will synchronize the file system to match the contents of the DB +#xacml.rest.pap.filesystem.audit=true +#Audit will synchronize the DB to match the contents of the file system +#xacml.rest.pap.filesystem.audit=false +xacml.rest.pap.filesystem.audit=false + +# id +xacml.rest.pap.userid=testpap +# pass +xacml.rest.pap.password=alpha123 +# pdps file +xacml.rest.pdp.idfile=test.properties + +#Properties for db access +javax.persistence.jdbc.driver=org.h2.Driver +javax.persistence.jdbc.url=jdbc:h2:file:./sql/xacmlTest +javax.persistence.jdbc.user=sa +javax.persistence.jdbc.password= + +#Time in ms which a Policy DB transaction will wait to get the transaction lock object +xacml.rest.pap.transaction.waitms=1000 + +#Policy DB transaction timeout in ms after it has obtained the transaction lock object +xacml.rest.pap.transaction.timeoutms=500 + +#Policy Audit timeout in ms after it has obtained the transaction lock object +xacml.rest.pap.audit.timeoutms=5000 diff --git a/ONAP-PDP/xacml.pdp.properties b/ONAP-PDP/xacml.pdp.properties new file mode 100644 index 000000000..8ad735dda --- /dev/null +++ b/ONAP-PDP/xacml.pdp.properties @@ -0,0 +1,86 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP +# ================================================================================ +# 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========================================================= +### + +# Default XACML Properties File for PDP RESTful servlet +# +# Standard API Factories +# +xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory +xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory +xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory +# NOT USED SEE BELOW xacml.pipFinderFactory=com.att.research.xacml.std.pip.StdPIPFinderFactory +xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory +# +# AT&T PDP Implementation Factories +# +xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory +xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory +xacml.att.functionDefinitionFactory=org.onap.policy.xacml.custom.OnapFunctionDefinitionFactory +# NOT USED SEE BELOW xacml.att.policyFinderFactory=org.onap.policy.pdp.std.StdPolicyFinderFactory + +# +# AT&T RESTful PDP Implementation Factories +# +xacml.pipFinderFactory=org.onap.policy.rest.impl.XACMLPdpPIPFinderFactory +xacml.att.policyFinderFactory=org.onap.policy.rest.XACMLPdpPolicyFinderFactory +# +# When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into +# into one PolicySet and use the given Policy Algorithm. +# +xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-deny-overrides +# +# PDP RESTful API properties +# +# Set this to the address where the XACML-PAP-REST servlet is running +# http://localhost:9090/pap/ +xacml.rest.pap.url=http://localhost:8070/pap/ +# +# Give the running PDP an ID for the PAP. The url that its running as is a good choice. +# The PAP identifies PDP's using the URL of the PDP. +# +xacml.rest.pdp.id=http://localhost:8082/pdp/ +# +# Set the directory where the PDP holds its Policy Cache and PIP Configuration +# +xacml.rest.pdp.config=config_testing + +xacml.rest.pdp.webapps=/webapps + +xacml.rest.pdp.configparams=../webapps/configparams +# +# Initialize register with PAP servlet +# +xacml.rest.pdp.register=true +# +# Sleep period in seconds between register attempts +# +xacml.rest.pdp.register.sleep=15 +# +# number of attempts to register. -1 means keep trying forever. +# +xacml.rest.pdp.register.retries=-1 +# +# max number of bytes in a POST of a XML/JSON request +# +xacml.rest.pdp.maxcontent=32767 +# +# testClient file +# +xacml.rest.pep.idfile = testclient.properties diff --git a/ONAP-PDP/xacml.properties b/ONAP-PDP/xacml.properties new file mode 100644 index 000000000..13ffdcf0d --- /dev/null +++ b/ONAP-PDP/xacml.properties @@ -0,0 +1,46 @@ +### +# ============LICENSE_START======================================================= +# ONAP-PDP +# ================================================================================ +# 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========================================================= +### + +# Default XACML Properties File +# Standard API Factories +# +xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory +xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory +xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory +xacml.pipFinderFactory=com.att.research.xacml.std.pip.StdPIPFinderFactory + +# If there is a standard set of PIPEngines: +# xacml.pip.engines=engine1,engine2,...,engineN +# engine1.classname=com.att.research.xacmlpip.OraclePIP +# engine1.prop1=foo +# engine1.prop2=bar +# ... +# engine2.classname=com.att.research.xacmlpip.ActiveDirectoryPIP +# ... + +# AT&T PDP Implementation Factories +# +xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory +xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory +xacml.att.functionDefinitionFactory=com.att.research.xacmlatt.pdp.std.StdFunctionDefinitionFactory +xacml.att.policyFinderFactory=com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory + +# If there is a standard policy for the engine: +# xacml.att.stdPolicyFinderFactory.rootPolicyFile=/etc/stdpolicyset.xml diff --git a/ECOMP-REST/.gitignore b/ONAP-REST/.gitignore similarity index 100% rename from ECOMP-REST/.gitignore rename to ONAP-REST/.gitignore diff --git a/ONAP-REST/policyLogger.properties b/ONAP-REST/policyLogger.properties new file mode 100644 index 000000000..e5c1619b6 --- /dev/null +++ b/ONAP-REST/policyLogger.properties @@ -0,0 +1,44 @@ +### +# ============LICENSE_START======================================================= +# ONAP-REST +# ================================================================================ +# 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========================================================= +### + +################################### Set concurrentHashMap and timer info ####################### +#Timer initial delay and the delay between in milliseconds before task is to be execute. +timer.delay.time=1000 +#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. +check.interval= 30000 +#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. +event.expired.time=86400 +#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed +#to remove all expired records from this concurrentHashMap. +concurrentHashMap.limit=5000 +#Size of the concurrentHashMap - when its size drops to this point, stop the Timer +stop.check.point=2500 +################################### Set logging format ############################################# +# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println +logger.type=EELF +#################################### Set level for EELF or SYSTEMOUT logging ################################## +# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all +debugLogger.level=INFO +# Set level for metrics file. Set OFF to disable; set ON to enable +metricsLogger.level=ON +# Set level for error file. Set OFF to disable; set ON to enable +error.level=ON +# Set level for audit file. Set OFF to disable; set ON to enable +audit.level=ON diff --git a/ONAP-REST/pom.xml b/ONAP-REST/pom.xml new file mode 100644 index 000000000..220d2aa4e --- /dev/null +++ b/ONAP-REST/pom.xml @@ -0,0 +1,114 @@ + + + + + + 4.0.0 + + + org.onap.policy.engine + PolicyEngineSuite + 1.1.0-SNAPSHOT + + + ONAP-REST + + ONAP REST + + jar + + + + org.onap.policy.engine + ${project.version} + ONAP-XACML + + + javax.servlet + javax.servlet-api + 3.1.0 + + + commons-logging + commons-logging + 1.1.3 + + + javax.servlet + servlet-api + + + + + com.google.guava + guava + 14.0.1 + + + com.google.code.gson + gson + 2.8.0 + + + junit + junit + 4.11 + test + + + org.mockito + mockito-core + 1.9.5 + + + org.springframework + spring-mock + 2.0.8 + + + com.mockrunner + mockrunner + 0.3.1 + + + org.eclipse.emf + org.eclipse.emf.ecore.xmi + 2.11.0-v20150123-0347 + + + org.eclipse.emf + org.eclipse.emf.ecore + 2.11.0-v20150123-0347 + + + org.eclipse.emf + org.eclipse.emf.common + 2.11.0-v20150123-0347 + + + org.json + json + [20090211,) + + + diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRest.java b/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRest.java new file mode 100644 index 000000000..6bef28dfb --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRest.java @@ -0,0 +1,216 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest; + +import java.io.IOException; +import java.util.Enumeration; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import javax.servlet.ServletConfig; +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + +import com.att.research.xacml.util.XACMLProperties; + + +/** + * This static class is used by both the PDP and PAP servlet's. It contains some common + * static functions and objects used by both the servlet's. + * + * + */ +public class XACMLRest { + private static final Log logger = LogFactory.getLog(XACMLRest.class); + private static Properties restProperties = new Properties(); + + /** + * This must be called during servlet initialization. It sets up the xacml.?.properties + * file as a system property. If the System property is already set, then it does not + * do anything. This allows the developer to specify their own xacml.properties file to be + * used. They can 1) modify the default properties that comes with the project, or 2) change + * the WebInitParam annotation, or 3) specify an alternative path in the web.xml, or 4) set + * the Java System property to point to their xacml.properties file. + * + * The recommended way of overriding the default xacml.properties file is using a Java System + * property: + * + * -Dxacml.properties=/opt/app/xacml/etc/xacml.admin.properties + * + * This way one does not change any actual code or files in the project and can leave the + * defaults alone. + * + * @param config - The servlet config file passed from the javax servlet init() function + */ + public static void xacmlInit(ServletConfig config) { + // + // Get the XACML Properties File parameter first + // + String propFile = config.getInitParameter("XACML_PROPERTIES_NAME"); + if (propFile != null) { + // + // Look for system override + // + String xacmlPropertiesName = System.getProperty(XACMLProperties.XACML_PROPERTIES_NAME); + logger.info("\n\n" + xacmlPropertiesName + "\n" + XACMLProperties.XACML_PROPERTIES_NAME); + if (xacmlPropertiesName == null) { + // + // Set it to our servlet default + // + if (logger.isDebugEnabled()) { + logger.debug("Using Servlet Config Property for XACML_PROPERTIES_NAME:" + propFile); + } + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, propFile); + } else { + if (logger.isDebugEnabled()) { + logger.debug("Using System Property for XACML_PROPERTIES_NAME:" + xacmlPropertiesName); + } + } + } + // + // Setup the remaining properties + // + Enumeration params = config.getInitParameterNames(); + while (params.hasMoreElements()) { + String param = params.nextElement(); + if (! param.equals("XACML_PROPERTIES_NAME")) { + String value = config.getInitParameter(param); + //logger.info(param + "=" + config.getInitParameter(param)); + PolicyLogger.info(param + "=" + config.getInitParameter(param)); + restProperties.setProperty(param, value); + } + } + } + + /** + * Reset's the XACMLProperties internal properties object so we start + * in a fresh environment. Then adds back in our Servlet init properties that were + * passed in the javax Servlet init() call. + * + * This function is primarily used when a new configuration is passed in and the + * PDP servlet needs to load a new PDP engine instance. + * + * @param pipProperties - PIP configuration properties + * @param policyProperties - Policy configuration properties + */ + public static void loadXacmlProperties(Properties policyProperties, Properties pipProperties) { + try { + // + // Start fresh + // + XACMLProperties.reloadProperties(); + // + // Now load our init properties + // + XACMLProperties.getProperties().putAll(XACMLRest.restProperties); + // + // Load our policy properties + // + if (policyProperties != null) { + XACMLProperties.getProperties().putAll(policyProperties); + } + // + // Load our pip config properties + // + if (pipProperties != null) { + XACMLProperties.getProperties().putAll(pipProperties); + } + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Failed to put init properties into Xacml properties"); + } + // + // Dump them + // + if (logger.isDebugEnabled()) { + try { + logger.debug(XACMLProperties.getProperties().toString()); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Cannot dump properties"); + } + } + } + + /** + * Helper routine to dump the HTTP servlet request being serviced. Primarily for debugging. + * + * @param request - Servlet request (from a POST/GET/PUT/etc.) + */ + public static void dumpRequest(HttpServletRequest request) { + if (logger.isDebugEnabled()) { + // special-case for receiving heartbeat - don't need to repeatedly output all of the information in multiple lines + if (request.getMethod().equals("GET") && "hb".equals(request.getParameter("type")) ) { + //logger.debug("GET type=hb : heartbeat received"); + PolicyLogger.debug("GET type=hb : heartbeat received"); + return; + } + logger.debug(request.getMethod() + ":" + request.getRemoteAddr() + " " + request.getRemoteHost() + " " + request.getRemotePort()); + logger.debug(request.getLocalAddr() + " " + request.getLocalName() + " " + request.getLocalPort()); + Enumeration en = request.getHeaderNames(); + logger.debug("Headers:"); + while (en.hasMoreElements()) { + String element = en.nextElement(); + Enumeration values = request.getHeaders(element); + while (values.hasMoreElements()) { + String value = values.nextElement(); + logger.debug(element + ":" + value); + } + } + logger.debug("Attributes:"); + en = request.getAttributeNames(); + while (en.hasMoreElements()) { + String element = en.nextElement(); + logger.debug(element + ":" + request.getAttribute(element)); + } + logger.debug("ContextPath: " + request.getContextPath()); + if (request.getMethod().equals("PUT") || request.getMethod().equals("POST")) { + // POST and PUT are allowed to have parameters in the content, but in our usage the parameters are always in the Query string. + // More importantly, there are cases where the POST and PUT content is NOT parameters (e.g. it might contain a Policy file). + // Unfortunately the request.getParameterMap method reads the content to see if there are any parameters, + // and once the content is read it cannot be read again. + // Thus for PUT and POST we must avoid reading the content here so that the main code can read it. + logger.debug("Query String:" + request.getQueryString()); + try { + if (request.getInputStream() == null) { + logger.debug("Content: No content inputStream"); + } else { + logger.debug("Content available: " + request.getInputStream().available()); + } + } catch (Exception e) { + logger.debug("Content: inputStream exception: " + e.getMessage() + "; (May not be relevant)" +e); + } + } else { + logger.debug("Parameters:"); + Map params = request.getParameterMap(); + Set keys = params.keySet(); + for (String key : keys) { + String[] values = params.get(key); + logger.debug(key + "(" + values.length + "): " + (values.length > 0 ? values[0] : "")); + } + } + logger.debug("Request URL:" + request.getRequestURL()); + } + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRestProperties.java b/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRestProperties.java new file mode 100644 index 000000000..5c8449603 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRestProperties.java @@ -0,0 +1,456 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest; + +import com.att.research.xacml.util.XACMLProperties; + +/** + * These are XACML Properties that are relevant to the RESTful API interface for + * the PDP, PAP and AC interfaces. + * + * + */ +public class XACMLRestProperties extends XACMLProperties { + /** + * A unique identifier for the PDP servlet instance. Usually set to the URL + * it is running as in the J2EE container. + * + * Eg. http://localhost:8080/pdp/ + */ + public static final String PROP_PDP_ID = "xacml.rest.pdp.id"; + /** + * A PDP servlet's configuration directory. Holds the pip and policy + * configuration data as well as the local policy cache. + * + * Eg: /opt/app/xacml/config + */ + public static final String PROP_PDP_CONFIG = "xacml.rest.pdp.config"; + // Resilience feature- + public static final String PROP_PDP_WEBAPPS = "xacml.rest.pdp.webapps"; + //Closed Loop JSON table + public static final String PROP_ADMIN_CLOSEDLOOP = "xacml.rest.admin.closedLoopJSON"; + /** + * Set this property to true or false if the PDP servlet should register + * itself upon startup with the PAP servlet. + */ + public static final String PROP_PDP_REGISTER = "xacml.rest.pdp.register"; + /** + * Number of seconds the PDP will sleep while retrying registration with the + * PAP. This value must be greater or equal to 5. + */ + public static final String PROP_PDP_REGISTER_SLEEP = "xacml.rest.pdp.register.sleep"; + /** + * Number of retry attempts at registration with the PAP. A value of -1 + * indicates infinite retries. + */ + public static final String PROP_PDP_REGISTER_RETRIES = "xacml.rest.pdp.register.retries"; + /** + * Max content length accepted for an incoming POST XML/JSON request. + * Default is 32767 bytes. + */ + public static final String PROP_PDP_MAX_CONTENT = "xacml.rest.pdp.maxcontent"; + /** + * Custom HTTP header used by PDP to send the value of the PROP_PDP_ID + */ + public static final String PROP_PDP_HTTP_HEADER_ID = "X-XACML-PDP-ID"; + /** + * Custom HHTP header used by PDP to send its heartbeat value. + */ + public static final String PROP_PDP_HTTP_HEADER_HB = "X-XACML-PDP-HB"; + /* + * Custom HTTP header used by PDP to send the value of the + * X-XACML-PDP-JMX-PORT + */ + public static final String PROP_PDP_HTTP_HEADER_JMX_PORT = "X-XACML-PDP-JMX-PORT"; + /** + * The URL of the PAP servlet. Used by PDP servlet's to communicate. Because + * administrators can set whatever context they want to run the PAP servlet, + * it isn't easy to determine a return URL for the PAP servlet. This is + * especially true upon initialization. + */ + public static final String PROP_PAP_URL = "xacml.rest.pap.url"; + /** + * A comma divided list of urls pointing to avaiable PAP urls. + * If one or more fail, the other servers in the list can + * handle the requests. + */ + public static final String PROP_PAP_URLS = "xacml.rest.pap.urls"; + public static final String PROP_PAP_FAILED_URLS = "xacml.rest.pap.failedUrls"; + public static final String PROP_PAP_SUCCEEDED_URLS = "xacml.rest.pap.succeededUrls"; + //public static final String PROP_PAP_FAILED_URL_TIME = "xacml.rest.pap.failedUrlTime"; + + /** + * Upon startup, have the PAP servlet send latest configuration information + * to all the PDP nodes it knows about. + */ + public static final String PROP_PAP_INITIATE_PDP_CONFIG = "xacml.rest.pap.initiate.pdp"; + /** + * The interval the PAP servlet uses to send heartbeat requests to the PDP + * nodes. + */ + public static final String PROP_PAP_HEARTBEAT_INTERVAL = "xacml.rest.pap.heartbeat.interval"; + /** + * Timeout value used by the PAP servlet when trying to check the heartbeat + * of a PDP node. + */ + public static final String PROP_PAP_HEARTBEAT_TIMEOUT = "xacml.rest.pap.heartbeat.timeout"; + /* + * This is the domain you can setup for your organization, it should be a URI. + * Eg. com:sample:foo + */ + public static final String PROP_PAP_DOMAIN = "xacml.rest.pap.domain"; + + /* + * Local path to where user workspaces exist. The user workspace contains temporary files, the + * user's clone of the GIT repository, anything specific to the user, etc. + */ + public static final String PROP_PAP_WORKSPACE = "xacml.rest.pap.workspace"; + + /* + * Local path to where the GIT repository exists. + * + * Eg. /opt/app/xacml/repository + */ + public static final String PROP_PAP_REPOSITORY = "xacml.rest.pap.repository"; + + /* + * Database driver property + */ + public static final String PROP_PAP_DB_DRIVER = "javax.persistence.jdbc.driver"; + + /* + * Database url + */ + public static final String PROP_PAP_DB_URL = "javax.persistence.jdbc.url"; + + /* + * Database user + */ + public static final String PROP_PAP_DB_USER = "javax.persistence.jdbc.user"; + + /* + * Database password + */ + public static final String PROP_PAP_DB_PASSWORD = "javax.persistence.jdbc.password"; + + /* + * Time in ms which a Policy DB transaction will wait to get the transaction lock object + */ + public static final String PROP_PAP_TRANS_WAIT = "xacml.rest.pap.transaction.waitms"; + + /* + * Policy DB transaction timeout in ms after it has obtained the transaction lock object + */ + public static final String PROP_PAP_TRANS_TIMEOUT = "xacml.rest.pap.transaction.timeoutms"; + + /* + * Policy Audit transaction timeout in ms after it has obtained the transaction lock object + */ + public static final String PROP_PAP_AUDIT_TIMEOUT = "xacml.rest.pap.audit.timeoutms"; + + /* + * Value determines direction of audit. Value=true will synch the file system to contents of the DB. + * Value=false will synch the DB to the contents of the file system. + */ + public static final String PROP_PAP_AUDIT_FLAG = "xacml.rest.pap.filesystem.audit"; + + /* + * Value for enable/disable of audit functionality + */ + public static final String PROP_PAP_RUN_AUDIT_FLAG = "xacml.rest.pap.run.audit.flag"; + + /* + * Controls how long the timeout will be when a pap sends a notification to another pap + */ + public static final String PROP_PAP_NOTIFY_TIMEOUT = "xacml.rest.pap.notify.timeoutms"; + /* + * Value for Enable/Disable of AutoPush Flag. + */ + public static final String PROP_PAP_PUSH_FLAG = "xacml.rest.pap.autopush.flag"; + + /* + * Properties file for the AutoPush Functionality. + */ + public static final String PROP_PAP_PUSH_FILE = "xacml.rest.pap.autopush.file"; + + /* + * Local path to where the GIT repository exists. + * + * Eg. /opt/app/xacml/repository + */ + public static final String PROP_ADMIN_REPOSITORY = "xacml.rest.admin.repository"; + /* + * Local path to where user workspaces exist. The user workspace contains + * temporary files, the user's clone of the GIT repository, anything + * specific to the user, etc. + */ + public static final String PROP_ADMIN_WORKSPACE = "xacml.rest.admin.workspace"; + /* + * This is the domain you can setup for your organization, it should be a + * URI. + * + * Eg. com:sample:foo + */ + public static final String PROP_ADMIN_DOMAIN = "xacml.rest.admin.domain"; + /** + * PROP_ADMIN_USER_NAME is simply a name for the logged in user. + * + * AC authentication is out the scope of the web application itself. It is + * up to the developer to setup authentication as they please in the J2EE + * container used to run the web application. Whatever authentication + * mechanism they use, they should then set the attribute into the + * HttpSession object. The Admin Console will be able to read that value + * (default to "guest") in. + * + * ((HttpServletRequest) + * request).getSession().setAttribute("xacml.rest.admin.user.name", + * "Homer"); + * + */ + public static final String PROP_ADMIN_USER_NAME = "xacml.rest.admin.user.name"; + /** + * + * PROP_ADMIN_USER_ID is an id for the logged in user. + * + * Eg. hs1234 + * + * @see #PROP_ADMIN_USER_NAME for more information. + */ + public static final String PROP_ADMIN_USER_ID = "xacml.rest.admin.user.id"; + /** + * + * PROP_ADMIN_USER_EMAIL is a user's email address. + * + * @see #PROP_ADMIN_USER_NAME for more information. + */ + public static final String PROP_ADMIN_USER_EMAIL = "xacml.rest.admin.user.email"; + /** + * Directory path containing sub-directories where the Subscriber servlet + * puts files sent through data feeds. + */ + public static final String PROP_SUBSCRIBER_INCOMING = "xacml.subscriber.incoming"; + /** + * The specific data feed name for the Subscriber servlet to register for. + */ + public static final String PROP_SUBSCRIBER_FEED = "xacml.subscriber.feed"; + /** + * Value for the log time frame that is to be stored in the database any + * logs after this time frame will be removed. + */ + public static final String PROP_LOG_TIMEFRAME = "xacml.log.timeframe"; + /** + * Value for the DB connections used to store the log files. + */ + public static final String PROP_LOG_DB_DRIVER = "xacml.log.db.driver"; + public static final String PROP_LOG_DB_URL = "xacml.log.db.url"; + public static final String PROP_LOG_DB_USER = "xacml.log.db.user"; + public static final String PROP_LOG_DB_PASSWORD = "xacml.log.db.password"; + /* + * Value for JMX port for the PDP + */ + public static final String PROP_PDP_JMX_PORT = "xacml.jmx.port"; + + /* + * Value for refresh rate + */ + public static final String PROP_REFRESH_RATE = "xacml.refresh.rate"; + + // added for Security between Policy Components. + // 6/26 + /* + * PROP_PAP_USERID is the PAP Unique User ID + */ + public static final String PROP_PAP_USERID = "xacml.rest.pap.userid"; + /* + * PROP_PAP_PASS is the PAP password + */ + public static final String PROP_PAP_PASS = "xacml.rest.pap.password"; + /* + * PROP_PAP_PASS is the PAP password + */ + public static final String PROP_CONFIG_URL = "xacml.rest.config.url"; + /* + * PROP_PDP_USERID is the PDP Unique User ID + */ + public static final String PROP_PDP_USERID = "xacml.rest.pdp.userid"; + /* + * PROP_PDP_PASS is the PDP password + */ + public static final String PROP_PDP_PASS = "xacml.rest.pdp.password"; + /* + * PROP_PDP_IDFILE is the PDP Authentication File + */ + public static final String PROP_PDP_IDFILE = "xacml.rest.pdp.idfile"; + /* + * PROP_PEP_IDFILE is the Client Authentication File + */ + public static final String PROP_PEP_IDFILE = "xacml.rest.pep.idfile"; + /* + * webapps Location of the PAP-REST server + */ + public static final String PROP_PAP_WEBAPPS= "xacml.rest.config.webapps"; + /* + * Value for Notification Option + */ + public static final String PROP_NOTIFICATION_TYPE = "NOTIFICATION_TYPE"; + /* + * Value for Notification DMaaP servers + */ + public static final String PROP_NOTIFICATION_SERVERS = "NOTIFICATION_SERVERS"; + /* + * Value for Notification Delay + */ + public static final String PROP_NOTIFICATION_DELAY= "NOTIFICATION_DELAY"; + /* + * Value for Notification Topic + */ + public static final String PROP_NOTIFICATION_TOPIC= "NOTIFICATION_TOPIC"; + /* + * Value for Notification Topic + */ + public static final String PROP_UEB_API_KEY= "UEB_API_KEY"; + /* + * Value for Notification Topic + */ + public static final String PROP_UEB_API_SECRET= "UEB_API_SECRET"; + /* + * Closedloop Fault Policy Template Version + */ + public static final String TemplateVersion_Fault= "xacml.rest.closedLoopFault"; + /* + * Closedloop PM Policy Template Version + */ + public static final String TemplateVersion_PM= "xacml.rest.closedLoopPM"; + /* + * Value for model properties file + */ + public static final String PROP_ADMIN_MICROSERVICE = "xacml.rest.admin.microServiceModel"; + /* + * MicroService Policy Template Version + */ + public static final String TemplateVersion_MS= "xacml.rest.microServices"; + /* + * Firewall Policy Template Version + */ + public static final String TemplateVersion_FW= "xacml.rest.firewallPolicy"; + /* + * Size of SelectList for Users in MS + * + */ + public static final String PROP_USER_SELECTLIST_WINDOW_SIZE= "xacml.user.column.count"; + /* + * Audit function in pap admin to Update userinfo table to syncronize with Roles table + */ + public static final String PROP_ROLES_USERINFO_AUDIT= "xacml.audit.userInfo"; + /* + * test Environment LoginId + */ + public static final String PROP_TEST_ENVIRONMENT_LOGINID= "xacml.testEnvironment.loginId"; + /* + * Size of of the page length for sqlcontainer + * + */ + public static final String PROP_SQLCONTAINER_PAGE_LENGTH= "xacml.sqlcontainer.page.length"; + /* + * add values used to connect to restful api + * + */ + public static final String PROP_RESTFUL_INTERFACE= "xacm.restful.interface.file"; + /* + * add pattern to identify what values are designed as required + * + */ + public static final String PROP_XCORE_REQUIRED_PATTERN= "xacm.xcor.required.pattern"; + /* + * Time before a cache value is evicted + * + */ + public static final String PROP_CACHE_LIVE_TIME= "xacm.cache.live.time"; + /* + * Highest value allowed in priority + * + */ + public static final String PROP_PRIORITY_COUNT= "xacml.max.priority.count"; + /* + * The name of the PAP. Must be unique across the system + */ + public static final String PAP_RESOURCE_NAME="xacml.rest.pap.resource.name"; + /* + * The name of the site in which the PAP resides + */ + public static final String PAP_SITE_NAME="site_name"; + /* + * The node type of the PAP - really a no-op since it's value is pap + */ + public static final String PAP_NODE_TYPE="node_type"; + /* + * A list of the groups of resources/nodes on which the PAP is dependent. The members of a + * group are comma-separated and the groups are separated with semicolons. + */ + public static final String PAP_DEPENDENCY_GROUPS="dependency_groups"; + /* + * The (optional) period of time in seconds between executions of the integrity audit. + * Value < 0 : Audit does not run (default value if property is not present = -1) + * Value = 0 : Audit runs continuously + * Value > 0 : The period of time in seconds between execution of the audit on a particular node + */ + public static final String PAP_INTEGRITY_AUDIT_PERIOD_SECONDS = "integrity_audit_period_seconds"; + /* + * The name of the Admin. Must be unique across the system + */ + public static final String ADMIN_RESOURCE_NAME="xacml.rest.admin.resource.name"; + /* + * The name of the PDP. Must be unique across the system + */ + public static final String PDP_RESOURCE_NAME="xacml.rest.pdp.resource.name"; + /* + * Audit function in pap admin to Update userinfo table to syncronize with Roles table + */ + public static final String PROP_AUTOMATIC_POLICYPUSH= "xacml.automatic.push"; + /* + * Add Limit for Onap Portal Dashboard tab data + */ + public static final String PROP_ONAP_LOGLIMIT = "xacml.onap.dashboard.logTableLimit"; + public static final String PROP_ONAP_SYSTEMALERTLIMIT = "xacml.onap.dashboard.systemAlertTableLimit"; + /* + * Diff of the policies for the Firewall Feature. + */ + public static final String PROP_FW_GETURL = "FW_GETURL"; + public static final String PROP_FW_AUTHOURL = "FW_AUTHOURL"; + public static final String PROP_FW_PROXY = "FW_PROXY"; + public static final String PROP_FW_PORT = "FW_PORT"; + + /* + * The number of Risk Levels allowed + */ + public static final String ADMIN_RISK_LEVEL_COUNT="xacml.risk.level.count"; + /* + * The maxium Level displayed on the UI for Micro Services + */ + public static final String PROP_MODEL_LEVEL = "xacml.model.level"; + + /* + * Value for Incoming Notification tries + * + * */ + public static final String PROP_PAP_INCOMINGNOTIFICATION_TRIES = "xacml.rest.pap.incomingnotification.tries"; + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/XacmlAdminAuthorization.java b/ONAP-REST/src/main/java/org/onap/policy/rest/XacmlAdminAuthorization.java new file mode 100644 index 000000000..c8dc71918 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/XacmlAdminAuthorization.java @@ -0,0 +1,220 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.xacml.api.XACMLErrorConstants; + +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.api.Decision; +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.Response; +import com.att.research.xacml.api.Result; +import com.att.research.xacml.api.pdp.PDPEngine; +import com.att.research.xacml.api.pdp.PDPEngineFactory; +import com.att.research.xacml.api.pdp.PDPException; +import com.att.research.xacml.std.annotations.RequestParser; +import com.att.research.xacml.std.annotations.XACMLAction; +import com.att.research.xacml.std.annotations.XACMLRequest; +import com.att.research.xacml.std.annotations.XACMLResource; +import com.att.research.xacml.std.annotations.XACMLSubject; +import com.att.research.xacml.util.FactoryException; + + + +public class XacmlAdminAuthorization { + private static Log logger = LogFactory.getLog(XacmlAdminAuthorization.class); + + private static UserInfo userId; + public static UserInfo getUserId() { + return userId; + } + + public void setUserId(UserInfo userId) { + XacmlAdminAuthorization.userId = userId; + } + + public enum AdminAction { + ACTION_ACCESS("access"), + ACTION_READ("read"), + ACTION_WRITE("write"), + ACTION_ADMIN("admin"); + + String action; + AdminAction(String a) { + this.action = a; + } + public String toString() { + return this.action; + } + } + + public enum AdminResource { + RESOURCE_APPLICATION("application"), + RESOURCE_POLICY_WORKSPACE("workspace"), + RESOURCE_POLICY_EDITOR("editor"), + RESOURCE_DICTIONARIES("dictionaries"), + RESOURCE_PDP_ADMIN("pdp_admin"), + RESOURCE_PIP_ADMIN("pip_admin"), + RESOURCE_SCOPES_SUPERADMIN("manage_scopes"); + + String resource; + AdminResource(String r) { + this.resource = r; + } + public String toString() { + return this.resource; + } + } + + public enum Role { + ROLE_GUEST("guest"), + ROLE_ADMIN("admin"), + ROLE_EDITOR("editor"), + ROLE_SUPERGUEST("super-guest"), + ROLE_SUPEREDITOR("super-editor"), + ROLE_SUPERADMIN("super-admin"); + + String userRole; + + Role(String a) { + this.userRole = a; + } + public String toString() { + return this.userRole; + } + } + + @XACMLRequest(ReturnPolicyIdList=true) + public class AuthorizationRequest { + + @XACMLSubject(includeInResults=true) + String userID; + + @XACMLAction() + String action; + + @XACMLResource() + String resource; + + public AuthorizationRequest(String userId, String action, String resource) { + this.userID = userId; + this.action = action; + this.resource = resource; + } + + public String getUserID() { + return userID; + } + + public void setUserID(String userID) { + this.userID = userID; + } + + public String getAction() { + return action; + } + + public void setAction(String action) { + this.action = action; + } + + public String getResource() { + return resource; + } + + public void setResource(String resource) { + this.resource = resource; + } + } + + // + // The PDP Engine + // + protected PDPEngine pdpEngine; + + public XacmlAdminAuthorization() { + PDPEngineFactory pdpEngineFactory = null; + try { + pdpEngineFactory = PDPEngineFactory.newInstance(); + if (pdpEngineFactory == null) { + logger.error("Failed to create PDP Engine Factory"); + PolicyLogger.error("Failed to create PDP Engine Factory"); + } + this.pdpEngine = pdpEngineFactory.newEngine(); + } catch (FactoryException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception create PDP Engine: " + e.getLocalizedMessage()); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XacmlAdminAuthorization", "Exception create PDP Engine"); + } + } + + public boolean isAuthorized(String userid, AdminAction action, AdminResource resource) { + logger.info("authorize: " + userid + " to " + action + " with " + resource); + if (this.pdpEngine == null) { + logger.warn("no pdp engine available to authorize"); + return false; + } + Request request; + try { + request = RequestParser.parseRequest(new AuthorizationRequest(userid, action.toString(), resource.toString())); + } catch (IllegalArgumentException | IllegalAccessException | DataTypeException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create request: " + e.getLocalizedMessage()); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XacmlAdminAuthorization", "Failed to create request"); + return false; + } + if (request == null) { + logger.error("Failed to parse request."); + PolicyLogger.error("Failed to parse request"); + return false; + } + logger.info("Request: " + request); + // + // Ask the engine + // + try { + Response response = this.pdpEngine.decide(request); + if (response == null) { + logger.error("Null response from PDP decide"); + PolicyLogger.error("Null response from PDP decide"); + } + // + // Should only be one result + // + if(response != null){ + for (Result result : response.getResults()) { + Decision decision = result.getDecision(); + logger.info("Decision: " + decision); + if (decision.equals(Decision.PERMIT)) { + return true; + } + } + } + } catch (PDPException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PDP Decide failed: " + e.getLocalizedMessage()); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XacmlAdminAuthorization", "PDP Decide failed"); + } + return false; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AddressGroupJson.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AddressGroupJson.java new file mode 100644 index 000000000..c634a74d1 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AddressGroupJson.java @@ -0,0 +1,83 @@ +/*- + * ============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.rest.adapter; + + +import java.util.ArrayList; +import java.util.List; + +public class AddressGroupJson { + + protected String name; + protected String description; + protected List members; + + // name + public String getName() { + return name; + } + + public void setName(String value) { + this.name = value; + } + + public boolean equals(Object obj){ + if(obj == null){ + return false; + } + if(this.getClass() != obj.getClass()){ + return false; + } + AddressGroupJson servGroupobj=(AddressGroupJson) obj; + if(this.getName().equals(servGroupobj.getName())){ + return true; + } + return false; + } + + public int hashCode() { + return Integer.valueOf(name.charAt(0)+(name.charAt(1))); + } + + // description + public String getDescription() { + return description; + } + + public void setDescription(String value) { + this.description = value; + } + + public List getMembers() + { + if(members==null) + { + members= new ArrayList(); + } + return this.members; + } + + public void setMembers(List members) + { + this.members = members; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AddressJson.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AddressJson.java new file mode 100644 index 000000000..555994347 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AddressJson.java @@ -0,0 +1,52 @@ +/*- + * ============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.rest.adapter; + + +public class AddressJson { + + protected String type; + protected String name; + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + // type + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + /*public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + }*/ +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AddressMembers.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AddressMembers.java new file mode 100644 index 000000000..14e46f15f --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AddressMembers.java @@ -0,0 +1,46 @@ +/*- + * ============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.rest.adapter; + + + +public class AddressMembers { + + protected String type; + protected String value; + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AutoPushTabAdapter.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AutoPushTabAdapter.java new file mode 100644 index 000000000..4e5336a05 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/AutoPushTabAdapter.java @@ -0,0 +1,42 @@ +/*- + * ============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.rest.adapter; + + +import java.util.ArrayList; + +public class AutoPushTabAdapter { + + private ArrayList pdpDatas; + private ArrayList policyDatas; + public ArrayList getPdpDatas() { + return pdpDatas; + } + public void setPdpDatas(ArrayList pdpDatas) { + this.pdpDatas = pdpDatas; + } + public ArrayList getPolicyDatas() { + return policyDatas; + } + public void setPolicyDatas(ArrayList policyDatas) { + this.policyDatas = policyDatas; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopFaultBody.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopFaultBody.java new file mode 100644 index 000000000..80853af5d --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopFaultBody.java @@ -0,0 +1,280 @@ +/*- + * ============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.rest.adapter; + + + +public class ClosedLoopFaultBody { + + private boolean trinity; + private boolean vUSP; + private boolean mcr; + private boolean gama; + private boolean vDNS; + + private String vnfType; + private String vServices; + private String ONAPname; + + private String closedLoopPolicyStatus; + private ClosedLoopSignatures triggerSignatures; + private String actions; + private int timeInterval; + private int timeOutvPRO; + private int timeOutRuby; + private int retrys; + private int agingWindow; + private String geoLink; + private String emailAddress; + private ClosedLoopSignatures verificationSignatures; + private ClosedLoopPolicyConditions conditions; + private ClosedLoopFaultTriggerUISignatures triggerSignaturesUsedForUI; + private ClosedLoopFaultTriggerUISignatures verificationSignaturesUsedForUI; + private int triggerTimeWindowUsedForUI; + private int verfificationTimeWindowUsedForUI; + private String pepName; + private String pepAction; + private String templateVersion; + private int trapMaxAgeUsedForUI; + + + public Integer getTrapMaxAgeUsedForUI() { + return trapMaxAgeUsedForUI; + } + + public void setTrapMaxAgeUsedForUI(int trapMaxAgeUsedForUI) { + this.trapMaxAgeUsedForUI = trapMaxAgeUsedForUI; + } + + public String getTemplateVersion() { + return templateVersion; + } + + public void setTemplateVersion(String templateVersion) { + this.templateVersion = templateVersion; + } + + public Integer getTimeOutvPRO() { + return timeOutvPRO; + } + + public void setTimeOutvPRO(int timeOutvPRO) { + this.timeOutvPRO = timeOutvPRO; + } + + + public Integer getTriggerTimeWindowUsedForUI() { + return triggerTimeWindowUsedForUI; + } + + public String getPepName() { + return pepName; + } + + public void setPepName(String pepName) { + this.pepName = pepName; + } + + public String getPepAction() { + return pepAction; + } + + public void setPepAction(String pepAction) { + this.pepAction = pepAction; + } + + public void setTriggerTimeWindowUsedForUI(int triggerTimeWindowUsedForUI) { + this.triggerTimeWindowUsedForUI = triggerTimeWindowUsedForUI; + } + + public Integer getVerfificationTimeWindowUsedForUI() { + return verfificationTimeWindowUsedForUI; + } + + public void setVerfificationTimeWindowUsedForUI( + int verfificationTimeWindowUsedForUI) { + this.verfificationTimeWindowUsedForUI = verfificationTimeWindowUsedForUI; + } + + public String getONAPname(){ + return ONAPname; + } + + public void setONAPname(String ONAPname){ + this.ONAPname = ONAPname; + } + + public String getvServices() { + return vServices; + } + public void setvServices(String vServices) { + this.vServices = vServices; + } + + public ClosedLoopFaultTriggerUISignatures getVerificationSignaturesUsedForUI() { + return verificationSignaturesUsedForUI; + } + public void setVerificationSignaturesUsedForUI( + ClosedLoopFaultTriggerUISignatures verificationSignaturesUsedForUI) { + this.verificationSignaturesUsedForUI = verificationSignaturesUsedForUI; + } + public ClosedLoopFaultTriggerUISignatures getTriggerSignaturesUsedForUI() { + return triggerSignaturesUsedForUI; + } + public void setTriggerSignaturesUsedForUI( + ClosedLoopFaultTriggerUISignatures triggerSignaturesUsedForUI) { + this.triggerSignaturesUsedForUI = triggerSignaturesUsedForUI; + } + public ClosedLoopPolicyConditions getConditions() { + return conditions; + } + public void setConditions(ClosedLoopPolicyConditions conditions) { + this.conditions = conditions; + } + + public String getVnfType() { + return vnfType; + } + public void setVnfType(String vnfType) { + this.vnfType = vnfType; + } + + public Integer getAgingWindow() { + return agingWindow; + } + public void setAgingWindow(int agingWindow) { + this.agingWindow = agingWindow; + } + + public String getClosedLoopPolicyStatus() { + return closedLoopPolicyStatus; + } + public void setClosedLoopPolicyStatus( + String closedLoopPolicyStatus) { + this.closedLoopPolicyStatus = closedLoopPolicyStatus; + } + public ClosedLoopSignatures getTriggerSignatures() { + return triggerSignatures; + } + public void setTriggerSignatures(ClosedLoopSignatures triggerSignatures) { + this.triggerSignatures = triggerSignatures; + } + public String getActions() { + return actions; + } + public void setActions(String actions) { + this.actions = actions; + } + public Integer getTimeInterval() { + return timeInterval; + } + public void setTimeInterval(int timeInterval) { + this.timeInterval = timeInterval; + } + public Integer getTimeOutRuby() { + return timeOutRuby; + } + public void setTimeOutRuby(int timeOutRuby) { + this.timeOutRuby = timeOutRuby; + } + public Integer getRetrys() { + return retrys; + } + public void setRetrys(int retrys) { + this.retrys = retrys; + } + public String getGeoLink() { + return geoLink; + } + public void setGeoLink(String geoLink) { + this.geoLink = geoLink; + } + public String getEmailAddress() { + return emailAddress; + } + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + public ClosedLoopSignatures getVerificationSignatures() { + return verificationSignatures; + } + public void setVerificationSignatures( + ClosedLoopSignatures verificationSignatures) { + this.verificationSignatures = verificationSignatures; + } + + /*public ArrayList getD2Services() { + return d2Services; + } + + public void setD2Services(ArrayList d2Services) { + this.d2Services = d2Services; + } + + public ArrayList getSiteNames() { + return siteNames; + } + + public void setSiteNames(ArrayList siteNames) { + this.siteNames = siteNames; + }*/ + + public boolean isvDNS() { + return vDNS; + } + + public void setvDNS(boolean vDNS) { + this.vDNS = vDNS; + } + + public boolean isTrinity() { + return trinity; + } + + public void setTrinity(boolean trinity) { + this.trinity = trinity; + } + + public boolean isvUSP() { + return vUSP; + } + + public void setvUSP(boolean vUSP) { + this.vUSP = vUSP; + } + + public boolean isMcr() { + return mcr; + } + + public void setMcr(boolean mcr) { + this.mcr = mcr; + } + + public boolean isGama() { + return gama; + } + + public void setGama(boolean gama) { + this.gama = gama; + } +} + diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopFaultTriggerUISignatures.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopFaultTriggerUISignatures.java new file mode 100644 index 000000000..6363aa95f --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopFaultTriggerUISignatures.java @@ -0,0 +1,44 @@ +/*- + * ============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.rest.adapter; + + + +public class ClosedLoopFaultTriggerUISignatures { + + private String signatures; + + private String connectSignatures; + + public String getConnectSignatures() { + return connectSignatures; + } + public void setConnectSignatures(String connectSignatures) { + this.connectSignatures = connectSignatures; + } + public String getSignatures() { + return signatures; + } + public void setSignatures(String signatures) { + this.signatures = signatures; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPMBody.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPMBody.java new file mode 100644 index 000000000..1898bc46d --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPMBody.java @@ -0,0 +1,133 @@ +/*- + * ============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.rest.adapter; + + +import java.util.Map; + +public class ClosedLoopPMBody { + + private boolean trinity; + private boolean vUSP; + private boolean mcr; + private boolean gama; + private boolean vDNS; + private String geoLink; + private String vServices; + private String ONAPname; + + private String emailAddress; + + private String serviceTypePolicyName; + + private Map attributes; + private String templateVersion; + + public String getTemplateVersion() { + return templateVersion; + } + + public void setTemplateVersion(String templateVersion) { + this.templateVersion = templateVersion; + } + + public String getONAPname(){ + return ONAPname; + } + + public void setONAPname(String ONAPname){ + this.ONAPname = ONAPname; + } + + public String getvServices() { + return vServices; + } + + public void setvServices(String vServices) { + this.vServices = vServices; + } + + public Map getAttributes() { + return attributes; + } + + public void setAttributes(Map map) { + this.attributes = map; + } + + public String getGeoLink() { + return geoLink; + } + + public void setGeoLink(String geoLink) { + this.geoLink = geoLink; + } + + public String getEmailAddress() { + return emailAddress; + } + + public void setEmailAddress(String emailAddress) { + this.emailAddress = emailAddress; + } + + public String getServiceTypePolicyName() { + return serviceTypePolicyName; + } + + public void setServiceTypePolicyName(String serviceTypePolicyName) { + this.serviceTypePolicyName = serviceTypePolicyName; + } + + public boolean isGama() { + return gama; + } + public void setGama(boolean gama) { + this.gama = gama; + } + public boolean isvDNS() { + return vDNS; + } + public void setvDNS(boolean vDNS) { + this.vDNS = vDNS; + } + + public boolean isTrinity() { + return trinity; + } + public void setTrinity(boolean trinity) { + this.trinity = trinity; + } + public boolean isvUSP() { + return vUSP; + } + public void setvUSP(boolean vUSP) { + this.vUSP = vUSP; + } + public boolean isMcr() { + return mcr; + } + public void setMcr(boolean mcr) { + this.mcr = mcr; + } + +} + diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPerformanceMetrics.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPerformanceMetrics.java new file mode 100644 index 000000000..32839e97a --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPerformanceMetrics.java @@ -0,0 +1,36 @@ +/*- + * ============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.rest.adapter; + + +public class ClosedLoopPerformanceMetrics { + public static final String CLPM_UIFIELD_ONSET_MESSAGE = "Onset Message"; + public static final String CLPM_UIJSON_ONSET_MESSAGE = "attributes.OnsetMessage"; + + public static final String CLPM_UIFIELD_POLICY_NAME = "PolicyName"; + public static final String CLPM_UIJSON_POLICY_NAME = "attributes.PolicyName"; + + public static final String CLPM_UIFIELD_ABATEMENT_MESSAGE = "Abatement Message"; + public static final String CLPM_UIJSON_ABATEMENT_MESSAGE = "attributes.AbatementMessage"; + + public static final String CLPM_UIFIELD_GEOLINK = "Geo Link"; + public static final String CLPM_UIJSON_GEOLINK = "geoLink"; +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPolicy.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPolicy.java new file mode 100644 index 000000000..a230db84e --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPolicy.java @@ -0,0 +1,61 @@ +/*- + * ============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.rest.adapter; + + +public class ClosedLoopPolicy { + public static final String CLFAULT_UIFIELD_D2_SERVICES_TRINITY = "Hosted Voice (Trinity)"; + public static final String CLFAULT_UIJSON_D2_SERVICES_TRINITY = "trinity"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_VUSP = "vUSP"; + public static final String CLFAULT_UIJSON_D2_SERVICES_VUSP = "vUSP"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_MCR = "MCR"; + public static final String CLFAULT_UIJSON_D2_SERVICES_MCR = "mcr"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_GAMMA = "Gamma"; + public static final String CLFAULT_UIJSON_D2_SERVICES_GAMMA = "gama"; + + public static final String CLFAULT_UIFIELD_D2_SERVICES_VDNS = "vDNS"; + public static final String CLFAULT_UIJSON_D2_SERVICES_VDNS = "vDNS"; + + public static final String CLFAULT_UIFIELD_EMAIL_ADDRESS = "Email Address"; + public static final String CLFAULT_UIJSON_EMAIL_ADDRESS = "emailAddress"; + + public static final String CLFAULT_UIFIELD_TRIGGER_SIGNATURE = "Trigger Signature"; + public static final String CLFAULT_UIJSON_TRIGGER_SIGNATURE = "triggerSignaturesUsedForUI.signatures"; + + public static final String CLFAULT_UIFIELD_VERIFICATION_SIGNATURE = "Verification Signature"; + public static final String CLFAULT_UIJSON_VERIFICATION_SIGNATURE = "verificationSignaturesUsedForUI.signatures"; + + public static final String CLFAULT_UIFIELD_CONNECT_ALL_TRAPS = "Connect All Traps"; + public static final String CLFAULT_UIJSON_CONNECT_ALL_TRAPS = "triggerSignaturesUsedForUI.connectSignatures"; + + public static final String CLFAULT_UIFIELD_CONNECT_ALL_FAULTS = "Connect All Faults"; + public static final String CLFAULT_UIJSON_CONNECT_ALL_FAULTS = "verificationSignaturesUsedForUI.connectSignatures"; + + public static final String CLFAULT_UIFIELD_POLICY_STATUS_ACTIVE = "Active"; + public static final String CLFAULT_UIJSON_POLICY_STATUS_ACTIVE = "ACTIVE"; + + public static final String CLFAULT_UIFIELD_POLICY_STATUS_INACTIVE = "InActive"; + public static final String CLFAULT_UIJSON_POLICY_STATUS_INACTIVE = "INACTIVE"; + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPolicyConditions.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPolicyConditions.java new file mode 100644 index 000000000..5b3838985 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPolicyConditions.java @@ -0,0 +1,39 @@ +/*- + * ============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.rest.adapter; + + +public enum ClosedLoopPolicyConditions { + SEND("DCAE should send event notification"), + + NOTSEND("DCAE should not send event notification"); + private String name; + + private ClosedLoopPolicyConditions(String name){ + this.name = name; + } + + @Override + public String toString(){ + return this.name; + } +} + diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPolicyStatus.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPolicyStatus.java new file mode 100644 index 000000000..fd8f2b6cf --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopPolicyStatus.java @@ -0,0 +1,41 @@ +/*- + * ============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.rest.adapter; + + +public enum ClosedLoopPolicyStatus { + ACTIVE("active"), + + INACTIVE("inactive") + ; + + private String name; + + private ClosedLoopPolicyStatus(String name){ + this.name = name; + } + + @Override + public String toString(){ + return this.name; + } +} + diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopSignatures.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopSignatures.java new file mode 100644 index 000000000..b2226f95f --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ClosedLoopSignatures.java @@ -0,0 +1,52 @@ +/*- + * ============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.rest.adapter; + + +public class ClosedLoopSignatures { + + private String signatures; + + private int timeWindow; + + private Integer trapMaxAge; + + public String getSignatures() { + return signatures; + } + public void setSignatures(String signatures) { + this.signatures = signatures; + } + + public Integer getTimeWindow() { + return timeWindow; + } + public void setTimeWindow(Integer timeWindow) { + this.timeWindow = timeWindow; + } + + public Integer getTrapMaxAge() { + return trapMaxAge; + } + public void setTrapMaxAge(Integer trapMaxAge) { + this.trapMaxAge = trapMaxAge; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/DeletePolicyCondition.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/DeletePolicyCondition.java new file mode 100644 index 000000000..b4fb5d973 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/DeletePolicyCondition.java @@ -0,0 +1,38 @@ +/*- + * ============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.rest.adapter; + + +public enum DeletePolicyCondition { + ONE("Are you sure you want to delete Current Version of policy"), + + ALL("Are you sure you want to delete All Versions of policy"); + private String name; + + private DeletePolicyCondition(String name){ + this.name = name; + } + + @Override + public String toString(){ + return this.name; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/DeployNowJson.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/DeployNowJson.java new file mode 100644 index 000000000..6c41253a1 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/DeployNowJson.java @@ -0,0 +1,36 @@ +/*- + * ============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.rest.adapter; + + +public class DeployNowJson { + + protected boolean deployNow; + + // deployNow + public boolean getDeployNow() { + return deployNow; + } + + public void setDeployNow(boolean value) { + this.deployNow = value; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/GridData.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/GridData.java new file mode 100644 index 000000000..77bbf0378 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/GridData.java @@ -0,0 +1,54 @@ +/*- + * ============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.rest.adapter; + + +import java.util.ArrayList; + +public class GridData { + private ArrayList attributes; + private ArrayList transportProtocols; + private ArrayList appProtocols; + + public ArrayList getAttributes() { + return attributes; + } + + public void setAttributes(ArrayList attributes) { + this.attributes = attributes; + } + + public ArrayList getAppProtocols() { + return appProtocols; + } + + public void setAppProtocols(ArrayList appProtocols) { + this.appProtocols = appProtocols; + } + + public ArrayList getTransportProtocols() { + return transportProtocols; + } + + public void setTransportProtocols(ArrayList transportProtocols) { + this.transportProtocols = transportProtocols; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/IdMap.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/IdMap.java new file mode 100644 index 000000000..3557aae11 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/IdMap.java @@ -0,0 +1,42 @@ +/*- + * ============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.rest.adapter; + + +public class IdMap { + + protected String astraId; + protected String vendorId; + + public String getAstraId() { + return astraId; + } + public void setAstraId(String astraId) { + this.astraId = astraId; + } + public String getVendorId() { + return vendorId; + } + public void setVendorId(String vendorId) { + this.vendorId = vendorId; + } + +} \ No newline at end of file diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyExportAdapter.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyExportAdapter.java new file mode 100644 index 000000000..21efb9b48 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyExportAdapter.java @@ -0,0 +1,36 @@ +/*- + * ============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.rest.adapter; + + +import java.util.ArrayList; + +public class PolicyExportAdapter { + + private ArrayList policyDatas; + + public ArrayList getPolicyDatas() { + return policyDatas; + } + public void setPolicyDatas(ArrayList policyDatas) { + this.policyDatas = policyDatas; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java new file mode 100644 index 000000000..9d05e3984 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java @@ -0,0 +1,896 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-PAP-REST + * ================================================================================ + * 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.rest.adapter; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.persistence.EntityManagerFactory; + +import org.onap.policy.rest.jpa.OnapName; + +public class PolicyRestAdapter { + + /* + * + * Note : Make Sure if any variables are added in PolicyRestAdapter.java, add them to PolicyElasticData.java file + * + * + * */ + + + //Common + private Object data; + private String policyName = null; + private String configBodyData = null; + private String configType = null; + private String policyID = null; + private String policyType = null; + private String comboPolicyType; + private String configPolicyType = null; + private String policyDescription = null; + private String onapName = null; + private String configName = null; + private String ruleID = null; + private String parentPath; + private boolean isValidData = false; + private String adminNotification = null; + private boolean isEditPolicy = false; + private boolean isViewPolicy = false; + private boolean isDraft = false; + private Object policyData = null; + private String gitPath; + private boolean readOnly; + private String configHome; + private String configUrl; + private String finalPolicyPath; + private String version; + private String jsonBody; + private String apiflag; + private String prevJsonBody; + private Integer highestVersion; + private EntityManagerFactory entityManagerFactory = null; + private Boolean policyExists = false; + private String oldPolicyFileName = null; + private String domain = null; + private String userId; + private String newFileName; + private String clWarning = null; + private String newCLName = null; + private String existingCLName = null; + //Used by GUI + private OnapName onapNameField; + private Object jsonBodyData; + private String dirPath; + private String configBodyPath; + private ArrayList attributes; + private ArrayList settings; + private ArrayList ruleAlgorithmschoices; + + private LinkedHashMap serviceTypePolicyName; + + private LinkedHashMap verticaMetrics; + private LinkedHashMap description; + private LinkedHashMap attributeFields; + + //ClosedLoop + private String clearTimeOut; + private String trapMaxAge; + private String verificationclearTimeOut; + private Map dynamicLayoutMap; + + //FireWall + private String fwPolicyType; + private ArrayList fwattributes; + private String parentForChild; + private String securityZone; + + //Action & Decision + private String ruleCombiningAlgId = null; + private Map dynamicFieldConfigAttributes; + private Map dynamicSettingsMap; + private Map dropDownMap; + private String actionPerformer = null; + private String actionAttribute = null; + private List dynamicRuleAlgorithmLabels; + private List dynamicRuleAlgorithmCombo; + private List dynamicRuleAlgorithmField1; + private List dynamicRuleAlgorithmField2; + private List dynamicVariableList; + private List dataTypeList; + private String actionAttributeValue; + private String ruleProvider; + private String actionBody = null; + private String actionDictHeader = null; + private String actionDictType = null; + private String actionDictUrl = null; + private String actionDictMethod = null; + private YAMLParams yamlparams; + + //Rainy Day Decision + private RainyDayParams rainyday; + private Map rainydayMap; + private List errorCodeList; + private List treatmentList; + + //MicroSerice + private String serviceType = null; + private String uuid = null; + private String location = null; + private String priority = null; + private String msLocation = null; + + //BRMS Policies + private String ruleName; + private Map brmsParamBody=null; + private String brmsController = null; + private ArrayList brmsDependency = null; + private LinkedHashMap ruleData; + private LinkedHashMap ruleListData; + private Map drlRuleAndUIParams=null; + + //Safe Policy + private String policyScope; + private String providerComboBox = null; + private String riskType; + private String riskLevel; + private String guard = null; + private String ttlDate; + private Map matching; + + private ArrayList triggerSignatures; + private ArrayList symptomSignatures; + private String logicalConnector; + private String policyStatus; + private String gocServerScope; + private String supressionType; + + + public ArrayList getTriggerSignatures() { + return triggerSignatures; + } + public void setTriggerSignatures(ArrayList triggerSignatures) { + this.triggerSignatures = triggerSignatures; + } + public ArrayList getSymptomSignatures() { + return symptomSignatures; + } + public void setSymptomSignatures(ArrayList symptomSignatures) { + this.symptomSignatures = symptomSignatures; + } + public String getLogicalConnector() { + return logicalConnector; + } + public void setLogicalConnector(String logicalConnector) { + this.logicalConnector = logicalConnector; + } + public String getPolicyStatus() { + return policyStatus; + } + public void setPolicyStatus(String policyStatus) { + this.policyStatus = policyStatus; + } + public String getGocServerScope() { + return gocServerScope; + } + public void setGocServerScope(String gocServerScope) { + this.gocServerScope = gocServerScope; + } + + public String getSupressionType() { + return supressionType; + } + public void setSupressionType(String supressionType) { + this.supressionType = supressionType; + } + + /********************************************************************************/ + + + + public String getComboPolicyType() { + return comboPolicyType; + } + public void setComboPolicyType(String comboPolicyType) { + this.comboPolicyType = comboPolicyType; + } + public String getGitPath() { + return gitPath; + } + public void setGitPath(String gitPath) { + this.gitPath = gitPath; + } + public String getOldPolicyFileName() { + return oldPolicyFileName; + } + public void setOldPolicyFileName(String oldPolicyFileName) { + this.oldPolicyFileName = oldPolicyFileName; + } + public String getDomainDir() { + return domain; + } + public void setDomainDir(String domain) { + this.domain = domain; + } + public Integer getHighestVersion() { + return highestVersion; + } + public void setHighestVersion(Integer highestVersion) { + this.highestVersion = highestVersion; + } + public Object getData() { + return data; + } + public void setData(Object data) { + this.data = data; + } + public String getPolicyName() { + return policyName; + } + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + public String getConfigBodyData() { + return configBodyData; + } + public void setConfigBodyData(String configBodyData) { + this.configBodyData = configBodyData; + } + public String getConfigType() { + return configType; + } + public void setConfigType(String configType) { + this.configType = configType; + } + public String getPolicyID() { + return policyID; + } + public void setPolicyID(String policyID) { + this.policyID = policyID; + } + public String getPolicyType() { + return policyType; + } + public void setPolicyType(String policyType) { + this.policyType = policyType; + } + public String getPolicyDescription() { + return policyDescription; + } + public void setPolicyDescription(String policyDescription) { + this.policyDescription = policyDescription; + } + public String getOnapName() { + return onapName; + } + public void setOnapName(String onapName) { + this.onapName = onapName; + } + public String getConfigName() { + return configName; + } + public void setConfigName(String configName) { + this.configName = configName; + } + public String getRuleID() { + return ruleID; + } + public void setRuleID(String ruleID) { + this.ruleID = ruleID; + } + public String getRuleCombiningAlgId() { + return ruleCombiningAlgId; + } + public void setRuleCombiningAlgId(String ruleCombiningAlgId) { + this.ruleCombiningAlgId = ruleCombiningAlgId; + } + public Map getDynamicFieldConfigAttributes() { + return dynamicFieldConfigAttributes; + } + public void setDynamicFieldConfigAttributes( + Map dynamicFieldConfigAttributes) { + this.dynamicFieldConfigAttributes = dynamicFieldConfigAttributes; + } + public String getParentPath() { + return parentPath; + } + public void setParentPath(String parentPath) { + this.parentPath = parentPath; + } + public boolean isEditPolicy() { + return isEditPolicy; + } + public void setEditPolicy(boolean isEditPolicy) { + this.isEditPolicy = isEditPolicy; + } + public boolean isViewPolicy() { + return isViewPolicy; + } + public void setViewPolicy(boolean isViewPolicy) { + this.isViewPolicy = isViewPolicy; + } + public Object getPolicyData() { + return policyData; + } + public void setPolicyData(Object policyData) { + this.policyData = policyData; + } + public boolean isReadOnly() { + return readOnly; + } + public void setReadOnly(boolean readOnly) { + this.readOnly = readOnly; + } + public String getUserGitPath() { + return gitPath; + } + public void setUserGitPath(String gitPath) { + this.gitPath = gitPath; + } + public boolean isValidData() { + return isValidData; + } + public void setValidData(boolean isValidData) { + this.isValidData = isValidData; + } + public String getAdminNotification() { + return adminNotification; + } + public void setAdminNotification(String adminNotification) { + this.adminNotification = adminNotification; + } + public String getConfigHome() { + return configHome; + } + public void setConfigHome(String configHome) { + this.configHome = configHome; + } + public String getConfigUrl() { + return configUrl; + } + public void setConfigUrl(String configUrl) { + this.configUrl = configUrl; + } + public String getFinalPolicyPath() { + return finalPolicyPath; + } + public void setFinalPolicyPath(String finalPolicyPath) { + this.finalPolicyPath = finalPolicyPath; + } + public String getVersion() { + return version; + } + public void setVersion(String version) { + this.version = version; + } + public String getJsonBody() { + return jsonBody; + } + public void setJsonBody(String jsonBody) { + this.jsonBody = jsonBody; + } + public String getPrevJsonBody() { + return prevJsonBody; + } + public void setPrevJsonBody(String prevJsonBody) { + this.prevJsonBody = prevJsonBody; + } + public String getApiflag() { + return apiflag; + } + public void setApiflag(String apiflag) { + this.apiflag = apiflag; + } + /** + * @return the actionPerformer + */ + public String getActionPerformer() { + return actionPerformer; + } + /** + * @param actionPerformer the actionPerformer to set + */ + public void setActionPerformer(String actionPerformer) { + this.actionPerformer = actionPerformer; + } + /** + * @return the actionAttribute + */ + public String getActionAttribute() { + return actionAttribute; + } + /** + * @param actionAttribute the actionAttribute to set + */ + public void setActionAttribute(String actionAttribute) { + this.actionAttribute = actionAttribute; + } + /** + * @return the dynamicRuleAlgorithmLabels + */ + public List getDynamicRuleAlgorithmLabels() { + return dynamicRuleAlgorithmLabels; + } + /** + * @param dynamicRuleAlgorithmLabels the dynamicRuleAlgorithmLabels to set + */ + public void setDynamicRuleAlgorithmLabels( + List dynamicRuleAlgorithmLabels) { + this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; + } + /** + * @return the dynamicRuleAlgorithmCombo + */ + public List getDynamicRuleAlgorithmCombo() { + return dynamicRuleAlgorithmCombo; + } + /** + * @param dynamicRuleAlgorithmCombo the dynamicRuleAlgorithmCombo to set + */ + public void setDynamicRuleAlgorithmCombo(List dynamicRuleAlgorithmCombo) { + this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; + } + /** + * @return the dynamicRuleAlgorithmField1 + */ + public List getDynamicRuleAlgorithmField1() { + return dynamicRuleAlgorithmField1; + } + /** + * @param dynamicRuleAlgorithmField1 the dynamicRuleAlgorithmField1 to set + */ + public void setDynamicRuleAlgorithmField1( + List dynamicRuleAlgorithmField1) { + this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; + } + /** + * @return the dynamicRuleAlgorithmField2 + */ + public List getDynamicRuleAlgorithmField2() { + return dynamicRuleAlgorithmField2; + } + /** + * @param dynamicRuleAlgorithmField2 the dynamicRuleAlgorithmField2 to set + */ + public void setDynamicRuleAlgorithmField2( + List dynamicRuleAlgorithmField2) { + this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; + } + public Map getDropDownMap() { + return dropDownMap; + } + public void setDropDownMap(Map dropDownMap) { + this.dropDownMap = dropDownMap; + } + + public Map getDynamicSettingsMap() { + return dynamicSettingsMap; + } + public void setDynamicSettingsMap(Map dynamicSettingsMap) { + this.dynamicSettingsMap = dynamicSettingsMap; + } + public List getDynamicVariableList() { + return dynamicVariableList; + } + public void setDynamicVariableList(List dynamicVariableList) { + this.dynamicVariableList = dynamicVariableList; + } + public List getDataTypeList() { + return dataTypeList; + } + public void setDataTypeList(List dataTypeList) { + this.dataTypeList = dataTypeList; + } + public boolean isDraft() { + return isDraft; + } + public void setDraft(boolean isDraft) { + this.isDraft = isDraft; + } + public String getConfigPolicyType() { + return configPolicyType; + } + public void setConfigPolicyType(String configPolicyType) { + this.configPolicyType = configPolicyType; + } + public String getServiceType() { + return serviceType; + } + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + public String getLocation() { + return location; + } + public void setLocation(String location) { + this.location = location; + } + public String getPriority() { + return priority; + } + public void setPriority(String priority) { + this.priority = priority; + } + public Map getBrmsParamBody() { + return brmsParamBody; + } + public void setBrmsParamBody(Map brmsParamBody) { + this.brmsParamBody = brmsParamBody; + } + public EntityManagerFactory getEntityManagerFactory() { + return entityManagerFactory; + } + public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) { + this.entityManagerFactory = entityManagerFactory; + } + /** + * @return the policyExists + */ + public Boolean getPolicyExists() { + return policyExists; + } + /** + * @param policyExists the policyExists to set + */ + public void setPolicyExists(Boolean policyExists) { + this.policyExists = policyExists; + } + public String getPolicyScope() { + return policyScope; + } + + public void setPolicyScope(String domainDir) { + this. policyScope=domainDir; + } + public String getProviderComboBox() { + return providerComboBox; + } + public void setProviderComboBox(String providerComboBox) { + this.providerComboBox = providerComboBox; + } + public String getRiskType() { + return riskType; + } + public void setRiskType(String riskType) { + this.riskType = riskType; + } + public String getGuard() { + return guard; + } + public void setGuard(String guard) { + this.guard = guard; + } + public String getRiskLevel() { + return riskLevel; + } + public void setRiskLevel(String riskLevel) { + this.riskLevel = riskLevel; + } + public String getTtlDate() { + return ttlDate; + } + public void setTtlDate(String ttlDate) { + this.ttlDate = ttlDate; + } + public String getBrmsController() { + return brmsController; + } + public void setBrmsController(String brmsController) { + this.brmsController = brmsController; + } + public ArrayList getBrmsDependency() { + return brmsDependency; + } + public void setBrmsDependency(ArrayList brmsDependency) { + this.brmsDependency = brmsDependency; + } + public Map getMatching() { + return matching; + } + public void setMatching(Map matching) { + this.matching = matching; + } + public String getUserId() { + return userId; + } + public void setUserId(String userId) { + this.userId = userId; + } + public String getNewFileName() { + return newFileName; + } + public void setNewFileName(String newFileName) { + this.newFileName = newFileName; + } + + public String getDomain() { + return domain; + } + public void setDomain(String domain) { + this.domain = domain; + } + public OnapName getOnapNameField() { + return onapNameField; + } + public void setOnapNameField(OnapName onapNameField) { + this.onapNameField = onapNameField; + } + public Object getJsonBodyData() { + return jsonBodyData; + } + public void setJsonBodyData(Object jsonBodyData) { + this.jsonBodyData = jsonBodyData; + } + public String getDirPath() { + return dirPath; + } + public void setDirPath(String dirPath) { + this.dirPath = dirPath; + } + public String getConfigBodyPath() { + return configBodyPath; + } + public void setConfigBodyPath(String configBodyPath) { + this.configBodyPath = configBodyPath; + } + public ArrayList getAttributes() { + return attributes; + } + public void setAttributes(ArrayList attributes) { + this.attributes = attributes; + } + public ArrayList getSettings() { + return settings; + } + public void setSettings(ArrayList settings) { + this.settings = settings; + } + public ArrayList getRuleAlgorithmschoices() { + return ruleAlgorithmschoices; + } + public void setRuleAlgorithmschoices(ArrayList ruleAlgorithmschoices) { + this.ruleAlgorithmschoices = ruleAlgorithmschoices; + } + public LinkedHashMap getServiceTypePolicyName() { + return serviceTypePolicyName; + } + public void setServiceTypePolicyName(LinkedHashMap serviceTypePolicyName) { + this.serviceTypePolicyName = serviceTypePolicyName; + } + public LinkedHashMap getVerticaMetrics() { + return verticaMetrics; + } + public void setVerticaMetrics(LinkedHashMap verticaMetrics) { + this.verticaMetrics = verticaMetrics; + } + public LinkedHashMap getDescription() { + return description; + } + public void setDescription(LinkedHashMap description) { + this.description = description; + } + public LinkedHashMap getAttributeFields() { + return attributeFields; + } + public void setAttributeFields(LinkedHashMap attributeFields) { + this.attributeFields = attributeFields; + } + 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 Map getDynamicLayoutMap() { + return dynamicLayoutMap; + } + public void setDynamicLayoutMap(Map dynamicLayoutMap) { + this.dynamicLayoutMap = dynamicLayoutMap; + } + public String getFwPolicyType() { + return fwPolicyType; + } + public void setFwPolicyType(String fwPolicyType) { + this.fwPolicyType = fwPolicyType; + } + public ArrayList getFwattributes() { + return fwattributes; + } + public void setFwattributes(ArrayList fwattributes) { + this.fwattributes = fwattributes; + } + public String getParentForChild() { + return parentForChild; + } + public void setParentForChild(String parentForChild) { + this.parentForChild = parentForChild; + } + public String getRuleName() { + return ruleName; + } + public void setRuleName(String ruleName) { + this.ruleName = ruleName; + } + public LinkedHashMap getRuleData() { + return ruleData; + } + public void setRuleData(LinkedHashMap ruleData) { + this.ruleData = ruleData; + } + public LinkedHashMap getRuleListData() { + return ruleListData; + } + public void setRuleListData(LinkedHashMap ruleListData) { + this.ruleListData = ruleListData; + } + public String getSecurityZone() { + return securityZone; + } + public void setSecurityZone(String securityZone) { + this.securityZone = securityZone; + } + public String getActionAttributeValue() { + return actionAttributeValue; + } + public void setActionAttributeValue(String actionAttributeValue) { + this.actionAttributeValue = actionAttributeValue; + } + public String getRuleProvider() { + return ruleProvider; + } + public void setRuleProvider(String ruleProvider) { + this.ruleProvider = ruleProvider; + } + public String getMsLocation() { + return msLocation; + } + public void setMsLocation(String msLocation) { + this.msLocation = msLocation; + } + public Map getDrlRuleAndUIParams() { + return drlRuleAndUIParams; + } + public void setDrlRuleAndUIParams(Map drlRuleAndUIParams) { + this.drlRuleAndUIParams = drlRuleAndUIParams; + } + public String getActionBody() { + return actionBody; + } + public void setActionBody(String actionBody) { + this.actionBody = actionBody; + } + public String getActionDictHeader() { + return actionDictHeader; + } + public void setActionDictHeader(String actionDictHeader) { + this.actionDictHeader = actionDictHeader; + } + public String getActionDictType() { + return actionDictType; + } + public void setActionDictType(String actionDictType) { + this.actionDictType = actionDictType; + } + public String getActionDictUrl() { + return actionDictUrl; + } + public void setActionDictUrl(String actionDictUrl) { + this.actionDictUrl = actionDictUrl; + } + public String getActionDictMethod() { + return actionDictMethod; + } + public void setActionDictMethod(String actionDictMethod) { + this.actionDictMethod = actionDictMethod; + } + public String getClWarning() { + return clWarning; + } + public void setClWarning(String clWarning) { + this.clWarning = clWarning; + } + public String getNewCLName() { + return newCLName; + } + public void setNewCLName(String newCLName) { + this.newCLName = newCLName; + } + public String getExistingCLName() { + return existingCLName; + } + public void setExistingCLName(String existingCLName) { + this.existingCLName = existingCLName; + } + public YAMLParams getYamlparams() { + return yamlparams; + } + public void setYamlparams(YAMLParams yamlparams) { + this.yamlparams = yamlparams; + } + /** + * @return the rainyday + */ + public RainyDayParams getRainyday() { + return rainyday; + } + /** + * @param rainyday the rainyday to set + */ + public void setRainyday(RainyDayParams rainyday) { + this.rainyday = rainyday; + } + /** + * @return the errorCodeList + */ + public List getErrorCodeList() { + return errorCodeList; + } + /** + * @param errorCodeList the errorCodeList to set + */ + public void setErrorCodeList(List errorCodeList) { + this.errorCodeList = errorCodeList; + } + /** + * @return the treatmentList + */ + public List getTreatmentList() { + return treatmentList; + } + /** + * @param treatmentList the treatmentList to set + */ + public void setTreatmentList(List treatmentList) { + this.treatmentList = treatmentList; + } + /** + * @return the rainydayMap + */ + public Map getRainydayMap() { + return rainydayMap; + } + /** + * @param rainydayMap the rainydayMap to set + */ + public void setRainydayMap(Map rainydayMap) { + this.rainydayMap = rainydayMap; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PrefixIPList.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PrefixIPList.java new file mode 100644 index 000000000..c9b5b0cf1 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PrefixIPList.java @@ -0,0 +1,72 @@ +/*- + * ============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.rest.adapter; + + + +import java.util.ArrayList; +import java.util.List; + + +public class PrefixIPList { + protected String name; + protected String description; + protected List members; + + 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; + } + + public List getMembers() + { + if(members==null) + { + members= new ArrayList(); + } + return this.members; + } + + public void setMembers(List members) + { + this.members = members; + } + /*public String getValue() { + return value; + } + + + public void setValue(String value) { + this.value = value; + }*/ + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/RainyDayParams.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/RainyDayParams.java new file mode 100644 index 000000000..f465e8605 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/RainyDayParams.java @@ -0,0 +1,100 @@ +package org.onap.policy.rest.adapter; + +import java.util.ArrayList; +import java.util.List; + +public class RainyDayParams { + private String serviceType; + private String vnfType; + private String bbid; + private String workstep; + private ArrayList treatmentTableChoices; + private List errorcode; + private List treatment; + + /** + * @return the serviceType + */ + public String getServiceType() { + return serviceType; + } + /** + * @param serviceType the serviceType to set + */ + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + /** + * @return the vnfType + */ + public String getVnfType() { + return vnfType; + } + /** + * @param vnfType the vnfType to set + */ + public void setVnfType(String vnfType) { + this.vnfType = vnfType; + } + /** + * @return the workstep + */ + public String getWorkstep() { + return workstep; + } + /** + * @param workstep the workstep to set + */ + public void setWorkstep(String workstep) { + this.workstep = workstep; + } + /** + * @return the bbid + */ + public String getBbid() { + return bbid; + } + /** + * @param bbid the bbid to set + */ + public void setBbid(String bbid) { + this.bbid = bbid; + } + /** + * @return the treatmentTableChoices + */ + public ArrayList getTreatmentTableChoices() { + return treatmentTableChoices; + } + /** + * @param treatmentTableChoices the treatmentTableChoices to set + */ + public void setTreatmentTableChoices(ArrayList treatmentTableChoices) { + this.treatmentTableChoices = treatmentTableChoices; + } + /** + * @return the errorcode + */ + public List getErrorcode() { + return errorcode; + } + /** + * @param errorcode the errorcode to set + */ + public void setErrorcode(List errorcode) { + this.errorcode = errorcode; + } + /** + * @return the treatment + */ + public List getTreatment() { + return treatment; + } + /** + * @param treatment the treatment to set + */ + public void setTreatment(List treatment) { + this.treatment = treatment; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServiceGroupJson.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServiceGroupJson.java new file mode 100644 index 000000000..0d06552b1 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServiceGroupJson.java @@ -0,0 +1,83 @@ +/*- + * ============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.rest.adapter; + + +import java.util.ArrayList; +import java.util.List; + +public class ServiceGroupJson { + + protected String name; + protected String description; + protected List members; + + // name + public String getName() { + return name; + } + + public void setName(String value) { + this.name = value; + } + + public boolean equals(Object obj){ + if(obj == null){ + return false; + } + if(this.getClass() != obj.getClass()){ + return false; + } + ServiceGroupJson servGroupobj=(ServiceGroupJson) obj; + if(this.getName().equals(servGroupobj.getName())){ + return true; + } + return false; + } + + public int hashCode() { + return Integer.valueOf(name.charAt(0)+(name.charAt(1))); + } + + // description + public String getDescription() { + return description; + } + + public void setDescription(String value) { + this.description = value; + } + + public List getMembers() + { + if(members==null) + { + members= new ArrayList(); + } + return this.members; + } + + public void setMembers(List members) + { + this.members = members; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServiceListJson.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServiceListJson.java new file mode 100644 index 000000000..f64abb83f --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServiceListJson.java @@ -0,0 +1,111 @@ +/*- + * ============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.rest.adapter; + + + +public class ServiceListJson { + + protected String name; + protected String description; + protected String type; + protected String transportProtocol; + protected String appProtocol; + protected String ports; + // name + public String getName() { + return name; + } + + public void setName(String value) { + this.name = value; + } + + public boolean equals(Object obj){ + if(obj == null){ + return false; + } + if(this.getClass() != obj.getClass()){ + return false; + } + ServiceListJson servobj=(ServiceListJson) obj; + if(this.getName().equals(servobj.getName())){ + return true; + } + return false; + } + + public int hashCode() { + if(name!=null){ + return Integer.valueOf(name.charAt(0)+(name.charAt(1))); + }else{ + return 0; + } + } + + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + // type + public String getType() { + return type; + } + + public void setType(String value) { + this.type = value; + } + + // transportProtocol + public String getTransportProtocol() { + return transportProtocol; + } + + public void setTransportProtocol(String value) { + this.transportProtocol = value; + } + + // appProtocol + public String getAppProtocol() { + return appProtocol; + } + + public void setAppProtocol(String value) { + this.appProtocol = value; + } + + // ports + public String getPorts() { + return ports; + } + + public void setPorts(String value) { + this.ports = value; + } + + + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServiceMembers.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServiceMembers.java new file mode 100644 index 000000000..632d5a4e8 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServiceMembers.java @@ -0,0 +1,48 @@ +/*- + * ============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.rest.adapter; + + + +public class ServiceMembers { + + protected String type; + protected String name; + + // type + public String getType() { + return type; + } + + public void setType(String value) { + this.type = value; + } + + // transportProtocol + public String getName() { + return name; + } + + public void setName(String value) { + this.name = value; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServicesJson.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServicesJson.java new file mode 100644 index 000000000..5cb9e9801 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/ServicesJson.java @@ -0,0 +1,44 @@ +/*- + * ============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.rest.adapter; + + +public class ServicesJson { + + protected String type; + protected String name; + // type + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getName() { + return name; + } + + public void setName(String value) { + this.name = value; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/TagDefines.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/TagDefines.java new file mode 100644 index 000000000..339b0e1f5 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/TagDefines.java @@ -0,0 +1,41 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.adapter; + +public class TagDefines { + String key; + String value; + + public String getKey() { + return key; + } + public void setKey(String key) { + this.key = key; + } + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } + + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/Tags.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/Tags.java new file mode 100644 index 000000000..d046a2f97 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/Tags.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.adapter; + + +import java.util.List; + + +public class Tags { + String ruleName; + List tags; + String tagPickerName; + String networkRole; + + public String getRuleName() { + return ruleName; + } + public void setRuleName(String ruleName) { + this.ruleName = ruleName; + } + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + public String getTagPickerName() { + return tagPickerName; + } + + public void setTagPickerName(String tagPickerName) { + this.tagPickerName = tagPickerName; + } + public String getNetworkRole() { + return networkRole; + } + public void setNetworkRole(String networkRole) { + this.networkRole = networkRole; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/Term.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/Term.java new file mode 100644 index 000000000..7188e3558 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/Term.java @@ -0,0 +1,201 @@ +/*- + * ============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.rest.adapter; + + + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + + +public class Term { + + String position; + protected String ruleName; + protected List fromZones; + protected List toZones; + protected boolean negateSource; //hardcoded + protected boolean negateDestination; //hardcoded + protected List sourceList; + protected List destinationList; + protected List sourceServices; + protected Set destServices; + protected String action; + protected String description; + boolean enabled; //hardcoded + boolean log; //hardcoded + + //position + public String getPosition() { + return position; + } + + public void setPosition(String value) { + this.position = value; + } + + //RuleName + public String getRuleName() { + return ruleName; + } + + public void setRuleName(String value) { + this.ruleName = value; + } + + //From Zone + public List getFromZones() { + if (fromZones==null) + { + fromZones= new ArrayList(); + } + return fromZones; + } + + public void setFromZones(List fromZones) { + this.fromZones = fromZones; + } + + //To Zone + public List getToZones() { + if (toZones==null) + { + toZones= new ArrayList(); + } + return toZones; + } + + public void setToZones(List toZones) { + this.toZones = toZones; + } + + + //Negate Source + public boolean getNegateSource() { + return negateSource; + } + + public void setNegateSource(boolean negateSource) { + this.negateSource = negateSource; + } + + //Negate Destination + public boolean getNegateDestination() { + return negateDestination; + } + + public void setNegateDestination(boolean negateDestination) { + this.negateDestination = negateDestination; + } + + //SourceList + public List getSourceList() + { + if(sourceList==null) + { + sourceList= new ArrayList(); + } + return this.sourceList; + } + + public void setSourceList(List srcList) { + this.sourceList = srcList; + } + + //Destination List + public List getDestinationList() + { + if(destinationList==null) + { + destinationList= new ArrayList(); + } + return this.destinationList; + } + + public void setDestinationList(List destList) { + this.destinationList = destList; + } + + //Source Services + public List getSourceServices() { + if(sourceServices==null) + { + sourceServices= new ArrayList(); + } + return this.sourceServices; + } + + public void setSourceServices(List sourceServices) { + this.sourceServices = sourceServices; + } + + //Destination services. + public Set getDestServices() { + if(destServices==null) + { + destServices= new HashSet(); + } + return this.destServices; + } + + public void setDestServices(Set destServices) { + this.destServices = destServices; + } + + //Action + public String getAction() { + return action; + } + + public void setAction(String value) { + this.action = value; + } + + //description + public String getDescription() { + return description; + } + + public void setDescription(String desc) { + this.description = desc; + } + + //enabled + public boolean getEnabled() { + return enabled; + } + + public void setEnabled(boolean value) { + this.enabled = value; + } + + //Log + public boolean getLog() { + return log; + } + + public void setLog(boolean value) { + this.log = value; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/TermCollector.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/TermCollector.java new file mode 100644 index 000000000..cfc91f089 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/TermCollector.java @@ -0,0 +1,145 @@ +/*- + * ============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.rest.adapter; + + + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + + +public class TermCollector { + private String serviceTypeId; + private String configName; + private DeployNowJson deploymentOption; + private String securityZoneId; + private String vendorServiceId; + private VendorSpecificData vendorSpecificData= new VendorSpecificData(); + + protected Set serviceGroups; + protected Set addressGroups; + protected List firewallRuleList; + + protected List ruleToTag; + + public List getRuleToTag() { + return ruleToTag; + } + + public void setRuleToTag(List ruleToTag) { + this.ruleToTag = ruleToTag; + } + + //SecurityTypeId + public String getServiceTypeId() { + return serviceTypeId; + } + + public void setServiceTypeId(String serviceTypeId) { + this.serviceTypeId = serviceTypeId; + } + + //ConfigName + public String getConfigName() { + return configName; + } + + public void setConfigName(String configName) { + this.configName = configName; + } + + //DeploymentControl + public DeployNowJson getDeploymentOption() { + return deploymentOption; + } + + public void setDeploymentOption(DeployNowJson deploymentOption) { + this.deploymentOption = deploymentOption; + } + + //SecurityZoneId + public String getSecurityZoneId() { + return securityZoneId; + } + public void setSecurityZoneId(String securityZoneId) { + this.securityZoneId = securityZoneId; + } + + + //ServiceGroup + public Set getServiceGroups() { + if(serviceGroups==null) + { + serviceGroups= new HashSet(); + } + return this.serviceGroups; + } + + public void setServiceGroups(Set servListArray) { + this.serviceGroups = servListArray; + } + + //AddressGroup + public Set getAddressGroups() { + if(addressGroups==null) + { + addressGroups= new HashSet(); + } + return this.addressGroups; + } + + public void setAddressGroups(Set addressGroups) { + this.addressGroups = addressGroups; + } + + //FirewallRuleList + public List getFirewallRuleList() { + + if(firewallRuleList==null) + { + firewallRuleList= new ArrayList(); + } + return this.firewallRuleList; + } + + public void setFirewallRuleList(List firewallRuleList) { + this.firewallRuleList = firewallRuleList; + } + + //vendorServiceId + public String getVendorServiceId() { + return vendorServiceId; + } + + public void setVendorServiceId(String vendorServiceId) { + this.vendorServiceId = vendorServiceId; + } + + public VendorSpecificData getVendorSpecificData() { + return vendorSpecificData; + } + + public void setVendorSpecificData(VendorSpecificData vendorSpecificData) { + this.vendorSpecificData = vendorSpecificData; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/VendorSpecificData.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/VendorSpecificData.java new file mode 100644 index 000000000..740aa838c --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/VendorSpecificData.java @@ -0,0 +1,38 @@ +/*- + * ============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.rest.adapter; + +import java.util.ArrayList; +import java.util.List; + +public class VendorSpecificData { + + private List idMap= new ArrayList(); + + public List getIdMap() { + return idMap; + } + + public void setIdMap(List idMap) { + this.idMap = idMap; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/YAMLParams.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/YAMLParams.java new file mode 100644 index 000000000..e67a23ad8 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/YAMLParams.java @@ -0,0 +1,97 @@ +/*- + * ============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.rest.adapter; + +import java.util.List; + +public class YAMLParams { + private String actor; + private String recipe; + private String clname; + private String limit; + private String timeWindow; + private String timeUnits; + private String guardActiveStart; + private String guardActiveEnd; + private List blackList; + private List targets; + + public String getActor() { + return actor; + } + public void setActor(String actor) { + this.actor = actor; + } + public String getRecipe() { + return recipe; + } + public void setRecipe(String recipe) { + this.recipe = recipe; + } + public String getLimit() { + return limit; + } + public void setLimit(String limit) { + this.limit = limit; + } + public String getTimeWindow() { + return timeWindow; + } + public void setTimeWindow(String timeWindow) { + this.timeWindow = timeWindow; + } + public String getGuardActiveStart() { + return guardActiveStart; + } + public void setGuardActiveStart(String guardActiveStart) { + this.guardActiveStart = guardActiveStart; + } + public String getGuardActiveEnd() { + return guardActiveEnd; + } + public void setGuardActiveEnd(String guardActiveEnd) { + this.guardActiveEnd = guardActiveEnd; + } + public List getBlackList() { + return blackList; + } + public void setBlackList(List blackList) { + this.blackList = blackList; + } + public String getClname() { + return clname; + } + public void setClname(String clname) { + this.clname = clname; + } + public String getTimeUnits() { + return timeUnits; + } + public void setTimeUnits(String timeUnits) { + this.timeUnits = timeUnits; + } + public List getTargets() { + return targets; + } + public void setTargets(List targets) { + this.targets = targets; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/package-info.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/package-info.java new file mode 100644 index 000000000..29ad2551c --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/package-info.java @@ -0,0 +1,20 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.adapter; \ No newline at end of file diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/dao/CommonClassDao.java b/ONAP-REST/src/main/java/org/onap/policy/rest/dao/CommonClassDao.java new file mode 100644 index 000000000..c486f53cb --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/dao/CommonClassDao.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.dao; + +import java.util.List; + +import org.onap.policy.rest.jpa.PolicyRoles; + +public interface CommonClassDao { + + //Common methods + List getData(@SuppressWarnings("rawtypes") Class className); + List getDataById(@SuppressWarnings("rawtypes") Class className, String columnName, String key); + List getDataByColumn(@SuppressWarnings("rawtypes") Class className, String columnName); + List checkDuplicateEntry(String value, String columnName, @SuppressWarnings("rawtypes") Class className); + Object getEntityItem(@SuppressWarnings("rawtypes") Class className, String columnName, String key); + List getDataByQuery(String query); + List getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, String columnName, List data); + void save(Object entity); + void delete(Object entity); + void update(Object entity); + void updateQuery(String query); + + //Group Policy Scope + List checkExistingGroupListforUpdate(String groupListValue, String groupNameValue); + + + //Roles + List getUserRoles(); + + + //ClosedLoops + void updateClAlarms(String clName, String alarms); + void updateClYaml(String clName, String yaml); + void deleteAll(); + + + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/dao/package-info.java b/ONAP-REST/src/main/java/org/onap/policy/rest/dao/package-info.java new file mode 100644 index 000000000..2d8be25c4 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/dao/package-info.java @@ -0,0 +1,21 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.dao; diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionBodyEntity.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionBodyEntity.java new file mode 100644 index 000000000..e65b317d0 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionBodyEntity.java @@ -0,0 +1,195 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Lob; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import javax.persistence.Version; +/* + * The Entity class to persist a policy object Action Body + */ + +import com.fasterxml.jackson.annotation.JsonBackReference; + +@Entity +@Table(name="ActionBodyEntity") +@NamedQueries({ + @NamedQuery(name=" ActionBodyEntity.findAll", query="SELECT e FROM ActionBodyEntity e "), + @NamedQuery(name="ActionBodyEntity.deleteAll", query="DELETE FROM ActionBodyEntity WHERE 1=1") +}) + +public class ActionBodyEntity implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="actionBodyId") + @JsonBackReference + private long actionBodyId; + + @Column(name="actionBodyName", nullable=false, length=255) + private String actionBodyName = ""; + + @Version + @Column(name="version") + private int version; + + @Lob + @Column(name="actionBody", nullable=false, columnDefinition="TEXT") + private String actionBody = "NoBody"; + + @Column(name="created_by", nullable=false, length=255) + private String createdBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Column(name="modified_by", nullable=false, length=255) + private String modifiedBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @Column(name="deleted", nullable=false) + private boolean deleted = false; + + public ActionBodyEntity() { + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + } + /** + * @return the configurationDataId + */ + public long getActionBodyId() { + return actionBodyId; + } + /** + * @param configurationDataId the configurationDataId to set + */ + public void setActionBodyName(String name) { + this.actionBodyName = name; + } + public String getActionBodyName(){ + return this.actionBodyName; + } + + /** + * @return the actionBody + */ + public String getActionBody() { + return actionBody; + } + /** + * @param configBody the configBody to set + */ + public void setActionBody(String body) { + this.actionBody = body; + } + /** + * @return the createdBy + */ + public String getCreatedBy() { + return createdBy; + } + /** + * @param createdBy the createdBy to set + */ + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + /** + * @return the modifiedBy + */ + public String getModifiedBy() { + return modifiedBy; + } + /** + * @param modifiedBy the modifiedBy to set + */ + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + /** + * @return the modifiedDate + */ + public Date getModifiedDate() { + return modifiedDate; + } + /** + * @param modifiedDate the modifiedDate to set + */ + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + /** + * @return the version + */ + public int getVersion() { + return version; + } + /** + * @return the createdDate + */ + public Date getCreatedDate() { + return createdDate; + } + + /** + * @return the deleted + */ + public boolean isDeleted() { + return deleted; + } + + /** + * @param deleted the deleted to set + */ + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionList.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionList.java new file mode 100644 index 000000000..6be8cd7a8 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionList.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + +@Entity +@Table(name="actionlist") +@NamedQuery(name="ActionList.findAll", query="SELECT e FROM ActionList e ") +public class ActionList implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="actionname", nullable=false) + @OrderBy("asc") + private String actionName; + + @Column(name="description") + private String description; +/* + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate;*/ + + public ActionList() { + + } + public ActionList(String string, String userid) { + this(domain); + + } + public ActionList(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + public String getActionName() { + return this.actionName; + } + + public void setActionName(String actionName) { + this.actionName = actionName; + + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionPolicyDict.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionPolicyDict.java new file mode 100644 index 000000000..bf8a73161 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ActionPolicyDict.java @@ -0,0 +1,211 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.rest.XacmlAdminAuthorization; + + +@Entity +@Table(name="ActionPolicyDict") +@NamedQueries({ + @NamedQuery(name="ActionPolicyDict.findAll", query="SELECT e FROM ActionPolicyDict e") +}) +public class ActionPolicyDict implements Serializable { + private static final long serialVersionUID = 1L; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="ATTRIBUTE_NAME", nullable=false) + @OrderBy("asc") + private String attributeName; + + @Column(name="Type", nullable=false) + @OrderBy("asc") + private String type; + + @Column(name="URL", nullable=false) + @OrderBy("asc") + private String url; + + @Column(name="Method", nullable=false) + @OrderBy("asc") + private String method; + + @Column(name="Headers", nullable=true) + @OrderBy("asc") + private String header; + + @Column(name="Body", nullable=true) + @OrderBy("asc") + private String body; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + private static Log logger = LogFactory.getLog(ActionPolicyDict.class); + public ActionPolicyDict() { + + } + + public ActionPolicyDict(String string, String userid) { + this(string); + } + + public ActionPolicyDict(String domain) { + this.type = domain; + } + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy =XacmlAdminAuthorization.getUserId();; + } catch (Exception e) { + logger.error("Exception caused While adding Modified by Role"+e); + //PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "ActionPolicyDict", "Exception caused While adding Modified by Role"); + } + } + public int getId() { + return this.id; + } + public void setId(int id) { + this.id = id; + } + + public Date getCreatedDate() { + return this.createdDate; + } + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + public String getDescription() { + return this.description; + } + public void setDescription(String description) { + this.description = description; + } + + public Date getModifiedDate() { + return this.modifiedDate; + } + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + public String getUrl() { + return url; + } + public void setUrl(String url) { + this.url = url; + } + public String getMethod() { + return method; + } + public void setMethod(String method) { + this.method = method; + } + public String getHeader() { + return header; + } + public void setHeader(String header) { + this.header = header; + } + + public String getBody() { + return body; + } + public void setBody(String body) { + this.body = body; + } + public String getAttributeName() { + return attributeName; + } + public void setAttributeName(String attributeName) { + this.attributeName = attributeName; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/AddressGroup.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/AddressGroup.java new file mode 100644 index 000000000..2a14e709a --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/AddressGroup.java @@ -0,0 +1,114 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + +@Entity +@Table(name="AddressGroup") +@NamedQuery(name="AddressGroup.findAll", query="SELECT e FROM AddressGroup e ") +public class AddressGroup implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String name; + + @Column(name="prefixlist") + private String prefixList; + + + @Column(name="description") + private String description; + + public AddressGroup() { + + } + public AddressGroup(String string, String userid) { + this(domain); + + } + public AddressGroup(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getGroupName() { + return this.name; + } + + public void setGroupName(String serviceName) { + this.name = serviceName; + + } + + public String getPrefixList() { + return this.prefixList; + } + + public void setServiceList(String prefixList) { + this.prefixList = prefixList; + + } + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Attribute.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Attribute.java new file mode 100644 index 000000000..7285e2e36 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Attribute.java @@ -0,0 +1,363 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OneToMany; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import javax.persistence.Transient; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.rest.XacmlAdminAuthorization; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +/** + * The persistent class for the Attribute database table. + * + */ +@Entity +@Table(name="Attribute") +@NamedQuery(name="Attribute.findAll", query="SELECT a FROM Attribute a order by a.priority asc, a.xacmlId asc") +public class Attribute implements Serializable { + private static final long serialVersionUID = 1L; + private static final Log logger = LogFactory.getLog(Attribute.class); + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + //bi-directional many-to-one association to Category + @ManyToOne + @JoinColumn(name="constraint_type", nullable=true) + @JsonIgnore + private ConstraintType constraintType; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @Column(name="PRIORITY", nullable=true) + @OrderBy("asc") + private String priority; + + @Column(name="ATTRIBUTE_VALUE", nullable=true) + @OrderBy("asc") + private String attributeValue; + + @Column(name="xacml_id", unique = true, nullable=false) + @OrderBy("asc") + private String xacmlId = "urn"; + + //bi-directional many-to-one association to ConstraintValue + @OneToMany(mappedBy="attribute", orphanRemoval=true, cascade=CascadeType.REMOVE) + @JsonIgnore + private Set constraintValues = new HashSet<>(); + + //bi-directional many-to-one association to Category + @ManyToOne + @JoinColumn(name="category") + @JsonIgnore + private Category categoryBean; + + //bi-directional many-to-one association to Datatype + @ManyToOne + @JoinColumn(name="datatype") + private Datatype datatypeBean; + + @Column(name="is_designator", nullable=false) + @JsonIgnore + private char isDesignator = '1'; + + @Column(name="selector_path", nullable=true, length=2048) + private String selectorPath; + + + + @Transient + private String issuer = null; + + @Transient + private boolean mustBePresent = false; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + + public Attribute() { + } + + public Attribute(String domain) { + this.xacmlId = domain; + } + + public Attribute(Attribute copy) { + this(copy.getXacmlId() + ":(0)"); + this.constraintType = copy.getConstraintType(); + this.categoryBean = copy.getCategoryBean(); + this.datatypeBean = copy.getDatatypeBean(); + this.description = copy.getDescription(); + for (ConstraintValue value : copy.getConstraintValues()) { + ConstraintValue newValue = new ConstraintValue(value); + newValue.setAttribute(this); + this.addConstraintValue(newValue); + } + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy = XacmlAdminAuthorization.getUserId(); + } catch (Exception e) { + logger.error("Exception caused While adding Modified by Role"+e); + } + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public ConstraintType getConstraintType() { + return this.constraintType; + } + + public void setConstraintType(ConstraintType constraintType) { + this.constraintType = constraintType; + } + + public Date getCreatedDate() { + return this.createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getModifiedDate() { + return this.modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public String getXacmlId() { + return this.xacmlId; + } + +/* @Transient + public Identifier getXacmlIdentifier() { + return new IdentifierImpl(this.xacmlId); + }*/ + + public void setXacmlId(String xacmlId) { + this.xacmlId = xacmlId; + } + + public Set getConstraintValues() { + return this.constraintValues; + } + + public void setConstraintValues(Set constraintValues) { + for (ConstraintValue value : this.constraintValues) { + value.setAttribute(this); + } + this.constraintValues = constraintValues; + } + + public ConstraintValue addConstraintValue(ConstraintValue constraintValue) { + if (this.constraintValues == null) { + this.constraintValues = new HashSet<>(); + } + this.constraintValues.add(constraintValue); + constraintValue.setAttribute(this); + + return constraintValue; + } + + public ConstraintValue removeConstraintValue(ConstraintValue constraintValue) { + this.constraintValues.remove(constraintValue); + constraintValue.setAttribute(null); + + return constraintValue; + } + + public void removeAllConstraintValues() { + if (this.constraintValues == null) { + return; + } + for (ConstraintValue value : this.constraintValues) { + value.setAttribute(null); + } + this.constraintValues.clear(); + } + + public Category getCategoryBean() { + return this.categoryBean; + } + + public void setCategoryBean(Category categoryBean) { + this.categoryBean = categoryBean; + } + + public Datatype getDatatypeBean() { + return this.datatypeBean; + } + + public void setDatatypeBean(Datatype datatypeBean) { + this.datatypeBean = datatypeBean; + } + + public char getIsDesignator() { + return this.isDesignator; + } + + public void setIsDesignator(char is) { + this.isDesignator = is; + } + + public String getSelectorPath() { + return this.selectorPath; + } + + public void setSelectorPath(String path) { + this.selectorPath = path; + } + + @Transient + public String getIssuer() { + return issuer; + } + + @Transient + public void setIssuer(String issuer) { + this.issuer = issuer; + } + + @Transient + public boolean isMustBePresent() { + return mustBePresent; + } + + @Transient + public void setMustBePresent(boolean mustBePresent) { + this.mustBePresent = mustBePresent; + } + + @Transient + public boolean isDesignator() { + return (this.isDesignator == '1'); + } + + @Transient + public void setIsDesignator(boolean is) { + if (is) { + this.isDesignator = '1'; + } else { + this.isDesignator = '0'; + } + } + + public String getPriority() { + return priority; + } + + public void setPriority(String priority) { + this.priority = priority; + } + + public String getAttributeValue() { + return attributeValue; + } + + public void setAttributeValue(String attributeValue) { + this.attributeValue = attributeValue; + } +} + diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/AttributeAssignment.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/AttributeAssignment.java new file mode 100644 index 000000000..7a1be9e7d --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/AttributeAssignment.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +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.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.Table; + + +/** + * The persistent class for the ObadviceExpressions database table. + * + */ +@Entity +@Table(name="AttributeAssignment") +@NamedQuery(name="AttributeAssignment.findAll", query="SELECT a FROM AttributeAssignment a") +public class AttributeAssignment implements Serializable { + private static final long serialVersionUID = 1L; + + public static final String EXPRESSION_APPLY = "Apply"; + public static final String EXPRESSION_SELECTOR = "AttributeSelector"; + public static final String EXPRESSION_VALUE = "AttributeValue"; + public static final String EXPRESSION_FUNCTION = "Function"; + public static final String EXPRESSION_REFERENCE = "VarableReference"; + public static final String EXPRESSION_DESIGNATOR = "AttributeDesignator"; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="attribute_id") + private int attributeId; + + //bi-directional many-to-one association to Obadvice + @Column(name="expression", nullable=false) + private String expression; + + //bi-directional many-to-one association to Obadvice + @ManyToOne + private Obadvice obadvice; + + public AttributeAssignment() { + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public int getAttributeId() { + return this.attributeId; + } + + public void setAttributeId(int attributeId) { + this.attributeId = attributeId; + } + + public String getExpression() { + return expression; + } + + public void setExpression(String expression) { + this.expression = expression; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BRMSController.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BRMSController.java new file mode 100644 index 000000000..af2b11a20 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BRMSController.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="BRMSController") +@NamedQuery(name="BRMSController.findAll", query="SELECT b from BRMSController b ") +public class BRMSController implements Serializable{ + private static final long serialVersionUID = -8666947569754164177L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="controller_name", nullable=false, length=1024, unique=true) + @OrderBy("asc") + private String controllerName; + + @Column(name="description", nullable=true, length=1024) + private String description; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + @Column(name="controller", nullable=false) + private String controller; + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public Date getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + public String getController() { + return controller; + } + + public void setController(String controller) { + this.controller = controller; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getControllerName() { + return controllerName; + } + + public void setControllerName(String controllerName) { + this.controllerName = controllerName; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BRMSDependency.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BRMSDependency.java new file mode 100644 index 000000000..d06ec5d92 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BRMSDependency.java @@ -0,0 +1,153 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +@Entity +@Table(name="BRMSDependency") +@NamedQuery(name="BRMSDependency.findAll", query="SELECT b from BRMSDependency b ") +public class BRMSDependency implements Serializable{ + private static final long serialVersionUID = -7005622785653160761L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="dependency_name", nullable=false, length=1024, unique=true) + @OrderBy("asc") + private String dependencyName; + + @Column(name="description", nullable=true, length=1024) + private String description; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + @Column(name="dependency", nullable=false) + private String dependency; + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public Date getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + public String getDependency() { + return dependency; + } + + public void setDependency(String dependency) { + this.dependency = dependency; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getDependencyName() { + return dependencyName; + } + + public void setDependencyName(String dependencyName) { + this.dependencyName = dependencyName; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BRMSParamTemplate.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BRMSParamTemplate.java new file mode 100644 index 000000000..5a78df227 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/BRMSParamTemplate.java @@ -0,0 +1,142 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.Lob; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.onap.policy.rest.jpa.UserInfo; + +/* + * JPA for the BRMS Param Template. + * + * @version: 0.1 + */ + + +@Entity +@Table(name="BRMSParamTemplate") +@NamedQuery(name="BRMSParamTemplate.findAll", query="SELECT b FROM BRMSParamTemplate b ") +public class BRMSParamTemplate implements Serializable{ + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="param_template_name", nullable=false, unique=true) + @OrderBy("asc") + private String ruleName; + + @Lob + @Column(name="rule",nullable=false) + private String rule; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public BRMSParamTemplate(){ + } + + public BRMSParamTemplate(String userid){ + + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + + public Date getCreatedDate() { + return this.createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getRule(){ + return this.rule; + } + + public void setRule(String rule){ + this.rule = rule; + } + + public String getRuleName(){ + return this.ruleName; + } + + public void setRuleName(String ruleName){ + this.ruleName = ruleName; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Category.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Category.java new file mode 100644 index 000000000..1d0f0e456 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Category.java @@ -0,0 +1,218 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +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.OneToMany; +import javax.persistence.Table; +import javax.persistence.Transient; + +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.IdentifierImpl; +import com.fasterxml.jackson.annotation.JsonBackReference; + + +/** + * The persistent class for the Categories database table. + * + */ +@Entity +@Table(name="Category") +@NamedQuery(name="Category.findAll", query="SELECT c FROM Category c") +public class Category implements Serializable { + private static final long serialVersionUID = 1L; + + public static final char STANDARD = 'S'; + public static final char CUSTOM = 'C'; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="grouping", nullable=false, length=64) + private String grouping; + + @Column(name="is_standard", nullable=false) + private char isStandard; + + @Column(name="xacml_id", nullable=false, unique=true, length=255) + private String xacmlId; + + @Column(name="short_name", nullable=false, length=64) + private String shortName; + + //bi-directional many-to-one association to Attribute + @OneToMany(mappedBy="categoryBean") + @JsonBackReference + private Set attributes = new HashSet<>(); + + public Category() { + this.xacmlId = XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT.stringValue(); + this.grouping = "subject"; + this.isStandard = Category.STANDARD; + this.shortName = "subject"; + } + + public Category(Identifier cat, String grouping, char isStandard) { + if (cat != null) { + this.xacmlId = cat.stringValue(); + } + this.isStandard = isStandard; + if (grouping != null) { + this.grouping = grouping; + } else { + this.grouping = Category.extractGrouping(this.xacmlId); + } + } + + public Category(Identifier cat, String grouping) { + this(cat, grouping, Category.STANDARD); + } + + public Category(Identifier cat, char standard) { + this(cat, null, standard); + } + + public Category(Identifier cat) { + this(cat, Category.STANDARD); + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getGrouping() { + return this.grouping; + } + + public void setGrouping(String grouping) { + this.grouping = grouping; + } + + public char getIsStandard() { + return this.isStandard; + } + + public void setIsStandard(char isStandard) { + this.isStandard = isStandard; + } + + public String getXacmlId() { + return this.xacmlId; + } + + public void setXacmlId(String xacmlId) { + this.xacmlId = xacmlId; + } + + public String getShortName() { + return this.shortName; + } + + public void setShortName(String shortName) { + this.shortName = shortName; + } + + public Set getAttributes() { + return this.attributes; + } + + public void setAttributes(Set attributes) { + this.attributes = attributes; + } + + public Attribute addAttribute(Attribute attribute) { + getAttributes().add(attribute); + attribute.setCategoryBean(this); + + return attribute; + } + + public Attribute removeAttribute(Attribute attribute) { + getAttributes().remove(attribute); + attribute.setCategoryBean(null); + + return attribute; + } + + @Transient + public boolean isStandard() { + return (this.isStandard == Category.STANDARD); + } + + @Transient + public boolean isCustom() { + return (this.isStandard == Category.CUSTOM); + } + + @Transient + public static String extractGrouping(String xacmlId) { + if (xacmlId == null) { + return null; + } + if (xacmlId.matches(".*:attribute\\-category:.*")) { + String[] parts = xacmlId.split("[:]"); + if (parts != null && parts.length > 0) { + return parts[parts.length - 1]; + } + } else if (xacmlId.matches(".*:[a-zA-Z]+[\\-]category:.*")) { + String[] parts = xacmlId.split("[:]"); + if (parts != null && parts.length > 0) { + for (String part : parts) { + int index = part.indexOf("-category"); + if (index > 0) { + return part.substring(0, index); + } + } + } + } + return null; + } + + @Transient + public Identifier getIdentifer() { + return new IdentifierImpl(this.xacmlId); + } + + @Transient + @Override + public String toString() { + return "Category [id=" + id + ", grouping=" + grouping + + ", isStandard=" + isStandard + ", xacmlId=" + xacmlId + + ", attributes=" + attributes + "]"; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ClosedLoopD2Services.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ClosedLoopD2Services.java new file mode 100644 index 000000000..f4ade220e --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ClosedLoopD2Services.java @@ -0,0 +1,175 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + * + */ +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.rest.XacmlAdminAuthorization; + + +@Entity +@Table(name = "ClosedLoopD2Services") +@NamedQuery(name="ClosedLoopD2Services.findAll", query="SELECT c FROM ClosedLoopD2Services c ") +public class ClosedLoopD2Services implements Serializable{ + private static final long serialVersionUID = 1L; + + private static String domain; + + + @Id + @Column(name ="id") + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + + @Column(name="service_Name", nullable=false, unique=true) + @OrderBy("asc") + private String serviceName; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + private static Log LOGGER = LogFactory.getLog(ClosedLoopD2Services.class); + + public ClosedLoopD2Services(){ + + } + + public ClosedLoopD2Services(String string, String userid) { + this(domain); + } + + public ClosedLoopD2Services(String domain) { + this.serviceName = domain; + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy = XacmlAdminAuthorization.getUserId();; + } catch (Exception e) { + LOGGER.error("Exception caused While adding Modified by Role"+e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "ClosedLoopD2Services", "Exception caused While adding Modified by Role"); + } + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public Date getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ClosedLoopSite.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ClosedLoopSite.java new file mode 100644 index 000000000..6fbf9fb11 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ClosedLoopSite.java @@ -0,0 +1,177 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +/* + * + */ +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.rest.XacmlAdminAuthorization; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + + +@Entity +@Table(name = "ClosedLoopSite") +@NamedQuery(name="ClosedLoopSite.findAll", query="SELECT c FROM ClosedLoopSite c ") +public class ClosedLoopSite implements Serializable{ + private static final long serialVersionUID = 1L; + + private static String domain; + + + @Id + @Column(name ="id") + @GeneratedValue(strategy = GenerationType.AUTO) + private int id; + + @Column(name="site_Name", nullable=false, unique=true) + @OrderBy("asc") + private String siteName; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + private static Log LOGGER = LogFactory.getLog(ClosedLoopSite.class); + + public ClosedLoopSite(){ + + } + + public ClosedLoopSite(String string, String userid) { + this(domain); + } + + public ClosedLoopSite(String domain) { + this.siteName = domain; + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy = XacmlAdminAuthorization.getUserId();; + } catch (Exception e) { + LOGGER.error("Exception caused While adding Modified by Role"+e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "ClosedLoopSite", "Exception caused While adding Modified by Role"); + } + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getSiteName() { + return siteName; + } + + public void setSiteName(String siteName) { + this.siteName = siteName; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public Date getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ClosedLoops.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ClosedLoops.java new file mode 100644 index 000000000..bb5b4bda7 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ClosedLoops.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +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.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.Table; + +@Entity +@Table(name="ClosedLoops") +@NamedQueries({ + @NamedQuery(name="ClosedLoops.findAll", query="SELECT e FROM ClosedLoops e"), + @NamedQuery(name="ClosedLoops.deleteAll", query="DELETE FROM ClosedLoops WHERE 1=1") +}) +public class ClosedLoops implements Serializable { + + /** + * + */ + private static final long serialVersionUID = -7796845092457926842L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="closedLoopControlName", nullable=false, length=255) + @OrderBy("asc") + private String closedLoopControlName; + + @Column(name="alarmConditions", nullable=true, length=255) + private String alarmConditions; + + @Column(name="yaml", nullable=true, length=1028) + private String yaml; + + public ClosedLoops() { + + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getClosedLoopControlName() { + return closedLoopControlName; + } + + public void setClosedLoopControlName(String closedLoopControlName) { + this.closedLoopControlName = closedLoopControlName; + } + + public String getAlarmConditions() { + return alarmConditions; + } + + public void setAlarmConditions(String alarmConditions) { + this.alarmConditions = alarmConditions; + } + + public String getYaml() { + return yaml; + } + + public void setYaml(String yaml) { + this.yaml = yaml; + } + +} \ No newline at end of file diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConfigurationDataEntity.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConfigurationDataEntity.java new file mode 100644 index 000000000..e755d6fc5 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConfigurationDataEntity.java @@ -0,0 +1,224 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Lob; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import javax.persistence.Version; +/* + * The Entity class to persist a policy object configuration data + */ + +import com.fasterxml.jackson.annotation.JsonBackReference; + +@Entity +@Table(name="ConfigurationDataEntity") +@NamedQueries({ + @NamedQuery(name="ConfigurationDataEntity.findAll", query="SELECT e FROM ConfigurationDataEntity e "), + @NamedQuery(name="ConfigurationDataEntity.deleteAll", query="DELETE FROM ConfigurationDataEntity WHERE 1=1") +}) + +public class ConfigurationDataEntity implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="configurationDataId") + @JsonBackReference + private long configurationDataId; + + @Column(name="configurationName", nullable=false, length=255) + private String configurationName = ""; + + @Version + @Column(name="version") + private int version; + + @Column(name="configType", nullable=false, length=255) + private String configType = "NoType"; + + @Lob + @Column(name="configBody", nullable=false, columnDefinition="TEXT") + private String configBody = "NoBody"; + + @Column(name="created_by", nullable=false, length=255) + private String createdBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Column(name="description", nullable=false, length=2048) + private String description = "NoDescription"; + + @Column(name="modified_by", nullable=false, length=255) + private String modifiedBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @Column(name="deleted", nullable=false) + private boolean deleted = false; + + public ConfigurationDataEntity() { + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + } + /** + * @return the configurationDataId + */ + public long getConfigurationDataId() { + return configurationDataId; + } + /** + * @param configurationDataId the configurationDataId to set + */ + public void setConfigurationName(String configurationName) { + this.configurationName = configurationName; + } + public String getConfigurationName(){ + return this.configurationName; + } + /** + * @return the configType + */ + public String getConfigType() { + return configType; + } + /** + * @param configType the configType to set + */ + public void setConfigType(String configType) { + this.configType = configType; + } + /** + * @return the configBody + */ + public String getConfigBody() { + return configBody; + } + /** + * @param configBody the configBody to set + */ + public void setConfigBody(String configBody) { + this.configBody = configBody; + } + /** + * @return the createdBy + */ + public String getCreatedBy() { + return createdBy; + } + /** + * @param createdBy the createdBy to set + */ + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + /** + * @return the description + */ + public String getDescription() { + return description; + } + /** + * @param description the description to set + */ + public void setDescription(String description) { + this.description = description; + } + /** + * @return the modifiedBy + */ + public String getModifiedBy() { + return modifiedBy; + } + /** + * @param modifiedBy the modifiedBy to set + */ + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + /** + * @return the modifiedDate + */ + public Date getModifiedDate() { + return modifiedDate; + } + /** + * @param modifiedDate the modifiedDate to set + */ + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + /** + * @return the version + */ + public int getVersion() { + return version; + } + /** + * @return the createdDate + */ + public Date getCreatedDate() { + return createdDate; + } + + /** + * @return the deleted + */ + public boolean isDeleted() { + return deleted; + } + + /** + * @param deleted the deleted to set + */ + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConstraintType.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConstraintType.java new file mode 100644 index 000000000..eeadeb0fc --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConstraintType.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +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.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name="ConstraintType") +@NamedQuery(name="ConstraintType.findAll", query="SELECT a FROM ConstraintType a") +public class ConstraintType implements Serializable { + private static final long serialVersionUID = 1L; + + public static final String ENUMERATION_TYPE = "Enumeration"; + public static final String RANGE_TYPE = "Range"; + public static final String REGEXP_TYPE = "Regular Expression"; + + protected static final Map defaults = new HashMap<>(); + static { + defaults.put(ENUMERATION_TYPE, "Enumerate a set of values that the attribute may be set to during policy creation."); + defaults.put(RANGE_TYPE, "Set a range of min and/or max integer/double values the attribute can be set to during policy creation."); + defaults.put(REGEXP_TYPE, "Define a regular expression the attribute must match against during policy creation."); + } + private static final String[] RANGE_TYPES = {"minExclusive", "minInclusive", "maxExclusive", "maxInclusive"}; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="constraint_type", nullable=false, length=64) + private String constraintType; + + @Column(name="description", nullable=false, length=255) + private String description; + + //bi-directional many-to-one association to Attribute + @OneToMany(mappedBy="constraintType") + private Set attributes = new HashSet<>(); + + public ConstraintType() { + + } + + public ConstraintType(String constraintType) { + this(); + this.constraintType = constraintType; + } + + public ConstraintType(String constraintType, String description) { + this(constraintType); + this.description = description; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getConstraintType() { + return constraintType; + } + + public void setConstraintType(String constraintType) { + this.constraintType = constraintType; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Set getAttributes() { + return attributes; + } + + public void setAttributes(Set attributes) { + this.attributes = attributes; + } + + public static String[] getRangeTypes() { + return RANGE_TYPES; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConstraintValue.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConstraintValue.java new file mode 100644 index 000000000..57e9af8b8 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ConstraintValue.java @@ -0,0 +1,116 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +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.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.Table; + + +/** + * The persistent class for the ConstraintValues database table. + * + */ +@Entity +@Table(name="ConstraintValues") +@NamedQuery(name="ConstraintValue.findAll", query="SELECT c FROM ConstraintValue c") +public class ConstraintValue implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="property") + private String property; + + @Column(name="value") + private String value; + + //bi-directional many-to-one association to Attribute + @ManyToOne + @JoinColumn(name="attribute_id") + private Attribute attribute; + + public ConstraintValue() { + } + + public ConstraintValue(String property, String value) { + this.property = property; + this.value = value; + } + + public ConstraintValue(ConstraintValue value) { + this.property = value.getProperty(); + this.value = value.getValue(); + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getProperty() { + return this.property; + } + + public void setProperty(String property) { + this.property = property; + } + + public String getValue() { + return this.value; + } + + public void setValue(String value) { + this.value = value; + } + + public Attribute getAttribute() { + return this.attribute; + } + + public void setAttribute(Attribute attribute) { + this.attribute = attribute; + } + + public ConstraintValue clone() { + ConstraintValue constraint = new ConstraintValue(); + + constraint.property = this.property; + constraint.value = this.value; + constraint.attribute = this.attribute; + + return constraint; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DCAEUsers.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DCAEUsers.java new file mode 100644 index 000000000..27d5d2790 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DCAEUsers.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + + +@Entity +@Table(name="DCAEUsers") +@NamedQuery(name="DCAEUsers.findAll", query="SELECT e FROM DCAEUsers e ") +public class DCAEUsers implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String name; + + @Column(name="description ") + private String description ; + + + public DCAEUsers() { + + } + public DCAEUsers(String string, String userid) { + this(domain); + + } + public DCAEUsers(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + + } + public String getDescriptionValue() { + return this.description ; + } + + public void setDescriptionValue(String description ) { + this.description = description ; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DCAEuuid.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DCAEuuid.java new file mode 100644 index 000000000..b7f9243bc --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DCAEuuid.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + + +@Entity +@Table(name="DCAEuuid") +@NamedQuery(name="DCAEuuid.findAll", query="SELECT e FROM DCAEuuid e ") +public class DCAEuuid implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String name; + + @Column(name="description") + private String description; + + + public DCAEuuid() { + + } + public DCAEuuid(String string, String userid) { + this(domain); + + } + public DCAEuuid(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DatabaseLockEntity.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DatabaseLockEntity.java new file mode 100644 index 000000000..7b5a8954e --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DatabaseLockEntity.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="DatabaseLockEntity") +public class DatabaseLockEntity implements Serializable { + private static final long serialVersionUID = 1L; + @Id + @Column(name="lock_key") + private int lock_key = 1; + public DatabaseLockEntity(){ + + } + public int getKey(){ + return lock_key; + } + public void setKey(int key){ + this.lock_key = key; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Datatype.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Datatype.java new file mode 100644 index 000000000..6be1a84ce --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Datatype.java @@ -0,0 +1,244 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Set; + +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.OneToMany; +import javax.persistence.Table; +import javax.persistence.Transient; + +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.IdentifierImpl; +import com.fasterxml.jackson.annotation.JsonBackReference; +import com.fasterxml.jackson.annotation.JsonIgnore; + + +/** + * The persistent class for the Datatype database table. + * + */ +@Entity +@Table(name="Datatype") +@NamedQuery(name="Datatype.findAll", query="SELECT d FROM Datatype d") +public class Datatype implements Serializable { + private static final long serialVersionUID = 1L; + + public static final char STANDARD = 'S'; + public static final char CUSTOM = 'C'; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="is_standard", nullable=false) + private char isStandard; + + @Column(name="xacml_id", nullable=false, unique=true, length=255) + private String xacmlId; + + @Column(name="short_name", nullable=false, length=64) + private String shortName; + + //bi-directional many-to-one association to Attribute + @OneToMany(mappedBy="datatypeBean") + @JsonBackReference + private Set attributes = new HashSet<>(); + + //bi-directional many-to-one association to Attribute + @OneToMany(mappedBy="datatypeBean") + @JsonIgnore + private Set functions = new HashSet<>(); + + //bi-directional many-to-one association to Attribute + @OneToMany(mappedBy="datatypeBean") + @JsonIgnore + private Set arguments = new HashSet<>(); + + public Datatype() { + this.xacmlId = XACML3.ID_DATATYPE_STRING.stringValue(); + this.isStandard = Datatype.STANDARD; + } + + + public Datatype(int id, Datatype dt) { + this.id = id; + this.isStandard = dt.isStandard; + this.xacmlId = dt.xacmlId; + this.shortName = dt.shortName; + // + // Make a copy? + // + this.attributes = new HashSet<>(); + } + + public Datatype(Identifier identifier, char standard) { + if (identifier != null) { + this.xacmlId = identifier.stringValue(); + + } + this.isStandard = standard; + } + + public Datatype(Identifier identifier) { + this(identifier, Datatype.STANDARD); + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public char getIsStandard() { + return this.isStandard; + } + + public void setIsStandard(char isStandard) { + this.isStandard = isStandard; + } + + public String getXacmlId() { + return this.xacmlId; + } + + public void setXacmlId(String xacmlId) { + this.xacmlId = xacmlId; + } + + public String getShortName() { + return shortName; + } + + public void setShortName(String shortName) { + this.shortName = shortName; + } + + public Set getAttributes() { + return this.attributes; + } + + public void setAttributes(Set attributes) { + this.attributes = attributes; + } + + public Attribute addAttribute(Attribute attribute) { + getAttributes().add(attribute); + attribute.setDatatypeBean(this); + + return attribute; + } + + public Attribute removeAttribute(Attribute attribute) { + getAttributes().remove(attribute); + attribute.setDatatypeBean(null); + + return attribute; + } + + public Set getFunctions() { + return this.functions; + } + + public void setFunctions(Set functions) { + this.functions = functions; + } + + public FunctionDefinition addFunction(FunctionDefinition function) { + getFunctions().add(function); + function.setDatatypeBean(this); + + return function; + } + + public FunctionDefinition removeAttribute(FunctionDefinition function) { + getFunctions().remove(function); + function.setDatatypeBean(null); + + return function; + } + + public Set getArguments() { + return this.arguments; + } + + public void setArguments(Set argument) { + this.arguments = argument; + } + + public FunctionArgument addArgument(FunctionArgument argument) { + getArguments().add(argument); + argument.setDatatypeBean(this); + + return argument; + } + + public FunctionArgument removeArgument(FunctionArgument argument) { + getArguments().remove(argument); + argument.setDatatypeBean(null); + + return argument; + } + + @Transient + public Identifier getIdentifer() { + return new IdentifierImpl(this.xacmlId); + } + + @Transient + public Identifier getIdentiferByShortName() { + return new IdentifierImpl(this.shortName); + } + + @Transient + public boolean isStandard() { + return (this.isStandard == Datatype.STANDARD); + } + + @Transient + public boolean isCustom() { + return (this.isStandard == Datatype.CUSTOM); + } + + @Transient + @Override + public String toString() { + return "Datatype [id=" + id + ", isStandard=" + isStandard + + ", xacmlId=" + xacmlId + ", shortName=" + shortName + + ", attributes=" + attributes + ", functions=" + functions + + ", arguments=" + arguments + "]"; + + //return "Datatype [shortName=" + shortName + "]"; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DecisionSettings.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DecisionSettings.java new file mode 100644 index 000000000..164cc3cef --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DecisionSettings.java @@ -0,0 +1,235 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import javax.persistence.Transient; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.rest.XacmlAdminAuthorization; + + +@Entity +@Table(name="DecisionSettings") +@NamedQuery(name="DecisionSettings.findAll", query="SELECT a FROM DecisionSettings a order by a.priority asc, a.xacmlId asc") +public class DecisionSettings implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @Column(name="PRIORITY", nullable=true) + @OrderBy("asc") + private String priority; + + @Column(name="xacml_id", unique = true, nullable=false) + @OrderBy("asc") + private String xacmlId = "urn"; + + //bi-directional many-to-one association to Datatype + @ManyToOne + @JoinColumn(name="datatype") + private Datatype datatypeBean; + + @Transient + private String issuer = null; + + @Transient + private boolean mustBePresent = false; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + public DecisionSettings() { + } + + public DecisionSettings(String domain) { + this.xacmlId = domain; + } + + public DecisionSettings(String domain, String user) { + this(domain); + } + public DecisionSettings(DecisionSettings copy, String user) { + this(copy.getXacmlId() + ":(0)", user); + this.datatypeBean = copy.getDatatypeBean(); + this.description = copy.getDescription(); + + } + + public String getDecisionSettings(){ + return this.xacmlId; + } + + public String setDecisionSettings(){ + return this.xacmlId; + } + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy = XacmlAdminAuthorization.getUserId();; + } catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "DecisionSettings", "Exception caused While adding Modified by Role"); + } + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + + public Date getCreatedDate() { + return this.createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getModifiedDate() { + return this.modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public String getXacmlId() { + return this.xacmlId; + } + +/* @Transient + public Identifier getXacmlIdentifier() { + return new IdentifierImpl(this.xacmlId); + }*/ + + public void setXacmlId(String xacmlId) { + this.xacmlId = xacmlId; + } + + public Datatype getDatatypeBean() { + return this.datatypeBean; + } + + public void setDatatypeBean(Datatype datatypeBean) { + this.datatypeBean = datatypeBean; + } + + @Transient + public String getIssuer() { + return issuer; + } + + @Transient + public void setIssuer(String issuer) { + this.issuer = issuer; + } + + @Transient + public boolean isMustBePresent() { + return mustBePresent; + } + + @Transient + public void setMustBePresent(boolean mustBePresent) { + this.mustBePresent = mustBePresent; + } + + public String getPriority() { + return priority; + } + + public void setPriority(String priority) { + this.priority = priority; + } +} + diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DescriptiveScope.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DescriptiveScope.java new file mode 100644 index 000000000..30882fc13 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/DescriptiveScope.java @@ -0,0 +1,181 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.rest.XacmlAdminAuthorization; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + + +@Entity +@Table(name = "DescriptiveScope") +@NamedQuery(name = "DescriptiveScope.findAll", query= "Select p from DescriptiveScope p") +public class DescriptiveScope implements Serializable { + private static final long serialVersionUID = 1L; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "Id") + private int id; + + @Column(name="scopename", nullable=false) + @OrderBy("asc") + private String descriptiveScopeName; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Column(name="search", nullable=true) + @OrderBy("asc") + private String search; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + private static Log LOGGER = LogFactory.getLog(DescriptiveScope.class); + + public DescriptiveScope(){ + + } + + public DescriptiveScope(String string, String userid) { + this(string); + } + + public DescriptiveScope(String domain) { + this.descriptiveScopeName = domain; + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy =XacmlAdminAuthorization.getUserId();; + } catch (Exception e) { + LOGGER.error("Exception caused While adding Modified by Role"+e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "DescriptiveScope", "Exception caused While adding Modified by Role"); + } + } + + public int getId() { + return this.id; + } + public void setId(int id) { + this.id = id; + } + + public String getScopeName() { + return descriptiveScopeName; + } + + public void setScopeName(String descriptiveScopeName) { + this.descriptiveScopeName = descriptiveScopeName; + } + + public String getSearch() { + return search; + } + + public void setSearch(String search) { + this.search = search; + } + + public Date getCreatedDate() { + return this.createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getModifiedDate() { + return this.modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/EnforcingType.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/EnforcingType.java new file mode 100644 index 000000000..9c1cda451 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/EnforcingType.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; + +import javax.persistence.*; + +/** + * Entity implementation class for Entity: EnforcingType + * + */ +@Entity +@Table(name="EnforcingType") +@NamedQuery(name="EnforcingType.findAll", query="SELECT e FROM EnforcingType e ") +public class EnforcingType implements Serializable { + + + private static final long serialVersionUID = 1L; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + @Column(name="enforcingType", nullable=false, unique=true) + @OrderBy("asc") + private String enforcingType; + @Column(name="script", nullable=false, length=255) + private String script; + @Column(name="connectionQuery", nullable=false, length=255) + private String connectionQuery; + @Column(name="valueQuery", nullable=false, length=255) + private String valueQuery; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getEnforcingType() { + return enforcingType; + } + + public void setEnforcingType(String enforcingType) { + this.enforcingType = enforcingType; + } + + public String getScript() { + return script; + } + + public void setScript(String script) { + this.script = script; + } + + public String getConnectionQuery() { + return connectionQuery; + } + + public void setConnectionQuery(String connectionQuery) { + this.connectionQuery = connectionQuery; + } + + public String getValueQuery() { + return valueQuery; + } + + public void setValueQuery(String valueQuery) { + this.valueQuery = valueQuery; + } + + public EnforcingType() { + super(); + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FWTag.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FWTag.java new file mode 100644 index 000000000..71f4d6a6a --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FWTag.java @@ -0,0 +1,180 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.rest.XacmlAdminAuthorization; + +@Entity +@Table(name = "FWTag") +@NamedQuery(name = "FWTag.findAll", query= "Select p from FWTag p") +public class FWTag implements Serializable { + private static final long serialVersionUID = 1L; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "Id") + private int id; + + @Column(name="tagName", nullable=false) + @OrderBy("asc") + private String fwTagName; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Column(name="tagValues", nullable=true) + @OrderBy("asc") + private String tagValues; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + private static Log LOGGER = LogFactory.getLog(FWTag.class); + + public FWTag(){ + + } + + public FWTag(String string, String userid) { + this(string); + } + + public FWTag(String domain) { + this.fwTagName = domain; + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy =XacmlAdminAuthorization.getUserId();; + } catch (Exception e) { + LOGGER.error("Exception caused While adding Modified by Role"+e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FWTag", "Exception caused While adding Modified by Role"); + } + } + + public int getId() { + return this.id; + } + public void setId(int id) { + this.id = id; + } + + public String getFwTagName() { + return fwTagName; + } + + public void setFwTagName(String fwTagName) { + this.fwTagName = fwTagName; + } + + public String getTagValues() { + return tagValues; + } + + public void setTagValues(String tagValues) { + this.tagValues = tagValues; + } + + + public Date getCreatedDate() { + return this.createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getModifiedDate() { + return this.modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FWTagPicker.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FWTagPicker.java new file mode 100644 index 000000000..6f03b4915 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FWTagPicker.java @@ -0,0 +1,189 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.rest.XacmlAdminAuthorization; + +@Entity +@Table(name = "FWTagPicker") +@NamedQuery(name = "FWTagPicker.findAll", query= "Select p from FWTagPicker p") +public class FWTagPicker implements Serializable { + private static final long serialVersionUID = 1L; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "Id") + private int id; + + @Column(name="tagPickerName", nullable=false) + @OrderBy("asc") + private String tagPickerName; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Column(name="networkRole", nullable=true) + private String networkRole; + + @Column(name="tags", nullable=true) + @OrderBy("asc") + private String tagValues; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + private static Log logger = LogFactory.getLog(FWTagPicker.class); + + public FWTagPicker(){ + + } + + public FWTagPicker(String string, String userid) { + this(string); + } + + public FWTagPicker(String domain) { + this.tagPickerName = domain; + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy =XacmlAdminAuthorization.getUserId(); + } catch (Exception e) { + logger.error("Exception caused While adding Modified by Role"+e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "DescriptiveScope", "Exception caused While adding Modified by Role"); + } + } + + public int getId() { + return this.id; + } + public void setId(int id) { + this.id = id; + } + + public String getTagPickerName() { + return tagPickerName; + } + + public void setTagPickerName(String tagPickerName) { + this.tagPickerName = tagPickerName; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getNetworkRole() { + return networkRole; + } + + public void setNetworkRole(String networkRole) { + this.networkRole = networkRole; + } + + public String getTagValues() { + return tagValues; + } + + public void setTagValues(String tagValues) { + this.tagValues = tagValues; + } + + public Date getCreatedDate() { + return this.createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public Date getModifiedDate() { + return this.modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FirewallDictionaryList.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FirewallDictionaryList.java new file mode 100644 index 000000000..27f5e75bd --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FirewallDictionaryList.java @@ -0,0 +1,164 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +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.OrderBy; +import javax.persistence.Table; + + +@Entity +@Table(name="parentdictionaryitems") +@NamedQuery(name="FirewallDictionaryList.findAll", query="SELECT e FROM FirewallDictionaryList e") +public class FirewallDictionaryList implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="parentItemName", nullable=false) + @OrderBy("asc") + private String parentItemName; + + @Column(name="description") + private String description; + + @Column(name="addressList") + private String addressList; + + @Column(name="serviceList") + private String serviceList; + +/* @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy;*/ + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getParentItemName() { + return parentItemName; + } + + public String getDescription() { + return description; + } + + public String getAddressList() { + return addressList; + } + + public String getServiceList() { + return serviceList; + } + + public void setParentItemName(String parentItemName) { + this.parentItemName = parentItemName; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setAddressList(String addressList) { + this.addressList = addressList; + } + + public void setServiceList(String serviceList) { + this.serviceList = serviceList; + } + + + /*public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + }*/ + + public FirewallDictionaryList() { + + } + + public FirewallDictionaryList(String string, String userid) { + this(domain); + } + public FirewallDictionaryList(String domain) { + this.parentItemName = domain; + } + + /*@PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + auditLogger.debug("Added New Term Name: "+this.parentItemName+" by "+this.userCreatedBy); + + } + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy =XacmlAdminAuthorization.getUserId();; + } catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "TermList", "Exception caused While adding Modified by Role"); + } + auditLogger.debug("Updated Term Name: "+this.parentItemName+" by "+this.userModifiedBy); + } +*/ +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FunctionArgument.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FunctionArgument.java new file mode 100644 index 000000000..4d712994c --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FunctionArgument.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; + +import javax.persistence.*; + + +/** + * The persistent class for the FunctionArguments database table. + * + */ +@Entity +@Table(name="FunctionArguments") +@NamedQuery(name="FunctionArgument.findAll", query="SELECT f FROM FunctionArgument f") +public class FunctionArgument implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="is_bag", nullable=false) + private int isBag; + + //bi-directional many-to-one association to FunctionDefinition + @ManyToOne + @JoinColumn(name="function_id") + private FunctionDefinition functionDefinition; + + @Column(name="arg_index", nullable=false) + private int argIndex; + + //bi-directional many-to-one association to Datatype + @ManyToOne + @JoinColumn(name="datatype_id") + private Datatype datatypeBean; + + public FunctionArgument() { + } + + public FunctionArgument(final FunctionArgument argument) { + this.argIndex = argument.argIndex; + this.datatypeBean = argument.datatypeBean; + this.isBag = argument.isBag; + this.functionDefinition = argument.functionDefinition; + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public int getArgIndex() { + return this.argIndex; + } + + public void setArgIndex(int argIndex) { + this.argIndex = argIndex; + } + + public Datatype getDatatypeBean() { + return this.datatypeBean; + } + + public void setDatatypeBean(Datatype datatypeBean) { + this.datatypeBean = datatypeBean; + } + + public FunctionDefinition getFunctionDefinition() { + return this.functionDefinition; + } + + public int getIsBag() { + return isBag; + } + + public void setIsBag(int isBag) { + this.isBag = isBag; + } + + public void setFunctionDefinition(FunctionDefinition functionDefinition) { + this.functionDefinition = functionDefinition; + } + + @Transient + @Override + public String toString() { + return "FunctionArgument [id=" + id + ", argIndex=" + argIndex + + ", datatypeBean=" + datatypeBean + ", isBag=" + isBag + + ", functionDefinition=" + functionDefinition + "]"; + } + + @Transient + public boolean isBag() { + return this.isBag == 1; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FunctionDefinition.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FunctionDefinition.java new file mode 100644 index 000000000..c3dfcaa63 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/FunctionDefinition.java @@ -0,0 +1,219 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; + +import javax.persistence.*; + +import java.util.List; + + +/** + * The persistent class for the FunctionDefinition database table. + * + */ +@Entity +@Table(name="FunctionDefinition") +@NamedQueries({ + @NamedQuery(name="FunctionDefinition.findAll", query="SELECT f FROM FunctionDefinition f") +}) +public class FunctionDefinition implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="short_name", nullable=false, length=64) + private String shortname; + + @Column(name="xacml_id", nullable=false, length=255) + private String xacmlid; + + //bi-directional many-to-one association to Datatype + @ManyToOne + @JoinColumn(name="return_datatype", nullable=true) + private Datatype datatypeBean; + + @Column(name="is_bag_return", nullable=false) + private Integer isBagReturn; + + @Column(name="is_higher_order", nullable=false) + private Integer isHigherOrder; + + @Column(name="arg_lb", nullable=false) + private Integer argLb; + + @Column(name="arg_ub", nullable=false) + private Integer argUb; + + @Column(name="ho_arg_lb", nullable=true) + private Integer higherOrderArg_LB; + + @Column(name="ho_arg_ub", nullable=true) + private Integer higherOrderArg_UB; + + @Column(name="ho_primitive", nullable=true) + private Character higherOrderIsPrimitive; + + //bi-directional many-to-one association to FunctionArgument + @OneToMany(mappedBy="functionDefinition") + private List functionArguments; + + public FunctionDefinition() { + } + + public int getId() { + return this.id; + } + + public void setId(Integer id) { + this.id = id; + } + + public int getArgLb() { + return this.argLb; + } + + public void setArgLb(Integer argLb) { + this.argLb = argLb; + } + + public int getArgUb() { + return this.argUb; + } + + public void setArgUb(Integer argUb) { + this.argUb = argUb; + } + + public int getIsBagReturn() { + return isBagReturn; + } + + public void setIsBagReturn(Integer isBagReturn) { + this.isBagReturn = isBagReturn; + } + + public int getIsHigherOrder() { + return isHigherOrder; + } + + public void setIsHigherOrder(Integer isHigherOrder) { + this.isHigherOrder = isHigherOrder; + } + + public Datatype getDatatypeBean() { + return this.datatypeBean; + } + + public void setDatatypeBean(Datatype datatypeBean) { + this.datatypeBean = datatypeBean; + } + + public String getShortname() { + return this.shortname; + } + + public void setShortname(String shortname) { + this.shortname = shortname; + } + + public String getXacmlid() { + return this.xacmlid; + } + + public void setXacmlid(String xacmlid) { + this.xacmlid = xacmlid; + } + + public int getHigherOrderArg_LB() { + return higherOrderArg_LB; + } + + public void setHigherOrderArg_LB(Integer higherOrderArg_LB) { + this.higherOrderArg_LB = higherOrderArg_LB; + } + + public int getHigherOrderArg_UB() { + return higherOrderArg_UB; + } + + public void setHigherOrderArg_UB(Integer higherOrderArg_UB) { + this.higherOrderArg_UB = higherOrderArg_UB; + } + + public Character getHigherOrderIsPrimitive() { + return higherOrderIsPrimitive; + } + + public void setHigherOrderIsPrimitive(Character higherOrderIsPrimitive) { + this.higherOrderIsPrimitive = higherOrderIsPrimitive; + } + + public List getFunctionArguments() { + return this.functionArguments; + } + + public void setFunctionArguments(List functionArguments) { + this.functionArguments = functionArguments; + } + + public FunctionArgument addFunctionArgument(FunctionArgument functionArgument) { + getFunctionArguments().add(functionArgument); + functionArgument.setFunctionDefinition(this); + + return functionArgument; + } + + public FunctionArgument removeFunctionArgument(FunctionArgument functionArgument) { + getFunctionArguments().remove(functionArgument); + functionArgument.setFunctionDefinition(null); + + return functionArgument; + } + + @Transient + @Override + public String toString() { + return "FunctionDefinition [id=" + id + ", argLb=" + argLb + ", argUb=" + + argUb + ", isBagReturn=" + isBagReturn + ", isHigherOrder=" + + isHigherOrder + ", datatypeBean=" + datatypeBean + + ", shortname=" + shortname + ", xacmlid=" + xacmlid + + ", higherOrderArg_LB=" + higherOrderArg_LB + + ", higherOrderArg_UB=" + higherOrderArg_UB + + ", higherOrderIsPrimitive=" + higherOrderIsPrimitive + + ", functionArguments=" + functionArguments + "]"; + } + + @Transient + public boolean isBagReturn() { + return this.isBagReturn == 1; + } + + @Transient + public boolean isHigherOrder() { + return this.isHigherOrder == 1; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GlobalRoleSettings.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GlobalRoleSettings.java new file mode 100644 index 000000000..357906d4f --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GlobalRoleSettings.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.NamedQuery; +import javax.persistence.Table; + + +/** + * Entity implementation class for Entity: Administration + * + */ +@Entity +@Table(name="GlobalRoleSettings") +@NamedQuery(name="GlobalRoleSettings.findAll", query="SELECT g FROM GlobalRoleSettings g") +public class GlobalRoleSettings implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @Column(name="role", length=45) + private String role; + + @Column(name="lockdown") + private boolean lockdown; + + public GlobalRoleSettings() { + super(); + } + + public GlobalRoleSettings(boolean lockdown) { + this.role = org.onap.policy.rest.XacmlAdminAuthorization.Role.ROLE_SUPERADMIN.toString(); + this.lockdown = lockdown; + } + + /** + * return the role + * + * @return the role + */ + public String getRole() { + return role; + } + + /** + * set role + * + * @param role the role to set + */ + public void setRole(String role) { + this.role = role; + } + + /** + * is the system locked down + * + * @return + */ + public boolean isLockdown() { + return lockdown; + } + + /** + * sets lockdown configuration + * + * @param lockdown + */ + public void setLockdown(boolean lockdown) { + this.lockdown = lockdown; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GroupEntity.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GroupEntity.java new file mode 100644 index 000000000..a53ac2d58 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GroupEntity.java @@ -0,0 +1,270 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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========================================================= + */ + +/* + * AT&T - PROPRIETARY + * THIS FILE CONTAINS PROPRIETARY INFORMATION OF + * AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN + * ACCORDANCE WITH APPLICABLE AGREEMENTS. + * + * Copyright (c) 2013 AT&T Knowledge Ventures + * Unpublished and Not for Publication + * All Rights Reserved + */ +package org.onap.policy.rest.jpa; +/* + */ +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import javax.persistence.Version; + +import com.fasterxml.jackson.annotation.JsonManagedReference; + +/* + * The Entity class to persist a policy object and its configuration data + */ + +/** + * + */ +@Entity +//Add a non-unique index and a constraint that says the combo of policyName and scopeId must be unique +@Table(name="GroupEntity") + +@NamedQueries({ + @NamedQuery(name="GroupEntity.findAll", query="SELECT e FROM GroupEntity e "), + @NamedQuery(name="GroupEntity.deleteAll", query="DELETE FROM GroupEntity WHERE 1=1") +}) + +public class GroupEntity implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @Column (name="groupKey", nullable=false) + @GeneratedValue(strategy = GenerationType.AUTO) + private long groupKey; + + @Column (name="groupId", nullable=false) + private String groupId; + + @Column(name="groupName", nullable=false, unique=false, length=255) + private String groupName; + + @Version + @Column(name="version") + private int version; + + @ManyToMany(cascade = CascadeType.ALL) + @JoinTable(name="PolicyGroupEntity",joinColumns={@JoinColumn(name="groupKey")}, inverseJoinColumns={@JoinColumn(name="policyId")}) + @JsonManagedReference + private List policies; + + @Column(name="created_by", nullable=false, length=255) + private String createdBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Column(name="description", nullable=false, length=2048) + private String description = "NoDescription"; + + @Column(name="modified_by", nullable=false, length=255) + private String modifiedBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @Column(name="defaultGroup", nullable=false) + private boolean defaultGroup = false; + @Column(name="deleted", nullable=false) + private boolean deleted = false; + + public GroupEntity() { + super(); + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + } + + /** + * @return the policyId + */ + public String getGroupId() { + return groupId; + } + public long getGroupKey(){ + return groupKey; + } + + public void setGroupId(String groupId){ + this.groupId = groupId; + } + + /** + * @param policyId cannot be set + */ + + public String getgroupName() { + return groupName; + } + + public void setGroupName(String groupName) { + this.groupName = groupName; + } + + public boolean isDefaultGroup(){ + return defaultGroup; + } + + public void setDefaultGroup(boolean isDefaultGroup){ + this.defaultGroup = isDefaultGroup; + } + + + + /** + * @return the configurationDataEntity + */ + public List getPolicies() { + return policies; + } + + /** + * @param configurationDataEntity the configurationDataEntity to set + */ + public void addPolicyToGroup(PolicyEntity policy) { + if(!this.policies.contains(policy)){ + this.policies.add(policy); + } + } + public void removePolicyFromGroup(PolicyEntity policy){ + this.policies.remove(policy); + } + + + + /** + * @return the createdBy + */ + public String getCreatedBy() { + return createdBy; + } + + /** + * @param createdBy the createdBy to set + */ + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + /** + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * @param description the description to set + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * @return the modifiedBy + */ + public String getModifiedBy() { + return modifiedBy; + } + + /** + * @param modifiedBy the modifiedBy to set + */ + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + /** + * @return the version + */ + public int getVersion() { + return version; + } + + /** + * @return the createdDate + */ + public Date getCreatedDate() { + return createdDate; + } + + /** + * @return the modifiedDate + */ + public Date getModifiedDate() { + return modifiedDate; + } + + /** + * @return the deleted + */ + public boolean isDeleted() { + return deleted; + } + + /** + * @param deleted the deleted to set + */ + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GroupPolicyScopeList.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GroupPolicyScopeList.java new file mode 100644 index 000000000..44f27ba35 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GroupPolicyScopeList.java @@ -0,0 +1,111 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + + +@Entity +@Table(name="GroupPolicyScopeList") +@NamedQuery(name="GroupPolicyScopeList.findAll", query="SELECT e FROM GroupPolicyScopeList e ") +public class GroupPolicyScopeList implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String name; + + @Column(name="groupList") + private String groupList; + + @Column(name="description") + private String description; + + public GroupPolicyScopeList() { + + } + public GroupPolicyScopeList(String string, String userid) { + this(domain); + + } + public GroupPolicyScopeList(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getGroupName() { + return this.name; + } + + public void setGroupName(String serviceName) { + this.name = serviceName; + + } + + public String getGroupList() { + return this.groupList; + } + + public void setGroupList(String groupList) { + this.groupList = groupList; + + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GroupServiceList.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GroupServiceList.java new file mode 100644 index 000000000..53fb89d4f --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/GroupServiceList.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + + +@Entity +@Table(name="GroupServiceList") +@NamedQuery(name="GroupServiceList.findAll", query="SELECT e FROM GroupServiceList e ") +public class GroupServiceList implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String name; + + @Column(name="serviceList ") + private String serviceList; + + + public GroupServiceList() { + + } + public GroupServiceList(String string, String userid) { + this(domain); + + } + public GroupServiceList(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getGroupName() { + return this.name; + } + + public void setGroupName(String serviceName) { + this.name = serviceName; + + } + + public String getServiceList() { + return this.serviceList; + } + + public void setServiceList(String serviceList) { + this.serviceList = serviceList; + + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceAttribute.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceAttribute.java new file mode 100644 index 000000000..bb0507123 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceAttribute.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + +@Entity +@Table(name="MicroServiceAttribute") +@NamedQuery(name="MicroServiceAttribute.findAll", query="SELECT e FROM MicroServiceAttribute e ") +public class MicroServiceAttribute implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String name; + + @Column(name="value") + private String value ; + + @Column(name="modelName") + private String modelName; + + + public MicroServiceAttribute() { + + } + public MicroServiceAttribute(String string, String userid) { + this(domain); + + } + public MicroServiceAttribute(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + + } + public String getValue() { + return this.value ; + } + + public void setValue(String value ) { + this.value = value ; + } + public String getModelName() { + return modelName; + } + public void setModelName(String modelName) { + this.modelName = modelName; + } + +} \ No newline at end of file diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceConfigName.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceConfigName.java new file mode 100644 index 000000000..f47b96ed8 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceConfigName.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + + +@Entity +@Table(name="MicroServiceConfigName") +@NamedQuery(name="MicroServiceConfigName.findAll", query="SELECT e FROM MicroServiceConfigName e ") +public class MicroServiceConfigName implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String name; + + @Column(name="description ") + private String description ; + + + public MicroServiceConfigName() { + + } + public MicroServiceConfigName(String string, String userid) { + this(domain); + + } + public MicroServiceConfigName(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + + } + public String getDescriptionValue() { + return this.description ; + } + + public void setDescriptionValue(String description ) { + this.description = description ; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceLocation.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceLocation.java new file mode 100644 index 000000000..4d82a3b20 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceLocation.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + + +@Entity +@Table(name="MicroServiceLocation") +@NamedQuery(name="MicroServiceLocation.findAll", query="SELECT e FROM MicroServiceLocation e ") +public class MicroServiceLocation implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String name; + + @Column(name="description ") + private String description ; + + + public MicroServiceLocation() { + + } + public MicroServiceLocation(String string, String userid) { + this(domain); + + } + public MicroServiceLocation(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + + } + public String getDescriptionValue() { + return this.description ; + } + + public void setDescriptionValue(String description ) { + this.description = description ; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceModels.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceModels.java new file mode 100644 index 000000000..513799762 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroServiceModels.java @@ -0,0 +1,189 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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========================================================= + */ + +/* + * AT&T - PROPRIETARY + * THIS FILE CONTAINS PROPRIETARY INFORMATION OF + * AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN + * ACCORDANCE WITH APPLICABLE AGREEMENTS. + * + * Copyright (c) 2015 AT&T Knowledge Ventures + * Unpublished and Not for Publication + * All Rights Reserved + */ +package org.onap.policy.rest.jpa; + +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.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.Table; +/* + * JPA for the Micro Service Models. + * + * @version: 0.1 + */ + + +@Entity +@Table(name="MicroServiceModels") +@NamedQuery(name="MicroServiceModels.findAll", query="SELECT b FROM MicroServiceModels b ") +public class MicroServiceModels implements Serializable{ + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="modelName", nullable=false, unique=true) + @OrderBy("asc") + private String modelName; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Column(name="dependency", nullable=true, length=2048) + private String dependency; + + @Column(name="attributes", nullable=false, length=255) + private String attributes; + + @Column(name="ref_attributes", nullable=false, length=255) + private String ref_attributes; + + @Column (name="sub_attributes", nullable=false, length=2000) + private String sub_attributes; + + @Column (name="version", nullable=false, length=2000) + private String version; + + @Column (name="enumValues", nullable=false, length=2000) + private String enumValues; + + @Column (name="annotation", nullable=false, length=2000) + private String annotation; + + public String getSub_attributes() { + return sub_attributes; + } + + public void setSub_attributes(String sub_attributes) { + this.sub_attributes = sub_attributes; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + @ManyToOne + @JoinColumn(name="imported_by") + private UserInfo userCreatedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public MicroServiceModels(){ + } + + public MicroServiceModels(String userid){ + + } + + public String getAttributes() { + return attributes; + } + + public void setAttributes(String attributes) { + this.attributes = attributes; + } + + public String getRef_attributes() { + return ref_attributes; + } + + public void setRef_attributes(String ref_attributes) { + this.ref_attributes = ref_attributes; + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDependency() { + return dependency; + } + + public void setDependency(String dependency) { + this.dependency = dependency; + } + + public String getModelName(){ + return this.modelName; + } + + public void setModelName(String modelName){ + this.modelName = modelName; + } + + public String getEnumValues() { + return enumValues; + } + + public void setEnumValues(String enumValues) { + this.enumValues = enumValues; + } + + public String getAnnotation() { + return annotation; + } + + public void setAnnotation(String annotation) { + this.annotation = annotation; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Obadvice.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Obadvice.java new file mode 100644 index 000000000..b3b52cdd4 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Obadvice.java @@ -0,0 +1,227 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +import javax.persistence.CascadeType; +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.OneToMany; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import javax.persistence.Transient; + +import com.att.research.xacml.api.Identifier; + +/** + * The persistent class for the Obadvice database table. + * + */ +@Entity +@Table(name="Obadvice") +@NamedQuery(name="Obadvice.findAll", query="SELECT o FROM Obadvice o") +public class Obadvice implements Serializable { + private static final long serialVersionUID = 1L; + + public static final String OBLIGATION = "Obligation"; + public static final String ADVICE = "Advice"; + public static final String EFFECT_PERMIT = "Permit"; + public static final String EFFECT_DENY = "Deny"; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="type", nullable=false) + private String type; + + @Column(name="xacml_id", nullable=false, length=255) + private String xacmlId; + + @Column(name="fulfill_on", nullable=true, length=32) + private String fulfillOn; + + @Column(name="description", nullable=true, length=2048) + private String description; + + //bi-directional one-to-many association to Attribute Assignment + @OneToMany(mappedBy="obadvice", orphanRemoval=true, cascade=CascadeType.REMOVE) + private Set obadviceExpressions = new HashSet<>(2); + + @Column(name="created_by", nullable=false, length=255) + private String createdBy; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", nullable=false, updatable=false) + private Date createdDate; + + @Column(name="modified_by", nullable=false, length=255) + private String modifiedBy; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + public Obadvice() { + this.type = Obadvice.OBLIGATION; + this.fulfillOn = Obadvice.EFFECT_PERMIT; + } + + public Obadvice(String domain, String userid) { + this.xacmlId = domain; + this.type = Obadvice.OBLIGATION; + this.fulfillOn = Obadvice.EFFECT_PERMIT; + this.createdBy = userid; + this.modifiedBy = userid; + } + + public Obadvice(Identifier id, String userid) { + this(id.stringValue(), userid); + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getCreatedBy() { + return this.createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getFulfillOn() { + return this.fulfillOn; + } + + public void setFulfillOn(String fulfillOn) { + this.fulfillOn = fulfillOn; + } + + public String getModifiedBy() { + return this.modifiedBy; + } + + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + public String getType() { + return this.type; + } + + public void setType(String type) { + this.type = type; + } + + public String getXacmlId() { + return this.xacmlId; + } + + public void setXacmlId(String xacmlId) { + this.xacmlId = xacmlId; + } + + public Set getObadviceExpressions() { + return this.obadviceExpressions; + } + + public void setObadviceExpressions(Set obadviceExpressions) { + this.obadviceExpressions = obadviceExpressions; + } + + public ObadviceExpression addObadviceExpression(ObadviceExpression obadviceExpression) { + this.obadviceExpressions.add(obadviceExpression); + obadviceExpression.setObadvice(this); + + return obadviceExpression; + } + + public ObadviceExpression removeObadviceExpression(ObadviceExpression obadviceExpression) { + this.obadviceExpressions.remove(obadviceExpression); + obadviceExpression.setObadvice(null); + + return obadviceExpression; + } + + public void removeAllExpressions() { + if (this.obadviceExpressions == null) { + return; + } + for (ObadviceExpression expression : this.obadviceExpressions) { + expression.setObadvice(null); + } + this.obadviceExpressions.clear(); + } + + @Transient + public Obadvice clone() { + Obadvice obadvice = new Obadvice(); + + obadvice.type = this.type; + obadvice.xacmlId = this.xacmlId; + obadvice.fulfillOn = this.fulfillOn; + obadvice.description = this.description; + obadvice.createdBy = this.createdBy; + obadvice.modifiedBy = this.modifiedBy; + for (ObadviceExpression exp: this.obadviceExpressions) { + obadvice.addObadviceExpression(exp.clone()); + } + + return obadvice; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ObadviceExpression.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ObadviceExpression.java new file mode 100644 index 000000000..8d5be9742 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ObadviceExpression.java @@ -0,0 +1,123 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +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.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OneToOne; +import javax.persistence.Table; + + +/** + * The persistent class for the ObadviceExpressions database table. + * + */ +@Entity +@Table(name="ObadviceExpressions") +@NamedQuery(name="ObadviceExpression.findAll", query="SELECT o FROM ObadviceExpression o") +public class ObadviceExpression implements Serializable { + private static final long serialVersionUID = 1L; + + public static final String EXPRESSION_APPLY = "Apply"; + public static final String EXPRESSION_SELECTOR = "Attribute Selector"; + public static final String EXPRESSION_VALUE = "Attribute Value"; + public static final String EXPRESSION_FUNCTION = "Function"; + public static final String EXPRESSION_REFERENCE = "Varable Reference"; + public static final String EXPRESSION_DESIGNATOR = "Attribute Designator"; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + //unidirectional one-to-one association to Attribute + @OneToOne + @JoinColumn(name="attribute_id") + private Attribute attribute; + + @Column(name="type", nullable=false) + private String type; + + /* + @Lob + @Column(name="expression", nullable=false) + private byte[] expression; + */ + + //bi-directional many-to-one association to Obadvice + @ManyToOne + @JoinColumn(name="obadvice_id") + private Obadvice obadvice; + + public ObadviceExpression() { + type = EXPRESSION_VALUE; + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public Attribute getAttribute() { + return this.attribute; + } + + public void setAttribute(Attribute attribute) { + this.attribute = attribute; + } + + public String getType() { + return this.type; + } + + public void setType(String type) { + this.type = type; + } + + public Obadvice getObadvice() { + return this.obadvice; + } + + public void setObadvice(Obadvice obadvice) { + this.obadvice = obadvice; + } + + public ObadviceExpression clone() { + ObadviceExpression expression = new ObadviceExpression(); + + expression.attribute = this.attribute; + expression.type = this.type; + expression.obadvice = this.obadvice; + + return expression; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/OnapName.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/OnapName.java new file mode 100644 index 000000000..a4c0c85da --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/OnapName.java @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.rest.XacmlAdminAuthorization; + + +@Entity +@Table(name="OnapName") +@NamedQuery(name="OnapName.findAll", query="SELECT e FROM OnapName e ") +public class OnapName implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="onap_Name", nullable=false, unique=true) + @OrderBy("asc") + private String onapName; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + public OnapName() { + + } + + public OnapName(String string, String userid) { + this(domain); + } + + public OnapName(String domain) { + this.onapName = domain; + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy =XacmlAdminAuthorization.getUserId(); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "OnapName", "Exception caused While adding Modified by Role"); + } + } + public String getOnapName() { + return this.onapName; + } + + public void setOnapName(String onapName) { + this.onapName = onapName; + + } + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public Date getCreatedDate() { + return this.createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getModifiedDate() { + return this.modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PEPOptions.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PEPOptions.java new file mode 100644 index 000000000..c1fff1420 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PEPOptions.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + * + * */ +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.rest.XacmlAdminAuthorization; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + + +@Entity +@Table(name = "PEPOptions") +@NamedQuery(name = "PEPOptions.findAll", query= "Select p from PEPOptions p") +public class PEPOptions implements Serializable { + private static final long serialVersionUID = 1L; + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "Id") + private int id; + + @Column(name="PEP_NAME", nullable=false) + @OrderBy("asc") + private String pepName; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Column(name="Actions", nullable=true) + @OrderBy("asc") + private String actions; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + private static Log LOGGER = LogFactory.getLog(PEPOptions.class); + + public PEPOptions(){ + + } + + public PEPOptions(String string, String userid) { + this(string); + } + + public PEPOptions(String domain) { + this.pepName = domain; + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy =XacmlAdminAuthorization.getUserId();; + } catch (Exception e) { + LOGGER.error("Exception caused While adding Modified by Role"+e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PEPOptions", "Exception caused While adding Modified by Role"); + } + } + + public int getId() { + return this.id; + } + public void setId(int id) { + this.id = id; + } + + public String getPepName() { + return pepName; + } + + public void setPepName(String pepName) { + this.pepName = pepName; + } + + public String getActions() { + return actions; + } + + public void setActions(String actions) { + this.actions = actions; + } + + public Date getCreatedDate() { + return this.createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getModifiedDate() { + return this.modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPConfigParam.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPConfigParam.java new file mode 100644 index 000000000..1540c8ad8 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPConfigParam.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; + +import javax.persistence.*; + + +/** + * The persistent class for the PIPConfigParams database table. + * + */ +@Entity +@Table(name="PIPConfigParams") +@NamedQuery(name="PIPConfigParam.findAll", query="SELECT p FROM PIPConfigParam p") +public class PIPConfigParam implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="PARAM_NAME", nullable=false, length=1024) + private String paramName; + + @Column(name="PARAM_VALUE", nullable=false, length=2048) + private String paramValue; + + @Column(name="PARAM_DEFAULT", nullable=true, length=2048) + private String paramDefault = null; + + @Column(name="REQUIRED", nullable=false) + private char required = '0'; + + //bi-directional many-to-one association to PIPConfiguration + @ManyToOne + @JoinColumn(name="PIP_ID") + private PIPConfiguration pipconfiguration; + + public PIPConfigParam() { + } + + public PIPConfigParam(String param) { + this.paramName = param; + } + + public PIPConfigParam(String param, String value) { + this(param); + this.paramValue = value; + } + + public PIPConfigParam(PIPConfigParam param) { + this(param.getParamName(), param.getParamValue()); + this.paramDefault = param.getParamDefault(); + this.required = param.required; + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getParamName() { + return this.paramName; + } + + public void setParamName(String paramName) { + this.paramName = paramName; + } + + public String getParamValue() { + return this.paramValue; + } + + public void setParamValue(String paramValue) { + this.paramValue = paramValue; + } + + public String getParamDefault() { + return paramDefault; + } + + public void setParamDefault(String paramDefault) { + this.paramDefault = paramDefault; + } + + public char getRequired() { + return required; + } + + public void setRequired(char required) { + this.required = required; + } + + public PIPConfiguration getPipconfiguration() { + return this.pipconfiguration; + } + + public void setPipconfiguration(PIPConfiguration pipconfiguration) { + this.pipconfiguration = pipconfiguration; + } + + @Transient + public boolean isRequired() { + return (this.required == '1'); + } + + @Transient + public void setRequired(boolean required) { + if (required) { + this.setRequired('1'); + } else { + this.setRequired('0'); + } + } + + @Transient + @Override + public String toString() { + return "PIPConfigParam [id=" + id + ", paramName=" + paramName + + ", paramValue=" + paramValue + ", required=" + required + "]"; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPConfiguration.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPConfiguration.java new file mode 100644 index 000000000..5d731552b --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPConfiguration.java @@ -0,0 +1,537 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OneToMany; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import javax.persistence.Transient; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.xacml.api.XACMLErrorConstants; + +import com.att.research.xacml.api.pip.PIPException; +import com.att.research.xacml.std.pip.engines.StdConfigurableEngine; +import com.att.research.xacml.util.XACMLProperties; +import com.google.common.base.Joiner; +import com.google.common.base.Splitter; + + +/** + * The persistent class for the PIPConfiguration database table. + * + */ +@Entity +@Table(name="PIPConfiguration") +@NamedQuery(name="PIPConfiguration.findAll", query="SELECT p FROM PIPConfiguration p") +public class PIPConfiguration implements Serializable { + private static final long serialVersionUID = 1L; + private static final Log logger = LogFactory.getLog(PIPConfiguration.class); + + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="DESCRIPTION", nullable=true, length=2048) + private String description; + + @Column(name="NAME", nullable=false, length=255) + private String name; + + @Column(name="CLASSNAME", nullable=false, length=2048) + private String classname; + + @Column(name="ISSUER", nullable=true, length=1024) + private String issuer; + + @Column(name="READ_ONLY", nullable=false) + private char readOnly = '0'; + + @Column(name="REQUIRES_RESOLVER", nullable=false) + private char requiresResolvers; + + @Column(name="CREATED_BY", nullable=false, length=255) + private String createdBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="CREATED_DATE", nullable=false, updatable=false) + private Date createdDate; + + @Column(name="MODIFIED_BY", nullable=false, length=255) + private String modifiedBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="MODIFIED_DATE", nullable=false) + private Date modifiedDate; + + //bi-directional many-to-one association to PIPConfigParam + @OneToMany(mappedBy="pipconfiguration", orphanRemoval=true, cascade=CascadeType.REMOVE) + private Set pipconfigParams = new HashSet<>(); + + //bi-directional many-to-one association to PIPType + @ManyToOne + @JoinColumn(name="TYPE") + private PIPType piptype; + + //bi-directional many-to-one association to PIPResolver + @OneToMany(mappedBy="pipconfiguration", orphanRemoval=true, cascade=CascadeType.REMOVE) + private Set pipresolvers = new HashSet<>(); + + public PIPConfiguration() { + } + + public PIPConfiguration(PIPConfiguration config, String user) { + this.description = config.description; + this.name = config.name; + this.classname = config.classname; + this.issuer = config.issuer; + this.requiresResolvers = config.requiresResolvers; + this.readOnly = config.readOnly; + this.piptype = config.piptype; + for (PIPConfigParam param : config.pipconfigParams) { + this.addPipconfigParam(new PIPConfigParam(param)); + } + for (PIPResolver resolver : config.pipresolvers) { + this.addPipresolver(new PIPResolver(resolver)); + } + } + + public PIPConfiguration(String id, Properties properties) throws PIPException { + this.readProperties(id, properties); + } + + public PIPConfiguration(String id, Properties properties, String user) throws PIPException { + this.createdBy = user; + this.modifiedBy = user; + this.readProperties(id, properties); + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public String getClassname() { + return classname; + } + + public void setClassname(String classname) { + this.classname = classname; + } + + public String getIssuer() { + return issuer; + } + + public void setIssuer(String issuer) { + this.issuer = issuer; + } + + public char getReadOnly() { + return readOnly; + } + + public void setReadOnly(char readOnly) { + this.readOnly = readOnly; + } + + public char getRequiresResolvers() { + return requiresResolvers; + } + + public void setRequiresResolvers(char requireResolvers) { + this.requiresResolvers = requireResolvers; + } + + public Set getPipconfigParams() { + return this.pipconfigParams; + } + + public void setPipconfigParams(Set pipconfigParams) { + this.pipconfigParams = pipconfigParams; + } + + public PIPConfigParam addPipconfigParam(PIPConfigParam pipconfigParam) { + getPipconfigParams().add(pipconfigParam); + pipconfigParam.setPipconfiguration(this); + + return pipconfigParam; + } + + public PIPConfigParam removePipconfigParam(PIPConfigParam pipconfigParam) { + if (pipconfigParam == null) { + return pipconfigParam; + } + getPipconfigParams().remove(pipconfigParam); + pipconfigParam.setPipconfiguration(null); + + return pipconfigParam; + } + + @Transient + public void clearConfigParams() { + while (this.pipconfigParams.isEmpty() == false) { + this.removePipconfigParam(this.pipconfigParams.iterator().next()); + } + } + + public PIPType getPiptype() { + return this.piptype; + } + + public void setPiptype(PIPType piptype) { + this.piptype = piptype; + } + + public Set getPipresolvers() { + return this.pipresolvers; + } + + public void setPipresolvers(Set pipresolvers) { + this.pipresolvers = pipresolvers; + } + + public PIPResolver addPipresolver(PIPResolver pipresolver) { + getPipresolvers().add(pipresolver); + pipresolver.setPipconfiguration(this); + + return pipresolver; + } + + public PIPResolver removePipresolver(PIPResolver pipresolver) { + getPipresolvers().remove(pipresolver); + pipresolver.setPipconfiguration(null); + + return pipresolver; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public String getModifiedBy() { + return modifiedBy; + } + + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + public Date getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + + @Transient + public boolean isReadOnly() { + return (this.readOnly == '1'); + } + + @Transient + public void setReadOnly(boolean readOnly) { + if (readOnly) { + this.readOnly = '1'; + } else { + this.readOnly = '0'; + } + } + + @Transient + public boolean requiresResolvers() { + return (this.requiresResolvers == '1'); + } + + @Transient + public void setRequiresResolvers(boolean requires) { + if (requires) { + this.requiresResolvers = '1'; + } else { + this.requiresResolvers = '0'; + } + } + + @Transient + public static Collection importPIPConfigurations(Properties properties) { + Collection configurations = new ArrayList<>(); + String engines = properties.getProperty(XACMLProperties.PROP_PIP_ENGINES); + if (engines == null || engines.isEmpty()) { + return configurations; + } + for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(engines)) { + PIPConfiguration configuration; + try { + String user = "super-admin"; + configuration = new PIPConfiguration(id, properties, user); + configuration.setCreatedBy(user); + configuration.setModifiedBy(user); + configurations.add(configuration); + } catch (PIPException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Import failed: " + e.getLocalizedMessage()); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PIPConfiguration", "Import failed"); + } + } + + return configurations; + } + + @Transient + protected void readProperties(String id, Properties properties) throws PIPException { + // + // Save the id if we don't have one already + // + + if (this.id == 0) { + try { + this.id = Integer.parseInt(id); + } catch (NumberFormatException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Convert id to integer failed: " + id); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PIPConfiguration", "Convert id to integer failed"); + } + } + // + // Get its classname, this MUST exist. + // + this.classname = properties.getProperty(id + ".classname"); + if (this.classname == null) { + throw new PIPException("PIP Engine defined without a classname"); + } + // + // Go through each property + // + for (Object name : properties.keySet()) { + if (name.toString().startsWith(id) == false) { + continue; + } + if (name.equals(id + ".classname")) { + // + // We already saved this + // + } else if (name.equals(id + "." + StdConfigurableEngine.PROP_NAME)) { + this.name = properties.getProperty(name.toString()); + } else if (name.equals(id + "." + StdConfigurableEngine.PROP_DESCRIPTION)) { + this.description = properties.getProperty(name.toString()); + } else if (name.equals(id + "." + StdConfigurableEngine.PROP_ISSUER)) { + this.issuer = properties.getProperty(name.toString()); + } else if (name.equals(id + ".resolvers")) { + // + // It has resolvers, make sure this is set to true if + // it has been already. + // + this.setRequiresResolvers(true); + // + // Parse the resolvers + // + Collection resolvers = PIPResolver.importResolvers(id + ".resolver", + properties.getProperty(name.toString()), + properties,"super-admin" + ); + for (PIPResolver resolver : resolvers) { + this.addPipresolver(resolver); + } + } else if (name.toString().startsWith(id + ".resolver")) { + // + // Ignore, the PIPResolver will parse these values + // + } else { + // + // Config Parameter + // + this.addPipconfigParam(new PIPConfigParam(name.toString().substring(id.length() + 1), + properties.getProperty(name.toString()))); + } + } + // + // Make sure we have a name at least + // + if (this.name == null) { + this.name = id; + } + } + + + @Transient + public Map getConfiguration(String name) { + String prefix; + if (name == null) { + prefix = Integer.toString(this.id); + } else { + prefix = name; + } + if (prefix.endsWith(".") == false) { + prefix = prefix + "."; + } + Map map = new HashMap<>(); + map.put(prefix + "classname", this.classname); + map.put(prefix + "name", this.name); + if (this.description != null) { + map.put(prefix + "description", this.description); + } + if (this.issuer != null) { + map.put(prefix + "issuer", this.issuer); + } + + for (PIPConfigParam param : this.pipconfigParams) { + map.put(prefix + param.getParamName(), param.getParamValue()); + } + + List ids = new ArrayList<>(); + Iterator iter = this.pipresolvers.iterator(); + while (iter.hasNext()) { + PIPResolver resolver = iter.next(); + String id = Integer.toString(resolver.getId()); + Map resolverMap = resolver.getConfiguration(prefix + "resolver." + id); + map.putAll(resolverMap); + ids.add(id); + } + if (ids.size() > 0) { + map.put(prefix + "resolvers", Joiner.on(',').join(ids)); + } + return map; + } + + @Transient + public Properties generateProperties(String name) { + String prefix; + if (name == null) { + prefix = Integer.toString(this.id); + } else { + if (name.endsWith(".")) { + prefix = name; + } else { + prefix = name + "."; + } + } + Properties props = new Properties(); + props.setProperty("xacml.pip.engines", name); + props.setProperty(prefix + "classname", this.classname); + props.setProperty(prefix + "name", this.name); + if (this.description != null) { + props.setProperty(prefix + "description", this.description); + } + if (this.issuer != null && this.issuer.isEmpty() == false) { + props.setProperty(prefix + "issuer", this.issuer); + } + + for (PIPConfigParam param : this.pipconfigParams) { + props.setProperty(prefix + param.getParamName(), param.getParamValue()); + } + + List ids = new ArrayList<>(); + Iterator iter = this.pipresolvers.iterator(); + while (iter.hasNext()) { + PIPResolver resolver = iter.next(); + String id = Integer.toString(resolver.getId()); + resolver.generateProperties(props, prefix + "resolver." + id); + ids.add(id); + } + if (ids.size() > 0) { + props.setProperty(prefix + "resolvers", Joiner.on(',').join(ids)); + } + return props; + } + + @Transient + @Override + public String toString() { + return "PIPConfiguration [id=" + id + ", piptype=" + piptype + + ", classname=" + classname + ", name=" + name + + ", description=" + description + ", issuer=" + issuer + + ", readOnly=" + readOnly + ", requiresResolvers=" + + requiresResolvers + ", createdBy=" + createdBy + + ", createdDate=" + createdDate + ", modifiedBy=" + modifiedBy + + ", modifiedDate=" + modifiedDate + ", pipconfigParams=" + + pipconfigParams + ", pipresolvers=" + pipresolvers + "]"; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPResolver.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPResolver.java new file mode 100644 index 000000000..daab6d658 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPResolver.java @@ -0,0 +1,365 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import javax.persistence.CascadeType; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OneToMany; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import javax.persistence.Transient; + +import com.att.research.xacml.api.pip.PIPException; +import com.att.research.xacml.std.pip.engines.StdConfigurableEngine; +import com.google.common.base.Splitter; + + +/** + * The persistent class for the PIPResolver database table. + * + */ +@Entity +@Table(name="PIPResolver") +@NamedQuery(name="PIPResolver.findAll", query="SELECT p FROM PIPResolver p") +public class PIPResolver implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="DESCRIPTION", nullable=true, length=2048) + private String description; + + @Column(name="NAME", nullable=false, length=255) + private String name; + + @Column(name="ISSUER", nullable=true, length=1024) + private String issuer; + + @Column(name="CLASSNAME", nullable=false, length=2048) + private String classname; + + @Column(name="READ_ONLY", nullable=false) + private char readOnly = '0'; + + @Column(name="CREATED_BY", nullable=false, length=255) + private String createdBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="CREATED_DATE", nullable=false, updatable=false) + private Date createdDate; + + @Column(name="MODIFIED_BY", nullable=false, length=255) + private String modifiedBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="MODIFIED_DATE", nullable=false) + private Date modifiedDate; + + //bi-directional many-to-one association to PIPConfiguration + @ManyToOne + @JoinColumn(name="PIP_ID") + private PIPConfiguration pipconfiguration; + + //bi-directional many-to-one association to PIPResolverParam + @OneToMany(mappedBy="pipresolver", orphanRemoval=true, cascade=CascadeType.REMOVE) + private Set pipresolverParams = new HashSet<>(); + + public PIPResolver() { + } + + public PIPResolver(String prefix, Properties properties, String user) throws PIPException { + this.createdBy = user; + this.modifiedBy = user; + this.readOnly = '0'; + this.readProperties(prefix, properties); + } + + public PIPResolver(PIPResolver resolver) { + this.name = resolver.name; + this.description = resolver.description; + this.issuer = resolver.issuer; + this.classname = resolver.classname; + this.readOnly = resolver.readOnly; + for (PIPResolverParam param : this.pipresolverParams) { + this.addPipresolverParam(new PIPResolverParam(param)); + } + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + public String getIssuer() { + return issuer; + } + + public void setIssuer(String issuer) { + this.issuer = issuer; + } + + public String getClassname() { + return classname; + } + + public void setClassname(String classname) { + this.classname = classname; + } + + public char getReadOnly() { + return readOnly; + } + + public void setReadOnly(char readOnly) { + this.readOnly = readOnly; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public String getModifiedBy() { + return modifiedBy; + } + + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + public Date getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public PIPConfiguration getPipconfiguration() { + return this.pipconfiguration; + } + + public void setPipconfiguration(PIPConfiguration pipconfiguration) { + this.pipconfiguration = pipconfiguration; + } + + public Set getPipresolverParams() { + return this.pipresolverParams; + } + + public void setPipresolverParams(Set pipresolverParams) { + this.pipresolverParams = pipresolverParams; + } + + public PIPResolverParam addPipresolverParam(PIPResolverParam pipresolverParam) { + getPipresolverParams().add(pipresolverParam); + pipresolverParam.setPipresolver(this); + + return pipresolverParam; + } + + public PIPResolverParam removePipresolverParam(PIPResolverParam pipresolverParam) { + if (pipresolverParam == null) { + return pipresolverParam; + } + getPipresolverParams().remove(pipresolverParam); + pipresolverParam.setPipresolver(null); + + return pipresolverParam; + } + + @Transient + public void clearParams() { + while (this.pipresolverParams.isEmpty() == false) { + this.removePipresolverParam(this.pipresolverParams.iterator().next()); + } + } + + @Transient + public boolean isReadOnly() { + return (this.readOnly == '1'); + } + + @Transient + public void setReadOnly(boolean readOnly) { + if (readOnly) { + this.readOnly = '1'; + } else { + this.readOnly = '0'; + } + } + + @Transient + public static Collection importResolvers(String prefix, String list, Properties properties, String user) throws PIPException { + Collection resolvers = new ArrayList<>(); + for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(list)) { + resolvers.add(new PIPResolver(prefix + "." + id, properties, user)); + } + return resolvers; + } + + @Transient + protected void readProperties(String prefix, Properties properties) throws PIPException { + // + // Get its classname, this MUST exist. + // + this.classname = properties.getProperty(prefix + ".classname"); + if (this.classname == null) { + throw new PIPException("PIP Engine defined without a classname"); + } + // + // Go through each property + // + for (Object name : properties.keySet()) { + if (name.toString().startsWith(prefix) == false) { + continue; + } + if (name.equals(prefix + ".classname")) { + // + // We already saved this + // + } else if (name.equals(prefix + "." + StdConfigurableEngine.PROP_NAME)) { + this.name = properties.getProperty(name.toString()); + } else if (name.equals(prefix + "." + StdConfigurableEngine.PROP_DESCRIPTION)) { + this.description = properties.getProperty(name.toString()); + } else if (name.equals(prefix + "." + StdConfigurableEngine.PROP_ISSUER)) { + this.issuer = properties.getProperty(name.toString()); + } else { + this.addPipresolverParam(new PIPResolverParam(name.toString().substring(prefix.length() + 1), + properties.getProperty(name.toString()))); + } + } + } + + @Transient + public Map getConfiguration(String prefix) { + Map map = new HashMap<>(); + if (prefix.endsWith(".") == false) { + prefix = prefix + "."; + } + map.put(prefix + "classname", this.classname); + map.put(prefix + "name", this.name); + if (this.description != null) { + map.put(prefix + "description", this.description); + } + if (this.issuer != null && this.issuer.isEmpty() != false) { + map.put(prefix + "issuer", this.issuer); + } + for (PIPResolverParam param : this.pipresolverParams) { + map.put(prefix + param.getParamName(), param.getParamValue()); + } + return map; + } + + @Transient + public void generateProperties(Properties props, String prefix) { + if (prefix.endsWith(".") == false) { + prefix = prefix + "."; + } + props.setProperty(prefix + "classname", this.classname); + props.setProperty(prefix + "name", this.name); + if (this.description != null) { + props.setProperty(prefix + "description", this.description); + } + if (this.issuer != null && this.issuer.isEmpty() != false) { + props.setProperty(prefix + "issuer", this.issuer); + } + for (PIPResolverParam param : this.pipresolverParams) { + props.setProperty(prefix + param.getParamName(), param.getParamValue()); + } + } + + @Transient + @Override + public String toString() { + return "PIPResolver [id=" + id + ", classname=" + classname + ", name=" + + name + ", description=" + description + ", issuer=" + issuer + + ", readOnly=" + readOnly + ", createdBy=" + createdBy + + ", createdDate=" + createdDate + ", modifiedBy=" + modifiedBy + + ", modifiedDate=" + modifiedDate + ", pipresolverParams=" + + pipresolverParams + "]"; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPResolverParam.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPResolverParam.java new file mode 100644 index 000000000..8dec7915a --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPResolverParam.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; + +import javax.persistence.*; + + +/** + * The persistent class for the PIPResolverParams database table. + * + */ +@Entity +@Table(name="PIPResolverParams") +@NamedQuery(name="PIPResolverParam.findAll", query="SELECT p FROM PIPResolverParam p") +public class PIPResolverParam implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="PARAM_NAME", nullable=false, length=1024) + private String paramName; + + @Column(name="PARAM_VALUE", nullable=false, length=2048) + private String paramValue; + + @Column(name="PARAM_DEFAULT", nullable=true, length=2048) + private String paramDefault; + + @Column(name="REQUIRED", nullable=false) + private char required = '0'; + + //bi-directional many-to-one association to PIPResolver + @ManyToOne + @JoinColumn(name="ID_RESOLVER") + private PIPResolver pipresolver; + + public PIPResolverParam() { + } + + public PIPResolverParam(String name) { + this.paramName = name; + } + + public PIPResolverParam(String name, String value) { + this(name); + this.paramValue = value; + } + + public PIPResolverParam(PIPResolverParam param) { + this(param.getParamName(), param.getParamValue()); + this.paramDefault = param.getParamDefault(); + this.required = param.required; + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getParamName() { + return this.paramName; + } + + public void setParamName(String paramName) { + this.paramName = paramName; + } + + public String getParamValue() { + return this.paramValue; + } + + public void setParamValue(String paramValue) { + this.paramValue = paramValue; + } + + public String getParamDefault() { + return paramDefault; + } + + public void setParamDefault(String paramDefault) { + this.paramDefault = paramDefault; + } + + public char getRequired() { + return required; + } + + public void setRequired(char required) { + this.required = required; + } + + public PIPResolver getPipresolver() { + return this.pipresolver; + } + + public void setPipresolver(PIPResolver pipresolver) { + this.pipresolver = pipresolver; + } + + @Transient + public boolean isRequired() { + return this.required == '1'; + } + + @Transient + public void setRequired(boolean required) { + if (required) { + this.required = '1'; + } else { + this.required = '0'; + } + } + + @Transient + @Override + public String toString() { + return "PIPResolverParam [id=" + id + ", paramName=" + paramName + + ", paramValue=" + paramValue + ", required=" + required + "]"; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPType.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPType.java new file mode 100644 index 000000000..0ef4388c4 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PIPType.java @@ -0,0 +1,131 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.Set; + +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.OneToMany; +import javax.persistence.Table; +import javax.persistence.Transient; + + +/** + * The persistent class for the PIPType database table. + * + */ +@Entity +@Table(name="PIPType") +@NamedQuery(name="PIPType.findAll", query="SELECT p FROM PIPType p") +public class PIPType implements Serializable { + private static final long serialVersionUID = 1L; + + public static final String TYPE_SQL = "SQL"; + public static final String TYPE_LDAP = "LDAP"; + public static final String TYPE_CSV = "CSV"; + public static final String TYPE_HYPERCSV = "Hyper-CSV"; + public static final String TYPE_CUSTOM = "Custom"; + + @Id + @GeneratedValue(strategy=GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="type", nullable=false, length=45) + private String type; + + //bi-directional many-to-one association to PIPConfiguration + @OneToMany(mappedBy="piptype") + private Set pipconfigurations; + + public PIPType() { + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getType() { + return this.type; + } + + public void setType(String type) { + this.type = type; + } + + public Set getPipconfigurations() { + return this.pipconfigurations; + } + + public void setPipconfigurations(Set pipconfigurations) { + this.pipconfigurations = pipconfigurations; + } + + public PIPConfiguration addPipconfiguration(PIPConfiguration pipconfiguration) { + getPipconfigurations().add(pipconfiguration); + pipconfiguration.setPiptype(this); + + return pipconfiguration; + } + + public PIPConfiguration removePipconfiguration(PIPConfiguration pipconfiguration) { + getPipconfigurations().remove(pipconfiguration); + pipconfiguration.setPiptype(null); + + return pipconfiguration; + } + + @Transient + public boolean isSQL() { + return this.type.equals(TYPE_SQL); + } + + @Transient + public boolean isLDAP() { + return this.type.equals(TYPE_LDAP); + } + + @Transient + public boolean isCSV() { + return this.type.equals(TYPE_CSV); + } + + @Transient + public boolean isHyperCSV() { + return this.type.equals(TYPE_HYPERCSV); + } + + @Transient + public boolean isCustom() { + return this.type.equals(TYPE_CUSTOM); + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PdpEntity.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PdpEntity.java new file mode 100644 index 000000000..a76bd624a --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PdpEntity.java @@ -0,0 +1,241 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +/* + * The Entity class to persist a policy object and its configuration data + */ + +/** + * + */ +@Entity +//Add a non-unique index and a constraint that says the combo of policyName and scopeId must be unique +@Table(name="PdpEntity") +@NamedQueries({ + @NamedQuery(name="PdpEntity.findAll", query="SELECT e FROM PdpEntity e "), + @NamedQuery(name="PdpEntity.deleteAll", query="DELETE FROM PdpEntity WHERE 1=1") +}) + +public class PdpEntity implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + //@GeneratedValue(strategy = GenerationType.SEQUENCE, generator="seqPdp") + @GeneratedValue(strategy = GenerationType.AUTO) + @Column (name="pdpKey") + private long pdpKey; + + @Column (name="pdpId", nullable=false, unique=false, length=255) + private String pdpId; + + @Column(name="pdpName", nullable=false, unique=false, length=255) + private String pdpName; + + @Column(name="jmxPort", nullable=false, unique=false) + private int jmxPort; + + + @ManyToOne(optional=false) + @JoinColumn(name="groupKey", referencedColumnName="groupKey") + private GroupEntity groupEntity; + + @Column(name="created_by", nullable=false, length=255) + private String createdBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Column(name="description", nullable=false, length=2048) + private String description = "NoDescription"; + + @Column(name="modified_by", nullable=false, length=255) + private String modifiedBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @Column(name="deleted", nullable=false) + private boolean deleted = false; + + public PdpEntity() { + super(); + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + } + + public long getPdpKey(){ + return pdpKey; + } + /** + * @return the policyId + */ + public String getPdpId() { + return pdpId; + } + + public void setPdpId(String id){ + pdpId = id; + } + /** + * @param policyId cannot be set + */ + + public String getPdpName() { + return pdpName; + } + + public void setPdpName(String groupName) { + this.pdpName = groupName; + } + + + + /** + * @return the configurationDataEntity + */ + public GroupEntity getGroup() { + return groupEntity; + } + + /** + * @param configurationDataEntity the configurationDataEntity to set + */ + public void setGroup(GroupEntity group) { + this.groupEntity = group; + } + + + + /** + * @return the createdBy + */ + public String getCreatedBy() { + return createdBy; + } + + /** + * @param createdBy the createdBy to set + */ + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + /** + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * @param description the description to set + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * @return the modifiedBy + */ + public String getModifiedBy() { + return modifiedBy; + } + + /** + * @param modifiedBy the modifiedBy to set + */ + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + /** + * @return the version + */ + public int getJmxPort() { + return jmxPort; + } + + public void setJmxPort(int jmxPort){ + this.jmxPort = jmxPort; + } + + /** + * @return the createdDate + */ + public Date getCreatedDate() { + return createdDate; + } + + /** + * @return the modifiedDate + */ + public Date getModifiedDate() { + return modifiedDate; + } + + /** + * @return the deleted + */ + public boolean isDeleted() { + return deleted; + } + + /** + * @param deleted the deleted to set + */ + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyAlgorithms.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyAlgorithms.java new file mode 100644 index 000000000..4488fcd30 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyAlgorithms.java @@ -0,0 +1,116 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +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 javax.persistence.Transient; + +import com.att.research.xacml.api.Identifier; + +@Entity +@Table(name="PolicyAlgorithms") +@NamedQuery(name="PolicyAlgorithms.findAll", query="SELECT d FROM PolicyAlgorithms d") +public class PolicyAlgorithms implements Serializable { + private static final long serialVersionUID = 1L; + + public static final char STANDARD = 'S'; + public static final char CUSTOM = 'C'; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="is_standard", nullable=false) + private char isStandard; + + @Column(name="xacml_id", nullable=false, unique=true, length=255) + private String xacmlId; + + @Column(name="short_name", nullable=false, length=64) + private String shortName; + + public PolicyAlgorithms(Identifier identifier, char standard) { + this.isStandard = standard; + if (identifier != null) { + this.xacmlId = identifier.stringValue(); + } + } + + public PolicyAlgorithms(Identifier identifier) { + this(identifier, PolicyAlgorithms.STANDARD); + } + + public PolicyAlgorithms() { + this(null, PolicyAlgorithms.STANDARD); + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public char getIsStandard() { + return this.isStandard; + } + + public void setIsStandard(char isStandard) { + this.isStandard = isStandard; + } + + @Transient + public boolean isStandard() { + return (this.isStandard == PolicyAlgorithms.STANDARD); + } + + @Transient + public boolean isCustom() { + return (this.isStandard == PolicyAlgorithms.CUSTOM); + } + + public String getXacmlId() { + return this.xacmlId; + } + + public void setXacmlId(String xacmlId) { + this.xacmlId = xacmlId; + } + + public String getShortName() { + return shortName; + } + + public void setShortName(String shortName) { + this.shortName = shortName; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyDBDaoEntity.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyDBDaoEntity.java new file mode 100644 index 000000000..8b0843ed0 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyDBDaoEntity.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +/* + * The Entity class to persist a PolicyDBDaoEntity object for registration of PolicyDBDao + */ + +/** + * + */ +@Entity +@Table(name="PolicyDBDaoEntity") + +@NamedQueries({ + @NamedQuery(name="PolicyDBDaoEntity.findAll", query="SELECT e FROM PolicyDBDaoEntity e "), + @NamedQuery(name="PolicyDBDaoEntity.deleteAll", query="DELETE FROM PolicyDBDaoEntity WHERE 1=1") +}) + +public class PolicyDBDaoEntity implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @Column(name="policyDBDaoUrl", nullable=false, unique=true) + private String policyDBDaoUrl; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + //username for the pap server that registered this PolicyDBDaoEntity + @Column(name="username") + private String username; + + //AES encrypted password for the pap server that registered this PolicyDBDaoEntity + @Column(name="password") + private String password; + + //A column to allow some descriptive text. For example: Atlanta data center + @Column(name="description", nullable=false, length=2048) + private String description = "NoDescription"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + public PolicyDBDaoEntity() { + super(); + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + } + + /** + * @return the policyDBDaoUrl + */ + public String getPolicyDBDaoUrl() { + return policyDBDaoUrl; + } + + /** + * @param url the policyDBDaoUrl to set + */ + public void setPolicyDBDaoUrl(String url) { + this.policyDBDaoUrl = url; + } + + /** + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * @param description the description to set + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * @return the createdDate + */ + public Date getCreatedDate() { + return createdDate; + } + + /** + * @return the modifiedDate + */ + public Date getModifiedDate() { + return modifiedDate; + } + + public String getUsername(){ + return this.username; + } + public void setUsername(String username){ + this.username = username; + } + public String getPassword(){ + return this.password; + } + public void setPassword(String password){ + this.password = password; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyEditorScopes.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyEditorScopes.java new file mode 100644 index 000000000..bfb4218ab --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyEditorScopes.java @@ -0,0 +1,159 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.rest.XacmlAdminAuthorization; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + +@Entity +@Table(name="PolicyEditorScopes") +@NamedQuery(name="PolicyEditorScopes.findAll", query="SELECT p FROM PolicyEditorScopes p ") +public class PolicyEditorScopes implements Serializable{ + private static final long serialVersionUID = 1L; + private static Log logger = LogFactory.getLog(PolicyEditorScopes.class); + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="scopeName", nullable=false, unique=true) + @OrderBy("asc") + private String scopeName; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + public PolicyEditorScopes() { + } + + public PolicyEditorScopes(String string, String userid) { + this(domain); + } + + public PolicyEditorScopes(String domain) { + this.scopeName = domain; + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy =XacmlAdminAuthorization.getUserId(); + } catch (Exception e) { + logger.error("Exception caused While adding Modified by Role"+e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyEditorScopes", "Exception caused While adding Modified by Role"); + } + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getScopeName() { + return scopeName; + } + + public void setScopeName(String scopeName) { + this.scopeName = scopeName; + } + + public Date getCreatedDate() { + return this.createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public Date getModifiedDate() { + return this.modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyEntity.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyEntity.java new file mode 100644 index 000000000..4cb4440c1 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyEntity.java @@ -0,0 +1,308 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.Lob; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.OneToOne; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import javax.persistence.Version; + +import com.fasterxml.jackson.annotation.JsonBackReference; +import com.fasterxml.jackson.annotation.JsonManagedReference; + +/* + * The Entity class to persist a policy object and its configuration data + */ + +/** + * + */ +@Entity +//Add a non-unique index and a constraint that says the combo of policyName and scopeId must be unique +@Table(name="PolicyEntity") + +@NamedQueries({ + @NamedQuery(name="PolicyEntity.findAll", query="SELECT e FROM PolicyEntity e "), + @NamedQuery(name="PolicyEntity.findAllByDeletedFlag", query="SELECT e FROM PolicyEntity e WHERE e.deleted = :deleted"), + @NamedQuery(name="PolicyEntity.FindById", query="SELECT e FROM PolicyEntity e WHERE e.policyId = :id"), + @NamedQuery(name="PolicyEntity.deleteAll", query="DELETE FROM PolicyEntity WHERE 1=1"), + @NamedQuery(name="PolicyEntity.findByNameAndScope", query="SELECT e FROM PolicyEntity e WHERE e.policyName = :name AND e.scope = :scope") +}) + +public class PolicyEntity implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column (name="policyId") + @JsonBackReference + private long policyId; + + @Column(name="policyName", nullable=false, unique=false, length=255) + private String policyName; + + //The scope is the directory structure in dot notation. For example: org.onap.myproject + @Column(name="scope", nullable=false, unique=false, length=255) + private String scope; + + @Version + @Column(name="version") + private int version; + + //not going to be used + @Column(name="policyVersion") + private int policyVersion = 0; + + @Lob + @Column(name="policyData", nullable=false, columnDefinition="TEXT") + private String policyData = "NoData"; + + @OneToOne(optional=true, orphanRemoval=true) + @JoinColumn(name="configurationDataId") + @JsonManagedReference + private ConfigurationDataEntity configurationDataEntity; + + @OneToOne(optional=true, orphanRemoval=true) + @JoinColumn(name="actionBodyId") + @JsonManagedReference + private ActionBodyEntity actionBodyEntity; + + @Column(name="created_by", nullable=false, length=255) + private String createdBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Column(name="description", nullable=false, length=2048) + private String description = "NoDescription"; + + @Column(name="modified_by", nullable=false, length=255) + private String modifiedBy = "guest"; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @Column(name="deleted", nullable=false) + private boolean deleted = false; + + public PolicyEntity() { + super(); + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + } + + /* + public void resetPolicyVersion(){ + this.policyVersion = 1; + } + public void advancePolicyVersion(){ + this.policyVersion++; + } + public int getPolicyVersion(){ + return this.policyVersion; + } + public void setPolicyVersion(int polVer){ + this.policyVersion = polVer; + } + */ + + /** + * @return the policyId + */ + public long getPolicyId() { + return policyId; + } + + /** + * @param policyId cannot be set + */ + + public String getPolicyName() { + return policyName; + } + + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + + /** + * @return the policyData + */ + public String getPolicyData() { + return policyData; + } + + /** + * @param policyData the policyData to set + */ + public void setPolicyData(String policyData) { + this.policyData = policyData; + } + + /** + * @return the configurationDataEntity + */ + public ConfigurationDataEntity getConfigurationData() { + return configurationDataEntity; + } + + /** + * @param configurationDataEntity the configurationDataEntity to set + */ + public void setConfigurationData(ConfigurationDataEntity configurationDataEntity) { + this.configurationDataEntity = configurationDataEntity; + } + + /** + * @return the actionBodyEntity + */ + public ActionBodyEntity getActionBodyEntity() { + return actionBodyEntity; + } + + /** + * @param actionBodyEntity the actionBodyEntity to set + */ + public void setActionBodyEntity(ActionBodyEntity actionBodyEntity) { + this.actionBodyEntity = actionBodyEntity; + } + + /** + * @return the scope + */ + public String getScope() { + return scope; + } + + /** + * @param scope the scope to set + */ + public void setScope(String scope) { + this.scope = scope; + } + + /** + * @return the createdBy + */ + public String getCreatedBy() { + return createdBy; + } + + /** + * @param createdBy the createdBy to set + */ + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + /** + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * @param description the description to set + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * @return the modifiedBy + */ + public String getModifiedBy() { + return modifiedBy; + } + + /** + * @param modifiedBy the modifiedBy to set + */ + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + /** + * @return the version + */ + public int getVersion() { + return version; + } + + /** + * @return the createdDate + */ + public Date getCreatedDate() { + return createdDate; + } + + /** + * @return the modifiedDate + */ + public Date getModifiedDate() { + return modifiedDate; + } + + /** + * @return the deleted + */ + public boolean isDeleted() { + return deleted; + } + + /** + * @param deleted the deleted to set + */ + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyGroupEntity.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyGroupEntity.java new file mode 100644 index 000000000..ef2ff6e56 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyGroupEntity.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.NamedQuery; +import javax.persistence.Table; + +@Entity +@Table(name="PolicyGroupEntity") +@NamedQuery(name="PolicyGroupEntity.findAll", query="SELECT p FROM PolicyGroupEntity p ") +public class PolicyGroupEntity implements Serializable{ + + private static final long serialVersionUID = 1L; + + @Id + @Column(name="groupKey") + private int groupKey; + + @Id + @Column(name="policyid") + private int policyid; + + public int getGroupKey() { + return groupKey; + } + + public void setGroupKey(int groupKey) { + this.groupKey = groupKey; + } + + public int getPolicyid() { + return policyid; + } + + public void setPolicyid(int policyid) { + this.policyid = policyid; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyManagement.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyManagement.java new file mode 100644 index 000000000..2a6571e52 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyManagement.java @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.sql.Clob; +import java.sql.Timestamp; + +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; + + +/** + * The persistent class for the roles database table. + * + */ +@Entity +@Table(name="policy_manangement") +@NamedQuery(name="PolicyManagement.findAll", query="SELECT r FROM PolicyManagement r") +public class PolicyManagement implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + + @Column(name="id") + private int id; + + @Column(name="POLICY_NAME", nullable=false, length=45) + private String policyName; + + @Column(name="scope", nullable=false, length=45) + private String scope; + + @Column(name="ONAP_NAME", nullable=false, length=45) + private String onapName; + + @Column(name="CONFIG_NAME", nullable=false, length=45) + private String configName; + + @Column(name="XML", nullable=false) + private Clob xml; + + @Column(name="CREATE_DATE_TIME", nullable=false) + private Timestamp createDateTime; + + + @Column(name="CREATED_BY", nullable=false, length=45) + private String createdBy; + + @Column(name="UPDATE_DATE_TIME", nullable=false) + private Timestamp updateDateTime; + + @Column(name="UPDATED_BY", nullable=false, length=45) + private String updatedBy; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getPolicyName() { + return policyName; + } + + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + + public String getScope() { + return scope; + } + + public void setScope(String scope) { + this.scope = scope; + } + + public String getOnapName() { + return onapName; + } + + public void setOnapName(String onapName) { + this.onapName = onapName; + } + + public String getConfigName() { + return configName; + } + + public void setConfigName(String configName) { + this.configName = configName; + } + + public Clob getXml() { + return xml; + } + + public void setXml(Clob xml) { + this.xml = xml; + } + + public Timestamp getCreateDateTime() { + return createDateTime; + } + + public void setCreateDateTime(Timestamp createDateTime) { + this.createDateTime = createDateTime; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public Timestamp getUpdateDateTime() { + return updateDateTime; + } + + public void setUpdateDateTime(Timestamp updateDateTime) { + this.updateDateTime = updateDateTime; + } + + public String getUpdatedBy() { + return updatedBy; + } + + public void setUpdatedBy(String updatedBy) { + this.updatedBy = updatedBy; + } + + + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyRoles.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyRoles.java new file mode 100644 index 000000000..99d6075a3 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyRoles.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.Table; + +import org.onap.policy.rest.jpa.UserInfo; + + +/** + * The persistent class for the roles database table. + * + */ +@Entity +@Table(name="roles") +@NamedQuery(name="PolicyRoles.findAll", query="SELECT r FROM PolicyRoles r ") +public class PolicyRoles implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + + @Column(name="id") + private int id; + + @ManyToOne + @JoinColumn(name="loginid") + @OrderBy("asc") + private UserInfo loginId; + + public UserInfo getLoginId() { + return loginId; + } + + public void setLoginId(UserInfo loginId) { + this.loginId = loginId; + } + + @Column(name="scope", nullable=true, length=45) + private String scope; + + @Column(name="role", nullable=false, length=45) + private String role; + + public PolicyRoles() { + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getScope() { + return this.scope; + } + + public void setScope(String scope) { + this.scope = scope; + + } + public String getRole() { + return this.role; + } + + public void setRole(String role) { + this.role = role; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeClosedLoop.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeClosedLoop.java new file mode 100644 index 000000000..6fc45eb70 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeClosedLoop.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + + +@Entity +@Table(name="PolicyScopeClosedLoop") +@NamedQuery(name="PolicyScopeClosedLoop.findAll", query="SELECT e FROM PolicyScopeClosedLoop e ") +public class PolicyScopeClosedLoop implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String name; + + @Column(name="description ") + private String description ; + + public PolicyScopeClosedLoop() { + + } + public PolicyScopeClosedLoop(String string, String userid) { + this(domain); + + } + public PolicyScopeClosedLoop(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + + } + public String getDescriptionValue() { + return this.description ; + } + + public void setDescriptionValue(String description ) { + this.description = description ; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeResource.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeResource.java new file mode 100644 index 000000000..f9ec94564 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeResource.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + + +@Entity +@Table(name="PolicyScopeResource") +@NamedQuery(name="PolicyScopeResource.findAll", query="SELECT e FROM PolicyScopeResource e ") +public class PolicyScopeResource implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String name; + + @Column(name="description ") + private String description ; + + public PolicyScopeResource() { + + } + public PolicyScopeResource(String string, String userid) { + this(domain); + + } + public PolicyScopeResource(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + + } + public String getDescriptionValue() { + return this.description ; + } + + public void setDescriptionValue(String description ) { + this.description = description ; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeService.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeService.java new file mode 100644 index 000000000..84e85570b --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeService.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + + +@Entity +@Table(name="PolicyScopeService") +@NamedQuery(name="PolicyScopeService.findAll", query="SELECT e FROM PolicyScopeService e ") +public class PolicyScopeService implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String name; + + @Column(name="description ") + private String description ; + + public PolicyScopeService() { + + } + public PolicyScopeService(String string, String userid) { + this(domain); + + } + public PolicyScopeService(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + + } + public String getDescriptionValue() { + return this.description ; + } + + public void setDescriptionValue(String description ) { + this.description = description ; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeType.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeType.java new file mode 100644 index 000000000..48f17b0fc --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScopeType.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + + +@Entity +@Table(name="PolicyScopeType") +@NamedQuery(name="PolicyScopeType.findAll", query="SELECT e FROM PolicyScopeType e ") +public class PolicyScopeType implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String name; + + @Column(name="description ") + private String description ; + + public PolicyScopeType() { + + } + public PolicyScopeType(String string, String userid) { + this(domain); + + } + public PolicyScopeType(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + + } + public String getDescriptionValue() { + return this.description ; + } + + public void setDescriptionValue(String description ) { + this.description = description ; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScore.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScore.java new file mode 100644 index 000000000..3ad4b9b85 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyScore.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +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.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.Table; + + +@Entity +@Table(name="POLICYSCORE") +@NamedQueries({ + @NamedQuery(name="POLICYSCORE.findAll", query="SELECT p FROM PolicyScore p"), + @NamedQuery(name="POLICYSCORE.deleteAll", query="DELETE FROM PolicyScore WHERE 1=1"), + @NamedQuery(name="POLICYSCORE.findByPolicyName", query="Select p from PolicyScore p where p.PolicyName=:pname") +}) +public class PolicyScore implements Serializable { + + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="POLICY_NAME", nullable=false) + @OrderBy("asc") + private String PolicyName; + + @Column(name="VERSIONEXTENSION", nullable=false) + @OrderBy("asc") + private String VersionExtension; + + @Column(name="POLICY_SCORE", nullable=true) + private String PolicyScore; + + public PolicyScore() { + + } + + public PolicyScore(String pName, String pScore) { + this(domain); + + } + public PolicyScore(String domain) { + + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + public String getPolicyName() { + return PolicyName; + } + public void setPolicyName(String policyName) { + PolicyName = policyName; + } + public String getVersionExtension() { + return VersionExtension; + } + + public void setVersionExtension(String versionExtension) { + VersionExtension = versionExtension; + } + public String getPolicyScore() { + return PolicyScore; + } + public void setPolicyScore(String policyScore) { + PolicyScore = policyScore; + } + + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyVersion.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyVersion.java new file mode 100644 index 000000000..d098ee5a2 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PolicyVersion.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +//import java.sql.Clob; +import java.sql.Timestamp; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.NamedQueries; +import javax.persistence.NamedQuery; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + + +@Entity +@Table(name="PolicyVersion") +@NamedQueries({ + @NamedQuery(name="PolicyVersion.findAll", query="SELECT p FROM PolicyVersion p"), + @NamedQuery(name="PolicyVersion.deleteAll", query="DELETE FROM PolicyVersion WHERE 1=1"), + @NamedQuery(name="PolicyVersion.findByPolicyName", query="Select p from PolicyVersion p where p.policyName=:pname"), + @NamedQuery(name="PolicyVersion.findAllCount", query="SELECT COUNT(p) FROM PolicyVersion p") +}) +public class PolicyVersion implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + + @Column(name="id") + private int id; + + @Column(name="POLICY_NAME", nullable=false, length=255) + private String policyName; + + @Column(name="ACTIVE_VERSION") + private int activeVersion; + + @Column(name="HIGHEST_VERSION") + private int higherVersion; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", nullable=false) + private Date createdDate; + + + public int getActiveVersion() { + return activeVersion; + } + + public void setActiveVersion(int activeVersion) { + this.activeVersion = activeVersion; + } + + public int getHigherVersion() { + return higherVersion; + } + + public void setHigherVersion(int higherVersion) { + this.higherVersion = higherVersion; + } + + @Column(name="CREATED_BY", nullable=false, length=45) + private String createdBy; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + + @Column(name="modified_by", nullable=false, length=45) + private String modifiedBy; + + public PolicyVersion(String domain, String loginUserId) { + this(domain); + this.createdBy = loginUserId; + this.modifiedBy = loginUserId; + } + + public PolicyVersion(String domain) { + this.policyName = domain; + } + + public PolicyVersion(){ + + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + /* + * The modifiedBy must be set via the setModifiedBy() method since PolicyVersion + * has been moved to XACML-REST module for access from the XACML-PAP-REST module + + String userid = ((XacmlAdminUI) UI.getCurrent()).getLoginUserId(); + this.modifiedBy =userid; + * + */ + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getPolicyName() { + return policyName; + } + + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Timestamp createdDate) { + this.createdDate = createdDate; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public Date getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(Timestamp modifiedDate) { + this.modifiedDate = modifiedDate; + } + + public String getModifiedBy() { + return modifiedBy; + } + + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + +} + diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PortList.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PortList.java new file mode 100644 index 000000000..5d2f35414 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PortList.java @@ -0,0 +1,104 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + +@Entity +@Table(name="portlist") +@NamedQuery(name="PortList.findAll", query="SELECT e FROM PortList e ") +public class PortList implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="portname", nullable=false) + @OrderBy("asc") + private String portName; + + @Column(name="description") + private String description; +/* + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate;*/ + + public PortList() { + + } + public PortList(String string, String userid) { + this(domain); + + } + public PortList(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getPortName() { + return this.portName; + } + + public void setPortName(String portName) { + this.portName = portName; + + } + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PrefixList.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PrefixList.java new file mode 100644 index 000000000..98e940228 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/PrefixList.java @@ -0,0 +1,114 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + +@Entity +@Table(name="PrefixList") +@NamedQuery(name="PrefixList.findAll", query="SELECT e FROM PrefixList e ") +public class PrefixList implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="pl_name", nullable=false) + @OrderBy("asc") + private String prefixListName; + + @Column(name="description", nullable=false) + private String description; + + @Column(name="pl_value", nullable=false) + private String prefixListValue; +/* + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate;*/ + + public PrefixList() { + + } + public PrefixList(String string, String userid) { + this(domain); + + } + public PrefixList(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + public String getPrefixListName() { + return this.prefixListName; + } + + public void setPrefixListName(String prefixListName) { + this.prefixListName = prefixListName; + + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + + } + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getPrefixListValue() { + return this.prefixListValue; + } + + public void setPrefixListValue(String prefixListValue) { + this.prefixListValue = prefixListValue; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ProtocolList.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ProtocolList.java new file mode 100644 index 000000000..befea36ed --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ProtocolList.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + +@Entity +@Table(name="protocollist") +@NamedQuery(name="ProtocolList.findAll", query="SELECT e FROM ProtocolList e ") +public class ProtocolList implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="protocolname", nullable=false) + @OrderBy("asc") + private String protocolName; + + @Column(name="description") + private String description; +/* + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate;*/ + + public ProtocolList() { + + } + public ProtocolList(String string, String userid) { + this(domain); + + } + public ProtocolList(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + public String getProtocolName() { + return this.protocolName; + } + + public void setProtocolName(String protocolName) { + this.protocolName = protocolName; + + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RainyDayTreatments.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RainyDayTreatments.java new file mode 100644 index 000000000..383eb11c2 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RainyDayTreatments.java @@ -0,0 +1,118 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +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.OrderBy; +import javax.persistence.Table; + +import java.io.Serializable; + +/** + * The persistent class for the RainyDayTreatment database table. + * + */ +@Entity +@Table(name="RainyDayTreatments") +@NamedQuery(name="RainyDayTreatments.findAll", query="SELECT e FROM RainyDayTreatments e") +public class RainyDayTreatments implements Serializable { + /** + * + */ + private static final long serialVersionUID = -2491410352490381323L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="bbid", nullable=false, length=255) + @OrderBy("asc") + private String bbid; + + @Column(name="workstep", nullable=true, length=255) + private String workstep; + + @Column(name="treatments", nullable=true, length=1028) + private String treatments; + + public RainyDayTreatments() { + + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + /** + * @return the bbid + */ + public String getBbid() { + return bbid; + } + + /** + * @param bbid the bbid to set + */ + public void setBbid(String bbid) { + this.bbid = bbid; + } + + /** + * @return the workstep + */ + public String getWorkstep() { + return workstep; + } + + /** + * @param workstep the workstep to set + */ + public void setWorkstep(String workstep) { + this.workstep = workstep; + } + + /** + * @return the treatments + */ + public String getTreatments() { + return treatments; + } + + /** + * @param treatments the treatments to set + */ + public void setTreatments(String treatments) { + this.treatments = treatments; + } + + +} \ No newline at end of file diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RemoteCatalogValues.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RemoteCatalogValues.java new file mode 100644 index 000000000..f0443c0db --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RemoteCatalogValues.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + + +@Entity +@Table(name="RemoteCatalogValues") +@NamedQuery(name="RemoteCatalogValues.findAll", query="SELECT e FROM RemoteCatalogValues e ") +public class RemoteCatalogValues implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String name; + + @Column(name="value") + private String value; + + + public RemoteCatalogValues() { + + } + public RemoteCatalogValues(String string, String userid) { + this(domain); + + } + public RemoteCatalogValues(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RiskType.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RiskType.java new file mode 100644 index 000000000..155372617 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RiskType.java @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.rest.XacmlAdminAuthorization; + + +@Entity +@Table(name="RiskType") +@NamedQuery(name="RiskType.findAll", query="SELECT e FROM RiskType e ") +public class RiskType implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false, unique=true) + @OrderBy("asc") + private String name; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + private static Log LOGGER = LogFactory.getLog(RiskType.class); + + public RiskType() { + + } + + public RiskType(String string, String userid) { + this(domain); + } + + public RiskType(String domain) { + this.name = domain; + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy =XacmlAdminAuthorization.getUserId(); + } catch (Exception e) { + LOGGER.error("Exception caused While adding Modified by Role"+e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "RiskType", "Exception caused While adding Modified by Role"); + } + } + public String getRiskName() { + return this.name; + } + + public void setRiskName(String riskName) { + this.name = riskName; + + } + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public Date getCreatedDate() { + return this.createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getModifiedDate() { + return this.modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RuleAlgorithms.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RuleAlgorithms.java new file mode 100644 index 000000000..83f6e2d3e --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/RuleAlgorithms.java @@ -0,0 +1,125 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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========================================================= + */ + +/* + * AT&T - PROPRIETARY + * THIS FILE CONTAINS PROPRIETARY INFORMATION OF + * AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN + * ACCORDANCE WITH APPLICABLE AGREEMENTS. + * + * Copyright (c) 2014 AT&T Knowledge Ventures + * Unpublished and Not for Publication + * All Rights Reserved + */ +package org.onap.policy.rest.jpa; + +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 javax.persistence.Transient; + +import com.att.research.xacml.api.Identifier; + +@Entity +@Table(name="RuleAlgorithms") +@NamedQuery(name="RuleAlgorithms.findAll", query="SELECT d FROM RuleAlgorithms d") +public class RuleAlgorithms implements Serializable { + private static final long serialVersionUID = 1L; + + public static final char STANDARD = 'S'; + public static final char CUSTOM = 'C'; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="is_standard", nullable=false) + private char isStandard; + + @Column(name="xacml_id", nullable=false, unique=true, length=255) + private String xacmlId; + + @Column(name="short_name", nullable=false, length=64) + private String shortName; + + public RuleAlgorithms(Identifier id, char standard) { + if (id != null) { + this.xacmlId = id.stringValue(); + } + this.isStandard = standard; + } + public RuleAlgorithms(Identifier id) { + this(id, RuleAlgorithms.STANDARD); + } + + public RuleAlgorithms() { + this(null, RuleAlgorithms.STANDARD); + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public char getIsStandard() { + return this.isStandard; + } + + public void setIsStandard(char isStandard) { + this.isStandard = isStandard; + } + + @Transient + public boolean isStandard() { + return (this.isStandard == RuleAlgorithms.STANDARD); + } + + @Transient + public boolean isCustom() { + return (this.isStandard == RuleAlgorithms.CUSTOM); + } + + public String getXacmlId() { + return this.xacmlId; + } + + public void setXacmlId(String xacmlId) { + this.xacmlId = xacmlId; + } + + public String getShortName() { + return shortName; + } + + public void setShortName(String shortName) { + this.shortName = shortName; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SafePolicyWarning.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SafePolicyWarning.java new file mode 100644 index 000000000..1f92fe67a --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SafePolicyWarning.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + + +@Entity +@Table(name="SafePolicyWarning") +@NamedQuery(name="SafePolicyWarning.findAll", query="SELECT e FROM SafePolicyWarning e ") +public class SafePolicyWarning implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String name; + + @Column(name="message") + private String message ; + + @Column(name="riskType") + private String riskType ; + + public String getRiskType() { + return riskType; + } + public void setRiskType(String riskType) { + this.riskType = riskType; + } + public SafePolicyWarning() { + + } + public SafePolicyWarning(String string, String userid) { + this(domain); + + } + public SafePolicyWarning(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getName() { + return this.name; + } + + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + public void setName(String name) { + this.name = name; + + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SecurityZone.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SecurityZone.java new file mode 100644 index 000000000..d8bc33c13 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SecurityZone.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + +@Entity +@Table(name="securityzone") +@NamedQuery(name="SecurityZone.findAll", query="SELECT e FROM SecurityZone e ") +public class SecurityZone implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String zoneName; + + @Column(name="value") + private String zoneValue; + + + public SecurityZone() { + + } + public SecurityZone(String string, String userid) { + this(domain); + + } + public SecurityZone(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getZoneName() { + return this.zoneName; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + + } + public String getZoneValue() { + return this.zoneValue; + } + + public void setZoneValue(String zoneValue) { + this.zoneValue = zoneValue; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ServiceList.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ServiceList.java new file mode 100644 index 000000000..40e31172e --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/ServiceList.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + +@Entity +@Table(name="servicegroup") +@NamedQuery(name="ServiceList.findAll", query="SELECT e FROM ServiceList e ") +public class ServiceList implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String serviceName; + + @Column(name="description") + private String serviceDesc; + + @Column(name="type") + private String serviceType; + + @Column(name="transportprotocol") + private String serviceTrasProtocol; + + @Column(name="appprotocol ") + private String serviceAppProtocol; + + @Column(name="ports") + private String servicePorts; + + + +/* + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate;*/ + + public ServiceList() { + + } + public ServiceList(String string, String userid) { + this(domain); + + } + public ServiceList(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getServiceName() { + return this.serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + + } + + public String getServiceDescription() { + return this.serviceDesc; + } + + public void setServiceDescription(String serviceDesc) { + this.serviceDesc = serviceDesc; + + } + + public String getServiceType() { + return this.serviceType; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public String getServiceTransProtocol() { + return this.serviceTrasProtocol; + } + + public void setServiceTransProtocol(String serviceTrasProtocol) { + this.serviceTrasProtocol = serviceTrasProtocol; + + } + + public String getServiceAppProtocol() { + return this.serviceAppProtocol; + } + + public void setServiceAppProtocol(String serviceAppProtocol) { + this.serviceAppProtocol = serviceAppProtocol; + + } + public String getServicePorts() { + return this.servicePorts; + } + + public void setServicePorts(String servicePorts) { + this.servicePorts = servicePorts; + + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SystemLogDB.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SystemLogDB.java new file mode 100644 index 000000000..0747c837f --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/SystemLogDB.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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========================================================= + */ + +/* + * AT&T - PROPRIETARY + * THIS FILE CONTAINS PROPRIETARY INFORMATION OF + * AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN + * ACCORDANCE WITH APPLICABLE AGREEMENTS. + * + * Copyright (c) 2013 AT&T Knowledge Ventures + * Unpublished and Not for Publication + * All Rights Reserved + */ +package org.onap.policy.rest.jpa; + +import java.io.Serializable; +import java.util.Date; + +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 javax.persistence.Temporal; +import javax.persistence.TemporalType; + +/** + * The persistent class for the system log database table. + * +*/ +@Entity +@Table(name="SystemLogDB") +@NamedQuery(name="SystemLogDB.findAll", query="SELECT o FROM SystemLogDB o") +public class SystemLogDB implements Serializable { + private static final long serialVersionUID = 1L; + + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="type", nullable=false) + private String type; + + @Column(name="system", nullable=false, length=255) + private String system; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Column(name="remote", nullable=false, length=255) + private String remote; + + @Column(name="logtype", nullable=false, length=255) + private String logtype; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="date", nullable=false, updatable=false) + private Date date; + + public SystemLogDB() { + super(); + } + + public SystemLogDB(int id, String system, String description, String remote, + String type, String logtype) { + this.id = id; + this.system = system; + this.description = description; + this.remote = remote; + this.type = type; + this.logtype = logtype; + } + + public void SystemLogB (int id, String system, String description, String remote, String type, Date date, String logtype){ + this.id = id; + this.system = system; + this.description = description; + this.remote = remote; + this.type = type; + this.date = date; + this.logtype = logtype; + + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public Date getDate(){ + return this.date; + } + + public void setDate(Date date){ + this.date = date; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getType() { + return this.type; + } + + public void setType(String type) { + this.type = type; + + } + + public String getSystem() { + return this.system; + } + + public void setSystem(String system) { + this.system = system; + } + + public String getRemote() { + return this.remote; + } + + public void setRemote(String remote) { + this.remote = remote; + + } + public String getLogtype() { + return this.logtype; + } + + public void setLogtype(String logtype) { + this.logtype = logtype; + + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/TermList.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/TermList.java new file mode 100644 index 000000000..c9a27ef15 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/TermList.java @@ -0,0 +1,261 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.rest.XacmlAdminAuthorization; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + + +@Entity +@Table(name="TERM") +@NamedQuery(name="TermList.findAll", query="SELECT e FROM TermList e") +public class TermList implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="termName", nullable=false) + @OrderBy("asc") + private String termName; + + @Column(name="description") + private String termDescription; + + @Column(name="fromzone") + private String fromZone; + + @Column(name="tozone") + private String toZone; + + @Column(name="srcIPList") + private String srcIPList; + + @Column(name="destIPList") + private String destIPList; + + @Column(name="protocolList") + private String protocolList; + + @Column(name="portList") + private String portList; + + @Column(name="srcPortList") + private String srcPortList; + + @Column(name="destPortList") + private String destPortList; + + @Column(name="action") + private String action; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + private static Log LOGGER = LogFactory.getLog(TermList.class); + + public TermList() { + + } + + private static final Log auditLogger = LogFactory + .getLog("auditLogger"); + + public TermList(String string, String userid) { + this(domain); + } + public TermList(String domain) { + this.termName = domain; + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + auditLogger.debug("Added New Term Name: "+this.termName+" by "+this.userCreatedBy); + + } + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy =XacmlAdminAuthorization.getUserId();; + } catch (Exception e) { + LOGGER.error("Exception caused While adding Modified by Role"+e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "TermList", "Exception caused While adding Modified by Role"); + } + auditLogger.debug("Updated Term Name: "+this.termName+" by "+this.userModifiedBy); + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getTermName() { + return this.termName; + } + + public void setTermName(String termName) { + this.termName = termName; + } + + public String getTermDescription() { + return this.termDescription; + } + + public void setDescription(String termDescription) { + this.termDescription = termDescription; + } + + public String getFromZone() { + return this.fromZone; + } + + public void setFromZones(String fromZone) { + this.fromZone = fromZone; + } + + public String getToZone() { + return this.toZone; + } + + public void setToZones(String toZone) { + this.toZone = toZone; + } + + public String getSrcIPList() { + return this.srcIPList; + } + + public void setSrcIPList(String srcIPList) { + this.srcIPList = srcIPList; + } + + public String getDestIPList() { + return this.destIPList; + } + + public void setDestIPList(String destIPList) { + this.destIPList = destIPList; + } + + public String getProtocolList() { + return this.protocolList; + } + + public void setProtocolList(String protocolList) { + this.protocolList = protocolList; + } + + public String getPortList() { + return this.portList; + } + + public void setPortList(String portList) { + this.portList = portList; + } + + public String getSrcPortList() { + return this.srcPortList; + } + + public void setSrcPortList(String srcPortList) { + this.srcPortList = srcPortList; + } + + public String getDestPortList() { + return this.destPortList; + } + + public void setDestPortList(String destPortList) { + this.destPortList = destPortList; + } + + + public String getAction() { + return this.action; + } + + public void setAction(String action) { + this.action = action; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/UserInfo.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/UserInfo.java new file mode 100644 index 000000000..d2185c27b --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/UserInfo.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.NamedQuery; +import javax.persistence.Table; +import javax.persistence.Transient; + +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.std.IdentifierImpl; +import com.fasterxml.jackson.annotation.JsonBackReference; + +@Entity +@Table(name = "UserInfo") +@NamedQuery(name="UserInfo.findAll", query="SELECT u FROM UserInfo u ") +public class UserInfo implements Serializable { + private static final long serialVersionUID = 1L; + + @Id + @Column(name="loginid", nullable=false, length=45) + private String userLoginId; + + @Column(name = "name", nullable = false, unique = true) + private String userName; + + public UserInfo(){ + this.userLoginId = userName; + + } + + public String getUserLoginId() { + return userLoginId; + } + + public void setUserLoginId(String loginid) { + this.userLoginId = loginid; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + @Transient + @JsonBackReference + public Identifier getIdentiferByUserId() { + return new IdentifierImpl(this.userName); + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VMType.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VMType.java new file mode 100644 index 000000000..01df59201 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VMType.java @@ -0,0 +1,102 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + + +@Entity +@Table(name="VMType") +@NamedQuery(name="VMType.findAll", query="SELECT e FROM VMType e ") +public class VMType implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="name", nullable=false) + @OrderBy("asc") + private String name; + + @Column(name="description") + private String description; + + + public VMType() { + + } + public VMType(String string, String userid) { + this(domain); + + } + public VMType(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VNFType.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VNFType.java new file mode 100644 index 000000000..cf1e6b85f --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VNFType.java @@ -0,0 +1,173 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.rest.XacmlAdminAuthorization; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + + + +@Entity +@Table(name="VNFType") +@NamedQuery(name="VNFType.findAll", query="SELECT v FROM VNFType v ") +public class VNFType implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="vnf_type", nullable=false, unique=true) + @OrderBy("asc") + private String vnftype; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + private static Log LOGGER = LogFactory.getLog(VNFType.class); + + public VNFType() { + + } + + public String getVnftype() { + return vnftype; + } + + public void setVnftype(String vnftype) { + this.vnftype = vnftype; + } + + public VNFType(String string, String userid) { + this(domain); + } + + public VNFType(String domain) { + this.vnftype = domain; + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy =XacmlAdminAuthorization.getUserId();; + } catch (Exception e) { + LOGGER.error("Exception caused While adding Modified by Role"+e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "VNFType", "Exception caused While adding Modified by Role"); + } + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public Date getCreatedDate() { + return this.createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getModifiedDate() { + return this.modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VSCLAction.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VSCLAction.java new file mode 100644 index 000000000..5bfab1793 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VSCLAction.java @@ -0,0 +1,173 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.rest.XacmlAdminAuthorization; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + + +@Entity +@Table(name="VSCLAction") +@NamedQuery(name="VSCLAction.findAll", query="SELECT v FROM VSCLAction v ") +public class VSCLAction implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="vscl_action", nullable=false, unique=true) + @OrderBy("asc") + private String vsclaction; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Column(name="description", nullable=true, length=2048) + private String description; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + private static Log LOGGER = LogFactory.getLog(VSCLAction.class); + + public VSCLAction() { + + } + + public VSCLAction(String string, String userid) { + this(domain); + } + + public VSCLAction(String domain) { + this.vsclaction = domain; + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy =XacmlAdminAuthorization.getUserId();; + } catch (Exception e) { + LOGGER.error("Exception caused While adding Modified by Role"+e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "VSCLAction", "Exception caused While adding Modified by Role"); + } + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getVsclaction() { + return vsclaction; + } + + public void setVsclaction(String vsclaction) { + this.vsclaction = vsclaction; + } + + + public Date getCreatedDate() { + return this.createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getModifiedDate() { + return this.modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VarbindDictionary.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VarbindDictionary.java new file mode 100644 index 000000000..0ede025bd --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/VarbindDictionary.java @@ -0,0 +1,184 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; + +import java.io.Serializable; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.NamedQuery; +import javax.persistence.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.rest.XacmlAdminAuthorization; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + +@Entity +@Table(name="VarbindDictionary") +@NamedQuery(name = "VarbindDictionary.findAll", query = "Select v FROM VarbindDictionary v") +public class VarbindDictionary implements Serializable{ + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "Id") + private int id; + + @Column(name ="varbind_Name", nullable = false, unique = true) + @OrderBy("asc") + private String varbindName; + + @Column(name = "varbind_Description", nullable = true, length = 2048) + private String varbindDescription; + + @Column(name = "varbind_oid", nullable = false) + private String varbindOID; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="created_date", updatable=false) + private Date createdDate; + + @Temporal(TemporalType.TIMESTAMP) + @Column(name="modified_date", nullable=false) + private Date modifiedDate; + + @ManyToOne(optional = false) + @JoinColumn(name="created_by") + private UserInfo userCreatedBy; + + @ManyToOne(optional = false) + @JoinColumn(name="modified_by") + private UserInfo userModifiedBy; + + public UserInfo getUserCreatedBy() { + return userCreatedBy; + } + + public void setUserCreatedBy(UserInfo userCreatedBy) { + this.userCreatedBy = userCreatedBy; + } + + public UserInfo getUserModifiedBy() { + return userModifiedBy; + } + + public void setUserModifiedBy(UserInfo userModifiedBy) { + this.userModifiedBy = userModifiedBy; + } + + private static Log LOGGER = LogFactory.getLog(VarbindDictionary.class); + + public VarbindDictionary() { + + } + + public VarbindDictionary(String string, String userid) { + this(domain); + } + + public VarbindDictionary(String domain) { + this.varbindName = domain; + } + + @PrePersist + public void prePersist() { + Date date = new Date(); + this.createdDate = date; + this.modifiedDate = date; + } + + @PreUpdate + public void preUpdate() { + this.modifiedDate = new Date(); + try { + this.userModifiedBy =XacmlAdminAuthorization.getUserId();; + } catch (Exception e) { + LOGGER.error("Exception caused While adding Modified by Role"+e); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "VarbindDictionary", "Exception caused While adding Modified by Role"); + } + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getVarbindName() { + return varbindName; + } + + public void setVarbindName(String varbindName) { + this.varbindName = varbindName; + } + + public String getVarbindDescription() { + return varbindDescription; + } + + public void setVarbindDescription(String varbindDescription) { + this.varbindDescription = varbindDescription; + } + + public String getVarbindOID() { + return varbindOID; + } + + public void setVarbindOID(String varbindOID) { + this.varbindOID = varbindOID; + } + + public Date getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Date createdDate) { + this.createdDate = createdDate; + } + + public Date getModifiedDate() { + return modifiedDate; + } + + public void setModifiedDate(Date modifiedDate) { + this.modifiedDate = modifiedDate; + } + + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/WatchPolicyNotificationTable.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/WatchPolicyNotificationTable.java new file mode 100644 index 000000000..297c1f6df --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/WatchPolicyNotificationTable.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + * + * + * */ + +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.OrderBy; +import javax.persistence.Table; + +@Entity +@Table(name = "WatchPolicyNotificationTable") +@NamedQuery(name="WatchPolicyNotificationTable.findAll", query="SELECT e FROM WatchPolicyNotificationTable e ") +public class WatchPolicyNotificationTable implements Serializable{ + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="policyName", nullable=false, unique=true) + @OrderBy("asc") + private String policyName; + + @Column(name="loginIds", nullable=false, unique=true) + @OrderBy("asc") + private String loginIds; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getPolicyName() { + return policyName; + } + + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + + public String getLoginIds() { + return loginIds; + } + + public void setLoginIds(String loginIds) { + this.loginIds = loginIds; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Zone.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Zone.java new file mode 100644 index 000000000..eb53c42f1 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/Zone.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; +/* + */ +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.OrderBy; +import javax.persistence.PrePersist; +import javax.persistence.PreUpdate; +import javax.persistence.Table; + +@Entity +@Table(name="zone") +@NamedQuery(name="Zone.findAll", query="SELECT e FROM Zone e ") +public class Zone implements Serializable { + private static final long serialVersionUID = 1L; + + private static String domain; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name="id") + private int id; + + @Column(name="zonename", nullable=false) + @OrderBy("asc") + private String zoneName; + + @Column(name="zonevalue") + private String zoneValue; + + + public Zone() { + + } + public Zone(String string, String userid) { + this(domain); + + } + public Zone(String domain) { + + } + + @PrePersist + public void prePersist() { + + } + @PreUpdate + public void preUpdate() { + } + + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + public String getZoneName() { + return this.zoneName; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + + } + public String getZoneValue() { + return this.zoneValue; + } + + public void setZoneValue(String zoneValue) { + this.zoneValue = zoneValue; + } + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/package-info.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/package-info.java new file mode 100644 index 000000000..72a36f4f4 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/package-info.java @@ -0,0 +1,21 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.jpa; diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/LockdownListener.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/LockdownListener.java new file mode 100644 index 000000000..8e06656a3 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/LockdownListener.java @@ -0,0 +1,36 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.util; + +public interface LockdownListener { + /** + * lockdown has been set in database + */ + public void lockdownSet(); + + /** + * lockdown has been unset in the database + */ + public void lockdownUnset(); +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeObject.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeObject.java new file mode 100644 index 000000000..b5d359fd6 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeObject.java @@ -0,0 +1,109 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.util; + +import java.util.HashMap; +import java.util.Map; + +public class MSAttributeObject { + + private String className; + private HashMap attribute = new HashMap<>(); + private HashMap refAttribute = new HashMap<>(); + private HashMap subClass = new HashMap<>(); + private String dependency; + private HashMap enumType = new HashMap<>(); + private HashMap matchingSet = new HashMap<>(); + private boolean policyTempalate; + + public Map getRefAttribute() { + return refAttribute; + } + public void setRefAttribute(HashMap refAttribute) { + this.refAttribute = refAttribute; + } + public String getClassName() { + return className; + } + public void setClassName(String className) { + this.className = className; + } + public Map getAttribute() { + return attribute; + } + public void setAttribute(HashMap attribute) { + this.attribute = attribute; + } + public HashMap getEnumType() { + return enumType; + } + public void setEnumType(HashMap enumType) { + this.enumType = enumType; + } + public void addAttribute(String key, String value){ + this.attribute.put(key, value); + } + public void addRefAttribute(String key, String value){ + this.refAttribute.put(key, value); + } + public void addAllAttribute(Map map){ + this.attribute.putAll(map); + } + public void addAllRefAttribute(Map map){ + this.refAttribute.putAll(map); + } + public HashMap getSubClass() { + return subClass; + } + public void setSubClass(HashMap subClass) { + this.subClass = subClass; + } + public void addAllSubClass(HashMap subClass){ + this.subClass.putAll(subClass); + } + public String getDependency() { + return dependency; + } + public void setDependency(String dependency) { + this.dependency = dependency; + } + public void addSingleEnum(String key, String value){ + this.enumType.put(key, value); + } + public HashMap getMatchingSet() { + return matchingSet; + } + public void setMatchingSet(HashMap matchingSet) { + this.matchingSet = matchingSet; + } + public void addMatchingSet(String key, String value){ + this.matchingSet.put(key, value); + } + public void addMatchingSet(HashMap matchingSet){ + this.matchingSet.putAll(matchingSet); + } + public boolean isPolicyTempalate() { + return policyTempalate; + } + public void setPolicyTempalate(boolean policyTempalate) { + this.policyTempalate = policyTempalate; + } +} \ No newline at end of file diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeValue.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeValue.java new file mode 100644 index 000000000..23b5f8658 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSAttributeValue.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.util; + +public class MSAttributeValue{ + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + public Boolean getRequired() { + return required; + } + public void setRequired(Boolean required) { + this.required = required; + } + public Boolean getArrayValue() { + return arrayValue; + } + public void setArrayValue(Boolean arrayValue) { + this.arrayValue = arrayValue; + } + public String getDefaultValue() { + return defaultValue; + } + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + private String name; + private String type; + private Boolean required; + private Boolean arrayValue; + private String defaultValue; + +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSModelUtils.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSModelUtils.java new file mode 100644 index 000000000..fa2c51d18 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/MSModelUtils.java @@ -0,0 +1,701 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.util; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.emf.common.util.EList; +import org.eclipse.emf.common.util.EMap; +import org.eclipse.emf.common.util.Enumerator; +import org.eclipse.emf.common.util.TreeIterator; +import org.eclipse.emf.common.util.URI; +import org.eclipse.emf.ecore.EAnnotation; +import org.eclipse.emf.ecore.EClass; +import org.eclipse.emf.ecore.EClassifier; +import org.eclipse.emf.ecore.EEnum; +import org.eclipse.emf.ecore.EEnumLiteral; +import org.eclipse.emf.ecore.EObject; +import org.eclipse.emf.ecore.EPackage; +import org.eclipse.emf.ecore.EReference; +import org.eclipse.emf.ecore.EStructuralFeature; +import org.eclipse.emf.ecore.impl.EAttributeImpl; +import org.eclipse.emf.ecore.impl.EEnumImpl; +import org.eclipse.emf.ecore.resource.Resource; +import org.eclipse.emf.ecore.resource.ResourceSet; +import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl; +import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl; +import org.json.JSONObject; +import org.onap.policy.rest.XACMLRestProperties; + +import com.att.research.xacml.util.XACMLProperties; +import com.google.gson.Gson; + + +public class MSModelUtils { + + private static final Log logger = LogFactory.getLog(MSModelUtils.class); + + private HashMap classMap = new HashMap<>(); + private HashMap enumMap = new HashMap<>(); + private HashMap matchingClass = new HashMap<>(); + private String configuration = "configuration"; + private String dictionary = "dictionary"; + private String onap = ""; + private String policy = ""; + private String eProxyURI = "eProxyURI:"; + + public MSModelUtils(String onap, String policy){ + this.onap = onap; + this.policy = policy; + } + + private enum ANNOTATION_TYPE{ + MATCHING, VALIDATION, DICTIONARY + }; + + public enum MODEL_TYPE { + XMI + }; + + + public HashMap processEpackage(String file, MODEL_TYPE model){ + if (model == MODEL_TYPE.XMI ){ + processXMIEpackage(file); + } + return classMap; + + } + + private void processXMIEpackage(String xmiFile){ + EPackage root = getEpackage(xmiFile); + TreeIterator treeItr = root.eAllContents(); + String className = null; + String returnValue = null; + + // Pulling out dependency from file + while (treeItr.hasNext()) { + EObject obj = (EObject) treeItr.next(); + if (obj instanceof EClassifier) { + EClassifier eClassifier = (EClassifier) obj; + className = eClassifier.getName(); + + if (obj instanceof EEnum) { + enumMap.putAll(getEEnum(obj)); + }else if (obj instanceof EClass) { + String temp = getDependencyList(eClassifier, className).toString(); + returnValue = StringUtils.replaceEach(temp, new String[]{"[", "]"}, new String[]{"", ""}); + getAttributes(className, returnValue, root); + } + } + } + + if (!enumMap.isEmpty()){ + addEnumClassMap(); + } + if (!matchingClass.isEmpty()){ + CheckForMatchingClass(); + } + } + + private void CheckForMatchingClass() { + HashMap tempAttribute = new HashMap<>(); + + for (Entry set : matchingClass.entrySet()){ + String key = set.getKey(); + if (classMap.containsKey(key)){ + Map listAttributes = classMap.get(key).getAttribute(); + Map listRef = classMap.get(key).getRefAttribute(); + for ( Entry eSet : listAttributes.entrySet()){ + String key2 = eSet.getKey(); + tempAttribute.put(key2, "matching-true"); + } + for ( Entry eSet : listRef.entrySet()){ + String key3 = eSet.getKey(); + tempAttribute.put(key3, "matching-true"); + } + + } + UpdateMatching(tempAttribute, key); + } + + } + + + + private void UpdateMatching(HashMap tempAttribute, String key) { + Map newClass = null; + + newClass = classMap; + + for (Entry updateClass : newClass.entrySet()){ + HashMap valueMap = updateClass.getValue().getMatchingSet(); + String keymap = updateClass.getKey(); + if (valueMap.containsKey(key)){ + HashMap modifyMap = classMap.get(keymap).getMatchingSet(); + modifyMap.remove(key); + modifyMap.putAll(tempAttribute); + classMap.get(keymap).setMatchingSet(modifyMap); + } + + } + } + + private void addEnumClassMap() { + for (Entry value :classMap.entrySet()){ + value.getValue().setEnumType(enumMap); + } + } + + private EPackage getEpackage(String xmiFile) { + ResourceSet resSet = new ResourceSetImpl(); + Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE; + Map m = reg.getExtensionToFactoryMap(); + m.put("xmi", new XMIResourceFactoryImpl()); + Resource resource = resSet.getResource(URI.createFileURI(xmiFile), true); + try { + resource.load(Collections.EMPTY_MAP); + } catch (IOException e) { + logger.error("Error loading Encore Resource for new Model" + e); + } + + EPackage root = (EPackage) resource.getContents().get(0); + + return root; + } + + private HashMap getEEnum(EObject obj) { + List valueList = new ArrayList<>(); + HashMap returnMap = new HashMap<>(); + EEnum eenum = (EEnum)obj; + + String name = eenum.getName(); + for (EEnumLiteral eEnumLiteral : eenum.getELiterals()) + { + Enumerator instance = eEnumLiteral.getInstance(); + String value = instance.getLiteral(); + valueList.add(value); + } + returnMap.put(name, valueList.toString()); + return returnMap; + } + + public void getAttributes(String className, String dependency, EPackage root) { + List dpendList = new ArrayList<>(); + if (dependency!=null){ + dpendList = new ArrayList(Arrays.asList(dependency.split(","))); + } + MSAttributeObject msAttributeObject = new MSAttributeObject(); + msAttributeObject.setClassName(className); + String extendClass = getSubTypes(root, className); + HashMap returnRefList = getRefAttributeList(root, className, extendClass); + HashMap returnAttributeList = getAttributeList(root, className, extendClass); + HashMap returnSubList = getSubAttributeList(root, className, extendClass); + HashMap returnAnnotation = getAnnotation(root, className, extendClass); + msAttributeObject.setAttribute(returnAttributeList); + msAttributeObject.setRefAttribute(returnRefList); + msAttributeObject.setSubClass(returnSubList); + msAttributeObject.setDependency(dpendList.toString()); + msAttributeObject.addMatchingSet(returnAnnotation); + msAttributeObject.setPolicyTempalate(isPolicyTemplate(root, className)); + + this.classMap.put(className, msAttributeObject); + } + + private HashMap getAnnotation(EPackage root, String className, String extendClass) { + TreeIterator treeItr = root.eAllContents(); + boolean requiredAttribute = false; + boolean requiredMatchAttribute = false; + HashMap annotationSet = new HashMap<>(); + String matching = null; + String range = null; + String dictionary = null; + + // Pulling out dependency from file + while (treeItr.hasNext()) { + EObject obj = treeItr.next(); + if (obj instanceof EClassifier) { + requiredAttribute = isRequiredAttribute(obj, className ); + requiredMatchAttribute = isRequiredAttribute(obj, extendClass ); + } + + if (requiredAttribute){ + if (obj instanceof EStructuralFeature) { + EStructuralFeature eStrucClassifier = (EStructuralFeature) obj; + if (eStrucClassifier.getEAnnotations().size() != 0) { + matching = annotationValue(eStrucClassifier, ANNOTATION_TYPE.MATCHING, policy); + if (matching!=null){ + annotationSet.put(eStrucClassifier.getName(), matching); + } + range = annotationValue(eStrucClassifier, ANNOTATION_TYPE.VALIDATION, policy); + if (range!=null){ + annotationSet.put(eStrucClassifier.getName(), range); + } + dictionary = annotationValue(eStrucClassifier, ANNOTATION_TYPE.DICTIONARY, policy); + if (dictionary!=null){ + annotationSet.put(eStrucClassifier.getName(), dictionary); + } + } + } + } else if (requiredMatchAttribute){ + if (obj instanceof EStructuralFeature) { + EStructuralFeature eStrucClassifier = (EStructuralFeature) obj; + if (eStrucClassifier.getEAnnotations().size() != 0) { + matching = annotationValue(eStrucClassifier, ANNOTATION_TYPE.MATCHING, policy); + if (matching!=null){ + if (obj instanceof EReference){ + EClass refType = ((EReference) obj).getEReferenceType(); + annotationSet.put(refType.getName(), matching); + matchingClass.put(refType.getName(), matching); + }else{ + annotationSet.put(eStrucClassifier.getName(), matching); + } + } + } + } + } + } + return annotationSet; + } + + private HashMap getSubAttributeList(EPackage root, String className , String superClass) { + TreeIterator treeItr = root.eAllContents(); + boolean requiredAttribute = false; + HashMap subAttribute = new HashMap(); + int rollingCount = 0; + int processClass = 0; + boolean annotation = false; + + // Pulling out dependency from file + while (treeItr.hasNext() && rollingCount < 2) { + + EObject obj = treeItr.next(); + if (obj instanceof EClassifier) { + if (isRequiredAttribute(obj, className ) || isRequiredAttribute(obj, superClass )){ + requiredAttribute = true; + }else { + requiredAttribute = false; + } + if (requiredAttribute){ + processClass++; + } + rollingCount = rollingCount+processClass; + } + + if (requiredAttribute) { + if (obj instanceof EStructuralFeature) { + EStructuralFeature eStrucClassifier = (EStructuralFeature) obj; + if (eStrucClassifier.getEAnnotations().size() != 0) { + annotation = annotationTest(eStrucClassifier, configuration, onap); + if (annotation && obj instanceof EReference) { + EClass refType = ((EReference) obj).getEReferenceType(); + if(!refType.toString().contains(eProxyURI)){ + subAttribute.put(eStrucClassifier.getName(), refType.getName()); + } + } + } + } + } + } + return subAttribute; + } + + public String checkDefultValue(String defultValue) { + if (defultValue!=null){ + return ":defaultValue-"+ defultValue; + } + return ":defaultValue-NA"; + + } + + public String checkRequiredPattern(int upper, int lower) { + + String pattern = XACMLProperties.getProperty(XACMLRestProperties.PROP_XCORE_REQUIRED_PATTERN); + + if (pattern!=null){ + if (upper == Integer.parseInt(pattern.split(",")[1]) && lower==Integer.parseInt(pattern.split(",")[0])){ + return ":required-true"; + } + } + + return ":required-false"; + } + + public JSONObject buildJavaObject(HashMap map, String attributeType){ + + JSONObject returnValue = new JSONObject(map); + + return returnValue; + + } + + public HashMap getRefAttributeList(EPackage root, String className, String superClass){ + + TreeIterator treeItr = root.eAllContents(); + boolean requiredAttribute = false; + HashMap refAttribute = new HashMap<>(); + int rollingCount = 0; + int processClass = 0; + boolean annotation = false; + // Pulling out dependency from file + while (treeItr.hasNext()) { + EObject obj = treeItr.next(); + if (obj instanceof EClassifier) { + if (isRequiredAttribute(obj, className ) || isRequiredAttribute(obj, superClass )){ + requiredAttribute = true; + }else { + requiredAttribute = false; + } + if (requiredAttribute){ + processClass++; + } + rollingCount = rollingCount+processClass; + } + + if (requiredAttribute) { + if (obj instanceof EStructuralFeature) { + EStructuralFeature eStrucClassifier = (EStructuralFeature) obj; + if (eStrucClassifier.getEAnnotations().size() != 0) { + annotation = annotationTest(eStrucClassifier, configuration, onap); + if ( annotation && obj instanceof EReference) { + EClass refType = ((EReference) obj).getEReferenceType(); + if(refType.toString().contains(eProxyURI)){ + String one = refType.toString().split(eProxyURI)[1]; + String refValue = StringUtils.replaceEach(one.split("#")[1], new String[]{"//", ")"}, new String[]{"", ""}); + refAttribute.put(eStrucClassifier.getName(), refValue); + } else { + String array = arrayCheck(((EStructuralFeature) obj).getUpperBound()); + refAttribute.put(eStrucClassifier.getName(), refType.getName() + array); + } + } else if (annotation && obj instanceof EAttributeImpl){ + EClassifier refType = ((EAttributeImpl) obj).getEType(); + if (refType instanceof EEnumImpl){ + String array = arrayCheck(((EStructuralFeature) obj).getUpperBound()); + refAttribute.put(eStrucClassifier.getName(), refType.getName() + array); } + } + } + } + } + } + return refAttribute; + } + + private boolean annotationTest(EStructuralFeature eStrucClassifier, String annotation, String type) { + String annotationType = null; + EAnnotation eAnnotation = null; + String onapType = null; + String onapValue = null; + + EList value = eStrucClassifier.getEAnnotations(); + + for (int i = 0; i < value.size(); i++){ + annotationType = value.get(i).getSource(); + eAnnotation = eStrucClassifier.getEAnnotations().get(i); + onapType = eAnnotation.getDetails().get(0).getValue(); + onapValue = eAnnotation.getDetails().get(0).getKey(); + if (annotationType.contains(type) && onapType.contains(annotation)){ + return true; + } else if (annotationType.contains(type) && onapValue.contains(annotation)){ + return true; + } + } + + return false; + } + + + private String annotationValue(EStructuralFeature eStrucClassifier, ANNOTATION_TYPE annotation, String type) { + String annotationType = null; + EAnnotation eAnnotation = null; + String onapType = null; + String onapValue = null; + + EList value = eStrucClassifier.getEAnnotations(); + + for (int i = 0; i < value.size(); i++){ + annotationType = value.get(i).getSource(); + eAnnotation = eStrucClassifier.getEAnnotations().get(i); + onapType = eAnnotation.getDetails().get(0).getKey(); + if (annotationType.contains(type) && onapType.compareToIgnoreCase(annotation.toString())==0){ + onapValue = eAnnotation.getDetails().get(0).getValue(); + if (annotation == ANNOTATION_TYPE.VALIDATION){ + return onapValue; + } else { + return onapType + "-" + onapValue; + } + } + } + + return onapValue; + } + public boolean isRequiredAttribute(EObject obj, String className){ + EClassifier eClassifier = (EClassifier) obj; + String workingClass = eClassifier.getName(); + workingClass.trim(); + if (workingClass.equalsIgnoreCase(className)){ + return true; + } + + return false; + } + + private boolean isPolicyTemplate(EPackage root, String className){ + + for (EClassifier classifier : root.getEClassifiers()){ + if (classifier instanceof EClass) { + EClass eClass = (EClass)classifier; + if (eClass.getName().contentEquals(className)){ + EList value = eClass.getEAnnotations(); + for (EAnnotation workingValue : value){ + EMap keyMap = workingValue.getDetails(); + if (keyMap.containsKey("policyTemplate")){ + return true; + } + } + } + } + } + return false; + } + private String getSubTypes(EPackage root, String className) { + String returnSubTypes = null; + for (EClassifier classifier : root.getEClassifiers()){ + if (classifier instanceof EClass) { + EClass eClass = (EClass)classifier; + + for (EClass eSuperType : eClass.getEAllSuperTypes()) + { + if (eClass.getName().contentEquals(className)){ + returnSubTypes = eSuperType.getName(); + } + } + } + } + return returnSubTypes; + } + + public HashMap getAttributeList(EPackage root, String className, String superClass){ + + TreeIterator treeItr = root.eAllContents(); + boolean requiredAttribute = false; + HashMap refAttribute = new HashMap<>(); + boolean annotation = false; + boolean dictionaryTest = false; + String defaultValue = null; + String eType = null; + + // Pulling out dependency from file + while (treeItr.hasNext()) { + EObject obj = treeItr.next(); + if (obj instanceof EClassifier) { + if (isRequiredAttribute(obj, className ) || isRequiredAttribute(obj, superClass )){ + requiredAttribute = true; + }else { + requiredAttribute = false; + } + + } + + if (requiredAttribute){ + if (obj instanceof EStructuralFeature) { + EStructuralFeature eStrucClassifier = (EStructuralFeature) obj; + if (eStrucClassifier.getEAnnotations().size() != 0) { + annotation = annotationTest(eStrucClassifier, configuration, onap); + dictionaryTest = annotationTest(eStrucClassifier, dictionary, policy); + EClassifier refType = ((EStructuralFeature) obj).getEType(); + if (annotation && !(obj instanceof EReference) && !(refType instanceof EEnumImpl)) { + String name = eStrucClassifier.getName(); + if (dictionaryTest){ + eType = annotationValue(eStrucClassifier, ANNOTATION_TYPE.DICTIONARY, policy); + }else { + eType = eStrucClassifier.getEType().getInstanceClassName(); + } + defaultValue = checkDefultValue(((EStructuralFeature) obj).getDefaultValueLiteral()); + + String array = arrayCheck(((EStructuralFeature) obj).getUpperBound()); + String required = checkRequiredPattern(((EStructuralFeature) obj).getUpperBound(), ((EStructuralFeature) obj).getLowerBound()); + String attributeValue = eType + defaultValue + required + array; + refAttribute.put(name, attributeValue); + } + } + } + } + } + return refAttribute; + + } + + public String arrayCheck(int upperBound) { + + if (upperBound == -1){ + return ":MANY-true"; + } + + return ":MANY-false"; + } + + public List getDependencyList(EClassifier eClassifier, String className){ + List returnValue = new ArrayList<>();; + EList somelist = ((EClass) eClassifier).getEAllSuperTypes(); + if (somelist.isEmpty()){ + return returnValue; + } + for(EClass depend: somelist){ + if (depend.toString().contains(eProxyURI)){ + String one = depend.toString().split(eProxyURI)[1]; + String value = StringUtils.replaceEach(one.split("#")[1], new String[]{"//", ")"}, new String[]{"", ""}); + returnValue.add(value); + } + } + + return returnValue; + } + + public Map buildSubList(HashMap subClassAttributes, HashMap classMap, String className){ + Map missingValues = new HashMap<>(); + Map workingMap = new HashMap<>(); + boolean enumType; + + for ( Entry map : classMap.get(className).getRefAttribute().entrySet()){ + String value = map.getValue().split(":")[0]; + if (value!=null){ + classMap.get(className).getEnumType(); + enumType = classMap.get(className).getEnumType().containsKey(value); + if (!enumType){ + workingMap = classMap.get(value).getRefAttribute(); + for ( Entry subMab : workingMap.entrySet()){ + String value2 = subMab.getValue().split(":")[0]; + if (!subClassAttributes.containsValue(value2)){ + missingValues.put(subMab.getKey(), subMab.getValue()); + } + } + + } + } + } + + return missingValues; + } + + public Map> recursiveReference(HashMap classMap, String className){ + + Map> returnObject = new HashMap<>(); + HashMap returnClass = getRefclass(classMap, className); + returnObject.put(className, returnClass); + for (Entry reAttribute :returnClass.entrySet()){ + if (reAttribute.getValue().split(":")[1].contains("MANY")){ + if (classMap.get(reAttribute.getValue().split(":")[0]) != null){ + returnObject.putAll(recursiveReference(classMap, reAttribute.getValue().split(":")[0])); + } + } + + } + + return returnObject; + + } + + public String createJson(HashMap subClassAttributes, HashMap classMap, String className) { + boolean enumType; + Map> myObject = new HashMap<>(); + for ( Entry map : classMap.get(className).getRefAttribute().entrySet()){ + String value = map.getValue().split(":")[0]; + if (value!=null){ + enumType = classMap.get(className).getEnumType().containsKey(value); + if (!enumType){ + if (map.getValue().split(":")[1].contains("MANY")){ + Map> testRecursive = recursiveReference(classMap, map.getValue().split(":")[0] ); + myObject.putAll(testRecursive); + } + } + } + } + + Gson gson = new Gson(); + String json = gson.toJson(myObject); + + return json; + } + + public HashMap getRefclass(HashMap classMap, String className){ + HashMap missingValues = new HashMap<>(); + + if (classMap.get(className).getAttribute()!=null || !classMap.get(className).getAttribute().isEmpty()){ + missingValues.putAll(classMap.get(className).getAttribute()); + } + + if (classMap.get(className).getRefAttribute()!=null || !classMap.get(className).getRefAttribute().isEmpty()){ + missingValues.putAll(classMap.get(className).getRefAttribute()); + } + + return missingValues; + } + + public String createSubAttributes(ArrayList dependency, HashMap classMap, String modelName) { + + HashMap workingMap = new HashMap<>(); + MSAttributeObject tempObject = new MSAttributeObject(); + if (dependency!=null){ + if (dependency.size()==0){ + return "{}"; + } + dependency.add(modelName); + for (String element: dependency){ + tempObject = classMap.get(element); + if (tempObject!=null){ + workingMap.putAll(classMap.get(element).getSubClass()); + } + } + } + + String returnValue = createJson(workingMap, classMap, modelName); + return returnValue; + } + + public ArrayList getFullDependencyList(ArrayList dependency, HashMap classMap) { + ArrayList returnList = new ArrayList<>(); + ArrayList workingList = new ArrayList<>(); + returnList.addAll(dependency); + for (String element : dependency ){ + if (classMap.containsKey(element)){ + MSAttributeObject value = classMap.get(element); + String rawValue = StringUtils.replaceEach(value.getDependency(), new String[]{"[", "]"}, new String[]{"", ""}); + workingList = new ArrayList(Arrays.asList(rawValue.split(","))); + for(String depend : workingList){ + if (!returnList.contains(depend) && !depend.isEmpty()){ + returnList.add(depend.trim()); + } + } + } + } + + return returnList; + } +} diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/Webapps.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/Webapps.java new file mode 100644 index 000000000..908078f73 --- /dev/null +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/Webapps.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest.util; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.rest.XACMLRestProperties; + +import org.onap.policy.xacml.api.XACMLErrorConstants; +import com.att.research.xacml.util.XACMLProperties; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + +public class Webapps { + private static String actionHome = null; + private static String configHome = null; + private static Log logger = LogFactory.getLog(Webapps.class); + + private Webapps() { + } + + public static String getConfigHome(){ + try { + loadWebapps(); + } catch (Exception e) { + logger.error("Exception Occured while loading webapps"+e); + return null; + } + return configHome; + } + + public static String getActionHome(){ + try { + loadWebapps(); + } catch (Exception e) { + logger.error("Exception Occured while loading webapps"+e); + return null; + } + return actionHome; + } + + private static void loadWebapps() throws Exception{ + String errorMessageName = "Invalid Webapps Path Location property :"; + if(actionHome == null || configHome == null){ + Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); + //Sanity Check + if (webappsPath == null) { + logger.error(errorMessageName + XACMLRestProperties.PROP_PAP_WEBAPPS); + PolicyLogger.error(errorMessageName + XACMLRestProperties.PROP_PAP_WEBAPPS); + throw new Exception(errorMessageName + XACMLRestProperties.PROP_PAP_WEBAPPS); + } + Path webappsPathConfig; + Path webappsPathAction; + if(webappsPath.toString().contains("\\")){ + webappsPathConfig = Paths.get(webappsPath.toString()+"\\Config"); + webappsPathAction = Paths.get(webappsPath.toString()+"\\Action"); + }else{ + webappsPathConfig = Paths.get(webappsPath.toString()+"/Config"); + webappsPathAction = Paths.get(webappsPath.toString()+"/Action"); + } + + checkConfigActionHomeExists(webappsPathConfig, webappsPathAction); + + actionHome = webappsPathAction.toString(); + configHome = webappsPathConfig.toString(); + } + } + + private static void checkConfigActionHomeExists(Path webappsPathConfig, Path webappsPathAction){ + if (!webappsPathConfig.toFile().exists()){ + try { + Files.createDirectories(webappsPathConfig); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: " + + webappsPathConfig.toAbsolutePath().toString(), e); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Webapps", "Failed to create config directory"); + } + } + + if (!webappsPathAction.toFile().exists()){ + try { + Files.createDirectories(webappsPathAction); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create config directory: " + + webappsPathAction.toAbsolutePath().toString(), e); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Webapps", "Failed to create config directory"); + } + } + } + +} diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/XACMLRestTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/XACMLRestTest.java new file mode 100644 index 000000000..3de436481 --- /dev/null +++ b/ONAP-REST/src/test/java/org/onap/policy/rest/XACMLRestTest.java @@ -0,0 +1,107 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-REST + * ================================================================================ + * 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.rest; + +/*import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.Random; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletInputStream; +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import junit.framework.TestCase; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockServletConfig; + +import com.att.research.xacml.util.XACMLProperties; +import com.mockrunner.mock.web.MockServletInputStream; + +public class XACMLRestTest extends TestCase{ + private static Log logger = LogFactory.getLog(XACMLRestTest.class); + + private List headers = new ArrayList(); + + private HttpServletRequest httpServletRequest; + private HttpServletResponse httpServletResponse; + private ServletOutputStream mockOutput; + private ServletInputStream mockInput; + private ServletConfig servletConfig; + + + @Before + public void setUp(){ + httpServletRequest = Mockito.mock(HttpServletRequest.class); + Mockito.when(httpServletRequest.getMethod()).thenReturn("POST"); + Mockito.when(httpServletRequest.getHeaderNames()).thenReturn(Collections.enumeration(headers)); + Mockito.when(httpServletRequest.getAttributeNames()).thenReturn(Collections.enumeration(headers)); + + mockOutput = Mockito.mock(ServletOutputStream.class); + + httpServletResponse = Mockito.mock(MockHttpServletResponse.class); + + try { + Mockito.when(httpServletResponse.getOutputStream()).thenReturn(mockOutput); + } catch (IOException e) { + fail(); + } + + servletConfig = Mockito.mock(MockServletConfig.class); + Mockito.when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers)); + //pdpServlet = new XACMLPdpServlet(); + + Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("xacml.pdp.properties"); + + System.setProperty("xacml.properties", "xacml.pdp.properties"); + System.setProperty("xacml.rest.pdp.config", "config_testing"); + System.setProperty("xacml.rest.pep.idfile", "testclient.properties"); + System.setProperty("xacml.rest.pdp.webapps", "/webapps"); + System.setProperty("xacml.rootPolicies", "test_PolicyEngine.xml"); + System.setProperty("xacml.referencedPolicies", "test_PolicyEngine.xml"); + System.setProperty("test_PolicyEngine.xml.file", "config_testing\\test_PolicyEngine.xml"); + System.setProperty("xacml.rest.pdp.register", "false"); + } + + @Test + public void testDummy(){ + logger.info("XACMLRestTest - testInit"); + try { + assertTrue(true); + } catch (Exception e) { + fail(); + + } + + } +} +*/ \ No newline at end of file diff --git a/ECOMP-SDK-APP/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch b/ONAP-SDK-APP/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch similarity index 100% rename from ECOMP-SDK-APP/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch rename to ONAP-SDK-APP/.externalToolBuilders/org.eclipse.wst.jsdt.core.javascriptValidator.launch diff --git a/ECOMP-SDK-APP/.gitignore b/ONAP-SDK-APP/.gitignore similarity index 100% rename from ECOMP-SDK-APP/.gitignore rename to ONAP-SDK-APP/.gitignore diff --git a/ECOMP-SDK-APP/JSONConfig.json b/ONAP-SDK-APP/JSONConfig.json similarity index 100% rename from ECOMP-SDK-APP/JSONConfig.json rename to ONAP-SDK-APP/JSONConfig.json diff --git a/ONAP-SDK-APP/README.md b/ONAP-SDK-APP/README.md new file mode 100644 index 000000000..043a967fd --- /dev/null +++ b/ONAP-SDK-APP/README.md @@ -0,0 +1,68 @@ +Onap SDK Web App +================= + +This is a Maven project with the ONAP SDK web application for public release, containing files specific to requirements of the open-source version. This project uses the Maven war plugin to copy in ("overlay") the contents of the ONAP SDK web application overlay files distribution at package time. + +Use Apache Maven to build, package and deploy this webapp to a web container like Apache Tomcat. Eclipse users must install the M2E-WTP connector, see https://www.eclipse.org/m2e-wtp/ +Release Notes + +All of the release notes in the epsdk-app-common and epsdk-app-overlay areas apply here! + +Build 1.2.8, ?? ??? 2017 + + put new entries here * + +Build 1.2.7, 10 Apr 2017 + + Drop shared context property + +Build 1.2.6, 23 Mar 2017 + + DE270905 Removed total page/current page text boxes from bottom of Profile Search page + DE272154 SDK-App: self profile page, changes on drop downs not saved (120272) + DE273128 Revise left menu to have unique IDs + DE271378 fixed Camunda Page link in fn_menu; additional links were updated: Notebook + US847688 Abstraction of support page content for AT&T vs Open Source in SQL Scripts + Add sample defs/definitions.xml file for partner applications to configure jsp pages + Downgrade angularJS from 1.5.0 to 1.4.8 + +Build 1.2.5, 16 Mar 2017 + + DE272709 Update icon names from DS1 to DS2 in database load script + Upgrade to EPSDK libraries version 1.2.5 + +Build 1.2.4, 10 Mar 2017 + + DE272042 Add missing includes so left menu appears on collaborate and notebook pages + DE272193 Fix class/icon name to restore role icon on Self Profile page + Restore spinners by changing class name from icon-spinner to icon-primary-spinner + DE272202 updated ionicon.css for open source version of report search page + Removed unused js files from samplePage.html in epsdk-app-os + Upgrade to EPSDK libraries version 1.2.4 + +Build 1.2.3, 8 Mar 2017 + + DE271038 Remove references to famous telecommunications company from system.properties + Upgrade to EPSDK libraries version 1.2.3 + +Build 1.2.2, 6 Mar 2017 + + DE270658 EPSDK-app-os header is covering part of left menu. + DE271510 Pages not loading in IE and FF properly. Drop page-resource-ds2.js; load scripts in HTML directly + Remove references to famous telecommunications company hosts from fusion.properties, portal.properties + Upgrade to EPSDK libraries version 1.2.2 + +Build 1.2.1, 2 Mar 2017 + + DE269231 Separated footer files on OS module displaying black footer with no content + US847688 Split database scripts; include full set in distributions + US847706 Refactored AdminAuthExtension to implement interface expected in OnboardingApiServiceImpl + Added class conf/HibernateMappingLocations - moved out of common to apps + Added file logback.xml to src/main/resources with appropriate logger names + Extend HibernateMappingLocations with method that returns list of package names to scan + Remove references to famous telecommunications company hosts from system.properties file + Upgrade to EPSDK libraries version 1.2.1 + +Build 1.2.0, 9 Feb 2017 + + Initial release diff --git a/ECOMP-SDK-APP/distribution.xml b/ONAP-SDK-APP/distribution.xml similarity index 100% rename from ECOMP-SDK-APP/distribution.xml rename to ONAP-SDK-APP/distribution.xml diff --git a/ONAP-SDK-APP/policyLogger.properties b/ONAP-SDK-APP/policyLogger.properties new file mode 100644 index 000000000..bbb0ecf4e --- /dev/null +++ b/ONAP-SDK-APP/policyLogger.properties @@ -0,0 +1,44 @@ +### +# ============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========================================================= +### + +################################### Set concurrentHashMap and timer info ####################### +#Timer initial delay and the delay between in milliseconds before task is to be execute. +timer.delay.time=1000 +#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. +check.interval= 30000 +#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. +event.expired.time=86400 +#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed +#to remove all expired records from this concurrentHashMap. +concurrentHashMap.limit=5000 +#Size of the concurrentHashMap - when its size drops to this point, stop the Timer +stop.check.point=2500 +################################### Set logging format ############################################# +# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println +logger.type=EELF +#################################### Set level for EELF or SYSTEMOUT logging ################################## +# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all +debugLogger.level=INFO +# Set level for metrics file. Set OFF to disable; set ON to enable +metricsLogger.level=ON +# Set level for error file. Set OFF to disable; set ON to enable +error.level=ON +# Set level for audit file. Set OFF to disable; set ON to enable +audit.level=ON diff --git a/ONAP-SDK-APP/pom.xml b/ONAP-SDK-APP/pom.xml new file mode 100644 index 000000000..5a2cab5b7 --- /dev/null +++ b/ONAP-SDK-APP/pom.xml @@ -0,0 +1,267 @@ + + + + 4.0.0 + + org.onap.policy.engine + PolicyEngineSuite + 1.1.0-SNAPSHOT + + ONAP-SDK-APP + war + + + UTF-8 + 1.1.0 + 4.2.0.RELEASE + 4.3.11.Final + + true + + 2.6.0 + + + + + doclint-java8-disable + + [1.8,) + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 + + -Xdoclint:none + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.2 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.19.1 + + ${skiptests} + + **/Test*.java + **/*Test.java + **/*TestCase.java + + + ${basedir}/war + + + classpath: + + + + + + org.apache.maven.plugins + maven-war-plugin + 2.1 + + true + + + true + + + ${project.version} + ${maven.build.timestamp} + + + + + org.openecomp.ecompsdkos + epsdk-app-overlay + + + org.onap.policy.engine + POLICY-SDK-APP + + + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.0.0 + + ${skipassembly} + + ${basedir}/distribution.xml + + + + + make-assembly + package + + single + + + + + + + + + + org.onap.policy.engine + POLICY-SDK-APP + ${project.version} + war + + + org.openecomp.ecompsdkos + epsdk-core + + + + + org.onap.policy.engine + POLICY-SDK-APP + ${project.version} + jar + classes + + + org.openecomp.ecompsdkos + epsdk-core + + + + + org.onap.policy.engine + PolicyEngineUtils + ${project.version} + + + com.att.aft + dme2 + + + + + + org.openecomp.ecompsdkos + epsdk-app-overlay + ${epsdk.version} + war + + + org.openecomp.ecompsdkos + epsdk-app-common + ${epsdk.version} + jar + + + + org.openecomp.ecompsdkos + epsdk-core + ${epsdk.version} + + + org.openecomp.ecompsdkos + epsdk-analytics + ${epsdk.version} + + + com.oracle + ojdbc6 + + + + + org.openecomp.ecompsdkos + epsdk-workflow + ${epsdk.version} + + + com.att.eelf + eelf-core + 0.0.1 + + + + org.slf4j + jcl-over-slf4j + 1.7.12 + + + com.mchange + c3p0 + 0.9.5.2 + + + + org.mariadb.jdbc + mariadb-java-client + 1.2.3 + + + commons-dbcp + commons-dbcp + 1.4 + + + + org.quartz-scheduler + quartz + 2.2.1 + + + + c3p0 + c3p0 + + + + + javax.servlet + javax.servlet-api + 3.1.0 + + + junit + junit + 4.12 + + + diff --git a/ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java new file mode 100644 index 000000000..15a6c765e --- /dev/null +++ b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java @@ -0,0 +1,161 @@ +/*- + * ================================================================================ + * ONAP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.portalapp.conf; + +import java.util.ArrayList; +import java.util.List; + +import org.onap.portalapp.login.LoginStrategyImpl; +import org.onap.portalapp.scheduler.RegistryAdapter; +import org.openecomp.portalsdk.core.auth.LoginStrategy; +import org.openecomp.portalsdk.core.conf.AppConfig; +import org.openecomp.portalsdk.core.conf.Configurable; +import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; +import org.openecomp.portalsdk.core.service.DataAccessService; +import org.openecomp.portalsdk.core.util.CacheManager; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import org.springframework.context.annotation.Profile; +import org.springframework.context.annotation.PropertySource; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; +import org.springframework.web.servlet.ViewResolver; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; + +/** + * ONAP Portal SDK sample application. ONAP Portal SDK core AppConfig class to + * reuse interceptors, view resolvers and other features defined there. + */ +@Configuration +@EnableWebMvc +@ComponentScan(basePackages = "org.onap") +@PropertySource(value = { "${container.classpath:}/WEB-INF/conf/app/test.properties" }, ignoreResourceNotFound = true) +@Profile("src") +@EnableAsync +@EnableScheduling +public class ExternalAppConfig extends AppConfig implements Configurable { + + private RegistryAdapter schedulerRegistryAdapter; + + @Configuration + @Import(SystemProperties.class) + static class InnerConfiguration { + } + + /** + * @see org.openecomp.portalsdk.core.conf.AppConfig#viewResolver() + */ + public ViewResolver viewResolver() { + return super.viewResolver(); + } + + /** + * @see org.openecomp.portalsdk.core.conf.AppConfig#addResourceHandlers(ResourceHandlerRegistry) + * + * @param registry + */ + public void addResourceHandlers(ResourceHandlerRegistry registry) { + super.addResourceHandlers(registry); + } + + /** + * @see org.openecomp.portalsdk.core.conf.AppConfig#dataAccessService() + */ + public DataAccessService dataAccessService() { + // Echo the JDBC URL to assist developers when starting the app. + System.out.println("ExternalAppConfig: " + SystemProperties.DB_CONNECTIONURL + " is " + + SystemProperties.getProperty(SystemProperties.DB_CONNECTIONURL)); + return super.dataAccessService(); + } + + /** + * Creates a new list with a single entry that is the external app + * definitions.xml path. + * + * @return List of String, size 1 + */ + public List addTileDefinitions() { + List definitions = new ArrayList<>(); + definitions.add("/WEB-INF/defs/definitions.xml"); + return definitions; + } + + /** + * Adds request interceptors to the specified registry by calling + * {@link AppConfig#addInterceptors(InterceptorRegistry)}, but excludes + * certain paths from the session timeout interceptor. + */ + @Override + public void addInterceptors(InterceptorRegistry registry) { + super.setExcludeUrlPathsForSessionTimeout("/login_external", "*/login_external.htm", "login", "/login.htm", + "/api*", "/single_signon.htm", "/single_signon"); + super.addInterceptors(registry); + } + + /** + * Creates and returns a new instance of a {@link CacheManager} class. + * + * @return New instance of {@link CacheManager} + */ + @Bean + public AbstractCacheManager cacheManager() { + return new CacheManager(); + } + + /** + * Creates and returns a new instance of a {@link SchedulerFactoryBean} and + * populates it with triggers. + * + * @return New instance of {@link SchedulerFactoryBean} + * @throws Exception + */ + // @Bean // ANNOTATION COMMENTED OUT + // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION + public SchedulerFactoryBean schedulerFactoryBean() throws Exception { + SchedulerFactoryBean scheduler = new SchedulerFactoryBean(); + scheduler.setTriggers(schedulerRegistryAdapter.getTriggers()); + scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties")); + scheduler.setDataSource(dataSource()); + return scheduler; + } + + /** + * Sets the scheduler registry adapter. + * + * @param schedulerRegistryAdapter + */ + @Autowired + public void setSchedulerRegistryAdapter(final RegistryAdapter schedulerRegistryAdapter) { + this.schedulerRegistryAdapter = schedulerRegistryAdapter; + } + + @Bean + public LoginStrategy loginStrategy() { + + return new LoginStrategyImpl(); + } +} diff --git a/ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java new file mode 100644 index 000000000..a77c781ff --- /dev/null +++ b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/ExternalAppInitializer.java @@ -0,0 +1,47 @@ +/*- + * ================================================================================ + * ONAP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.portalapp.conf; + +import org.openecomp.portalsdk.core.conf.AppInitializer; + +public class ExternalAppInitializer extends AppInitializer { + + @Override + protected Class[] getRootConfigClasses() { + return super.getRootConfigClasses(); + } + + @Override + protected Class[] getServletConfigClasses() { + Class appConfigClass = ExternalAppConfig.class; + // Show something on stdout to indicate the app is starting. + System.out.println("ExternalAppInitializer: servlet configuration class is " + appConfigClass.getName()); + return new Class[] { appConfigClass }; + } + + /* + * URL request will direct to the Spring dispatcher for processing + */ + @Override + protected String[] getServletMappings() { + return super.getServletMappings(); + } + +} diff --git a/ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/HibernateMappingLocations.java b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/HibernateMappingLocations.java new file mode 100644 index 000000000..ee73a5a98 --- /dev/null +++ b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/HibernateMappingLocations.java @@ -0,0 +1,57 @@ +/*- + * ================================================================================ + * ONAP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.portalapp.conf; + +import org.springframework.context.annotation.Profile; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.stereotype.Component; + +import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable; + +@Component +@Profile("src") +public class HibernateMappingLocations implements HibernateMappingLocatable { + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalsdk.core.conf.HibernateMappingLocatable# + * getMappingLocations() + */ + @Override + public Resource[] getMappingLocations() { + return new Resource[] { new ClassPathResource("../fusion/orm/Fusion.hbm.xml"), + new ClassPathResource("../fusion/orm/Workflow.hbm.xml"), + new ClassPathResource("../fusion/orm/RNoteBookIntegration.hbm.xml") }; + } + + /* + * (non-Javadoc) + * + * @see org.openecomp.portalsdk.core.conf.HibernateMappingLocatable# + * getPackagesToScan() + */ + @Override + public String[] getPackagesToScan() { + return new String[] { "org.onap" }; + } + +} diff --git a/ONAP-SDK-APP/src/main/java/org/onap/portalapp/lm/FusionLicenseManagerImpl.java b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/lm/FusionLicenseManagerImpl.java new file mode 100644 index 000000000..5028162b5 --- /dev/null +++ b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/lm/FusionLicenseManagerImpl.java @@ -0,0 +1,69 @@ +package org.onap.portalapp.lm; + +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletContext; + +import org.openecomp.portalsdk.core.lm.FusionLicenseManager; +import org.springframework.stereotype.Component; + +/* + * Please note that this class is not being used; its a dummy stub to have a qualifying bean for the interface. + */ + +@Component +public class FusionLicenseManagerImpl implements FusionLicenseManager { + + @Override + public void initKeyStoreParam() { + + } + + @Override + public void initCipherParam() { + + } + + @Override + public void initLicenseParam() { + + } + + @Override + public void doInitWork() { + + } + + @Override + public int installLicense() { + return 0; + } + + @Override + public synchronized int verifyLicense(ServletContext context) { + return 0; + } + + @Override + public void generateLicense(Map clientInfoMap, List ipAddressList) throws Exception { + + } + + @Override + public String nvl(String s) { + return null; + } + + @Override + public Date getExpiredDate() { + return null; + } + + @Override + public void setExpiredDate(Date expiredDate) { + + } + +} diff --git a/ONAP-SDK-APP/src/main/java/org/onap/portalapp/lm/LicenseableClassImpl.java b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/lm/LicenseableClassImpl.java new file mode 100644 index 000000000..d3b08e242 --- /dev/null +++ b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/lm/LicenseableClassImpl.java @@ -0,0 +1,62 @@ +/*- + * ================================================================================ + * onap Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.portalapp.lm; + +import java.io.FileNotFoundException; +import java.io.InputStream; + +import org.openecomp.portalsdk.core.lm.LicenseableClass; + +/* + * Please note that this class is not being used; its a dummy stub to have a qualifying bean for the interface. + */ + +public class LicenseableClassImpl implements LicenseableClass { + + public String getApplicationName() { + return ""; + } + + public InputStream getPublicKeystoreAsInputStream() throws FileNotFoundException { + return null; + } + + public String getAlias() { + return ""; + } + + public String getKeyPasswd() { + return ""; + } + + public String getPublicKeystorePassword() { + return ""; + } + + public String getCipherParamPassword() { + return ""; + } + + @SuppressWarnings("rawtypes") + public Class getClassToLicense() { + return this.getClass(); + } +} + diff --git a/ONAP-SDK-APP/src/main/java/org/onap/portalapp/login/LoginStrategyImpl.java b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/login/LoginStrategyImpl.java new file mode 100644 index 000000000..dca71ae5f --- /dev/null +++ b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/login/LoginStrategyImpl.java @@ -0,0 +1,73 @@ +package org.onap.portalapp.login; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.openecomp.portalsdk.core.auth.LoginStrategy; +import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; +import org.openecomp.portalsdk.core.onboarding.util.CipherUtil; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants; +import org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties; +import org.springframework.web.servlet.ModelAndView; + +public class LoginStrategyImpl extends LoginStrategy { + + private static final Logger LOGGER = FlexLogger.getLogger(LoginStrategyImpl.class); + + @Override + public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response) throws Exception { + //'login' for opensource is same as 'external' login. + return doExternalLogin(request, response); + } + + @Override + public String getUserId(HttpServletRequest request) throws PortalAPIException { + // Check ONAP Portal cookie + if (!isLoginCookieExist(request)) + return null; + + String userid = null; + try { + userid = getUserIdFromCookie(request); + } catch (Exception e) { + LOGGER.error("Exception Occured"+e); + } + return userid; + } + + private static String getUserIdFromCookie(HttpServletRequest request) throws Exception { + String userId = ""; + Cookie[] cookies = request.getCookies(); + Cookie userIdcookie = null; + if (cookies != null) + for (Cookie cookie : cookies) + if (cookie.getName().equals(USER_ID)) + userIdcookie = cookie; + if(userIdcookie!=null){ + userId = CipherUtil.decrypt(userIdcookie.getValue(), + PortalApiProperties.getProperty(PortalApiConstants.Decryption_Key)); + } + return userId; + + } + + private static boolean isLoginCookieExist(HttpServletRequest request) { + Cookie ep = getCookie(request, EP_SERVICE); + return (ep != null); + } + + private static Cookie getCookie(HttpServletRequest request, String cookieName) { + Cookie[] cookies = request.getCookies(); + if (cookies != null) + for (Cookie cookie : cookies) + if (cookie.getName().equals(cookieName)) + return cookie; + + return null; + } + + +} diff --git a/ONAP-SDK-APP/src/main/java/org/onap/portalapp/scheduler/Register.java b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/scheduler/Register.java new file mode 100644 index 000000000..b33707f2a --- /dev/null +++ b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/scheduler/Register.java @@ -0,0 +1,72 @@ +/*- + * ================================================================================ + * ONAP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.portalapp.scheduler; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.portalapp.scheduler.LogRegistry; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.openecomp.portalsdk.core.scheduler.Registerable; +import org.openecomp.portalsdk.core.util.SystemProperties; +import org.quartz.Trigger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.DependsOn; +import org.springframework.stereotype.Component; + +@Component +@DependsOn({ "logRegistry", "systemProperties" }) +public class Register implements Registerable { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(Register.class); + + private List scheduleTriggers = new ArrayList<>(); + Trigger trigger[] = new Trigger[1]; + + @Autowired + private LogRegistry logRegistry; + + @Override + public Trigger[] getTriggers() { + return getScheduleTriggers().toArray(trigger); + } + + @Override + public void registerTriggers() { + // if the property value is not available; the cron will not be added + // and can be ignored. its safe to ignore the exceptions + try { + if (SystemProperties.getProperty(SystemProperties.LOG_CRON) != null) + getScheduleTriggers().add(logRegistry.getTrigger()); + } catch (IllegalStateException ies) { + logger.info(EELFLoggerDelegate.debugLogger, ("Log Cron not available") + ies); + } + + } + + public List getScheduleTriggers() { + return scheduleTriggers; + } + + public void setScheduleTriggers(List scheduleTriggers) { + this.scheduleTriggers = scheduleTriggers; + } + +} diff --git a/ONAP-SDK-APP/src/main/java/org/onap/portalapp/scheduler/RegistryAdapter.java b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/scheduler/RegistryAdapter.java new file mode 100644 index 000000000..40069cf77 --- /dev/null +++ b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/scheduler/RegistryAdapter.java @@ -0,0 +1,92 @@ +/*- + * ================================================================================ + * ONAP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.portalapp.scheduler; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.openecomp.portalsdk.core.scheduler.Registerable; +import org.openecomp.portalsdk.workflow.services.WorkflowScheduleService; +import org.quartz.Trigger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; +import org.springframework.stereotype.Component; + +@Component +public class RegistryAdapter { + + @Autowired + private Registerable registry; + + @Autowired + private WorkflowScheduleService workflowScheduleService; + + private SchedulerFactoryBean schedulerBean; + + Trigger trigger[] = new Trigger[1]; + + public Trigger[] getTriggers() { + + registry.registerTriggers(); + + List allTriggers = new ArrayList<>(); + + List coreTriggers = addCoreTriggers(); + final Trigger[] extTriggerArray = registry.getTriggers(); + + allTriggers.addAll(Arrays.asList(extTriggerArray)); + allTriggers.addAll(coreTriggers); + + return allTriggers.toArray(trigger); + } + + public List addCoreTriggers() { + // On startup of the application after crash recovery, invoke workflow + // schedule trigger + List triggers = getWorkflowScheduleService().triggerWorkflowScheduling(); + return triggers; + } + + public void setSchedulerBean(SchedulerFactoryBean _schedulerBean) { + schedulerBean = _schedulerBean; + } + + public SchedulerFactoryBean getSchedulerBean() { + return schedulerBean; + } + + public Registerable getRegistry() { + return registry; + } + + public void setRegistry(Registerable registry) { + this.registry = registry; + } + + public WorkflowScheduleService getWorkflowScheduleService() { + return workflowScheduleService; + } + + public void setWorkflowScheduleService(WorkflowScheduleService workflowScheduleService) { + this.workflowScheduleService = workflowScheduleService; + } + +} diff --git a/ONAP-SDK-APP/src/main/java/org/onap/portalapp/service/AdminAuthExtension.java b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/service/AdminAuthExtension.java new file mode 100644 index 000000000..dadb66c8e --- /dev/null +++ b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/service/AdminAuthExtension.java @@ -0,0 +1,114 @@ +/*- + * ================================================================================ + * ONAP Portal SDK + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property + * ================================================================================ + * 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. + * ================================================================================ + */ +package org.onap.portalapp.service; + +import java.util.Set; + +import org.onap.policy.model.Roles; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.UserInfo; +import org.openecomp.portalapp.service.IAdminAuthExtension; +import org.openecomp.portalsdk.core.domain.Role; +import org.openecomp.portalsdk.core.domain.User; +import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + + +@Service("adminAuthExtension") +@Transactional +/** + * Provides empty implementations of the methods in IAdminAuthExtension. + */ +public class AdminAuthExtension implements IAdminAuthExtension { + + EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AdminAuthExtension.class); + + @Autowired + CommonClassDao commonClassDao; + + + /* + * (non-Javadoc) + * @see org.onap.portalapp.service.IAdminAuthExtension#saveUserExtension(org.openecomp.portalsdk.core.domain.User) + */ + public void saveUserExtension(User user) { + logger.debug("saveUserExtension"); + savePolicyRole(null, user); + } + + /* + * (non-Javadoc) + * @see org.onap.portalapp.service.IAdminAuthExtension#editUserExtension(org.openecomp.portalsdk.core.domain.User) + */ + public void editUserExtension(User user) { + logger.debug("editUserExtension"); + } + + /* + * (non-Javadoc) + * @see org.onap.portalapp.service.IAdminAuthExtension#saveUserRoleExtension(java.util.Set, org.openecomp.portalsdk.core.domain.User) + */ + public void saveUserRoleExtension(Set roles, User user) { + logger.debug("saveUserRoleExtension"); + savePolicyRole(roles, user); + } + + private void savePolicyRole(Set roles, User user){ + System.out.println("User Object Recieved"); + try{ + Roles roles1 = new Roles(); + roles1.setName(user.getFullName()); + roles1.setLoginId(user.getLoginId()); + if(user.getRoles() != null){ + String query = "delete from Roles where loginid='"+user.getLoginId()+"'"; + commonClassDao.updateQuery(query); + for(Role role : user.getRoles()){ + System.out.println("User Role"+role); + if(role.getName().trim().equalsIgnoreCase("Policy Super Admin") || role.getName().trim().equalsIgnoreCase("System Administrator") || role.getName().trim().equalsIgnoreCase("Standard User") ){ + roles1.setRole("super-admin"); + }else if(role.getName().trim().equalsIgnoreCase("Policy Super Editor")){ + roles1.setRole("super-editor"); + }else if(role.getName().trim().equalsIgnoreCase("Policy Super Guest")){ + roles1.setRole("super-guest"); + }else if(role.getName().trim().equalsIgnoreCase("Policy Admin")){ + roles1.setRole("admin"); + }else if(role.getName().trim().equalsIgnoreCase("Policy Editor")){ + roles1.setRole("editor"); + }else if(role.getName().trim().equalsIgnoreCase("Policy Guest")){ + roles1.setRole("guest"); + } + commonClassDao.save(roles1); + } + } + + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(user.getLoginId()); + userInfo.setUserName(user.getFullName()); + commonClassDao.save(userInfo); + System.out.println("User Object Updated Successfully"); + } + catch(Exception e){ + logger.error("Exception caused while Setting role to Policy DB"+e); + } + } + +} diff --git a/ONAP-SDK-APP/src/main/resources/logback.xml b/ONAP-SDK-APP/src/main/resources/logback.xml new file mode 100644 index 000000000..5340181f1 --- /dev/null +++ b/ONAP-SDK-APP/src/main/resources/logback.xml @@ -0,0 +1,370 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ${defaultLoggerPattern} + + + + + + + + + + + + ${logDirectory}/${generalLogName}.log + + + ${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.log.zip + + + 30 + 3GB + + + + ${applicationLoggerPattern} + + + + + + 256 + + true + + + + + + + + + + + + + + + + + + + ${logDirectory}/${auditLogName}.log + + + ${logDirectory}/${auditLogName}.%d{yyyy-MM-dd}.log.zip + + + 30 + 3GB + + + + ${auditLoggerPattern} + + + + 256 + + + + + ${logDirectory}/${metricsLogName}.log + + + ${logDirectory}/${metricsLogName}.%d{yyyy-MM-dd}.log.zip + + + 30 + 3GB + + + + ${metricsLoggerPattern} + + + + + + 256 + + + + + ${logDirectory}/${errorLogName}.log + + + ${logDirectory}/${errorLogName}.%d{yyyy-MM-dd}.log.zip + + + 30 + 3GB + + + + ${errorLoggerPattern} + + + + + 256 + + + + + ${debugLogDirectory}/${debugLogName}.log + + + ${logDirectory}/${debugLogName}.%d{yyyy-MM-dd}.log.zip + + + 30 + 3GB + + + + ${defaultLoggerPattern} + + + + + 256 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/ONAP-SDK-APP/src/main/resources/portal.properties b/ONAP-SDK-APP/src/main/resources/portal.properties new file mode 100644 index 000000000..deca4e34b --- /dev/null +++ b/ONAP-SDK-APP/src/main/resources/portal.properties @@ -0,0 +1,69 @@ +### +# ================================================================================ +# onap Portal SDK +# ================================================================================ +# Copyright (C) 2017 AT&T Intellectual Property +# ================================================================================ +# 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. +# ================================================================================ +### +# Properties read by ONAP Framework library, onapFW.jar + +########################################################################## +# The following properties should NOT be changed by partner applications. +########################################################################## + +portal.api.prefix = /api +max.idle.time = 5 +user.attribute.name = user_attribute + +# CSP settings +csp_cookie_name = attESSec +csp_gate_keeper_prod_key = PROD +testing=testing + +#Use REST API instead of UEB to fetch the functional menu data +use_rest_for_functional_menu=true + +########################################################################## +# The following properties MUST be changed by partner applications. +########################################################################## + +# Name of java class that implements the OnBoardingApiService interface. +portal.api.impl.class = org.onap.portalapp.service.OnBoardingApiServiceImpl + +# CSP Global Log On for single sign on +onap_redirect_url = todo_csp_global_logon + +# URL of the ONAP Portal REST API +onap_rest_url = todo_Onap_rest_url + +# Applications do not need to run a UEB listener in 1610. +ueb_listeners_enable = false + +# UEB Configuration +# In release 1607, all 6 entries below were required. +# In release 1610, if key ueb_listeners_enable is set to false, +# then only the ueb_app_key is required. +# UEB servers +ueb_url_list = todo_ueb_list +# ONAP Portal listens on this UEB topic +onap_portal_inbox_name = ONAP-PORTAL-INBOX-TEST-DEMETER +# Replace these 3 default values with the ones for your specific App, +# as shown on the on-boarding page on the ONAP Portal web application. +ueb_app_key = ZOicEniw7BWDL1pM +ueb_app_secret = PJIsBErHfo2RGKzuu03CZKgV +ueb_app_mailbox_name = ONAP-PORTAL-OUTBOX-TEST-32756 +# Consumer group name for UEB topic. +# Use the special tag '{UUID}' to generate a unique one for each sdk-app server. +ueb_app_consumer_group_name = {UUID} diff --git a/ONAP-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties b/ONAP-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties new file mode 100644 index 000000000..304bcbd90 --- /dev/null +++ b/ONAP-SDK-APP/src/main/webapp/WEB-INF/conf/system.properties @@ -0,0 +1,72 @@ +# Properties read by ONAP Core library, onapSDK-core.jar + +########################################################################## +# The following properties should NOT be changed by partner applications. +########################################################################## + +application_user_id = 30000 +post_default_role_id = 16 +clustered = true + +#Enable Fusion Mobile capabilities for the application +mobile_enable = false + +# Cache config file is needed on the classpath +cache_config_file_path = /WEB-INF/classes/cache.ccf +cache_switch = 199 +cache_load_on_startup = false + +user_name = fullName +decryption_key = AGLDdG4D04BKm2IxIWEr8o== + +########################################################################## +# The following properties MAY require changes by partner applications. +########################################################################## +#Mysql +db.driver = com.mysql.jdbc.Driver +db.connectionURL = jdbc:mysql://localhost:3306/onap_sdk +db.userName = policy_user +db.password = policy_user +db.hib.dialect = org.hibernate.dialect.MySQLDialect +db.min_pool_size = 5 +db.max_pool_size = 10 +hb.dialect = org.hibernate.dialect.MySQLDialect +# SQL statements are logged to stdout +hb.show_sql = true +hb.idle_connection_test_period = 3600 + +app_display_name = EP SDK App +files_path = /tmp + +#element map files +element_map_file_path = /tmp +element_map_icon_path = app/fusionapp/icons/ + +#Cron Schedules have 6 required fields and 1 optional field: +# Seconds Minutes Hours Day-of-Month Month Day-of-Week Year +log_cron = 0 0/1 * * * ?; +mylogins_feed_cron = 0 0/60 * * * ?; +#sessiontimeout_feed_cron = 0 * * * * ? * +my_login_feed_output_dir = /tmp/MyLogins + +# ONAP Portal Shared Context REST API URL +onap_shared_context_rest_url= todo_shared_context_url + +# Link shown in Help menu +contact_us_link = todo_Contact_link + +# Camunda cockpit link +camunda_cockpit_link = todo_camunda_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 ONAP SDK at the time of its deployment. +# Online Unique UUID generator - https://www.uuidgenerator.net/ +instance_uuid=8da691c9-987d-43ed-a358-00ac2f35685d + +# R Cloud feature +guard_notebook_url=todo_guard_url + +# Application base URL has the host and app context only; a proper prefix of the on-boarded URL. +# Only required for applications using WebJunction or FE/BE separation. For example: +# app_base_url = todo_App_base_url diff --git a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/defs/definitions.xml b/ONAP-SDK-APP/src/main/webapp/WEB-INF/defs/definitions.xml similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/WEB-INF/defs/definitions.xml rename to ONAP-SDK-APP/src/main/webapp/WEB-INF/defs/definitions.xml diff --git a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/fusion/conf/fusion.properties b/ONAP-SDK-APP/src/main/webapp/WEB-INF/fusion/conf/fusion.properties similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/WEB-INF/fusion/conf/fusion.properties rename to ONAP-SDK-APP/src/main/webapp/WEB-INF/fusion/conf/fusion.properties diff --git a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/footer.jsp b/ONAP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/footer.jsp similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/footer.jsp rename to ONAP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/footer.jsp diff --git a/ECOMP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/header.jsp b/ONAP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/header.jsp similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/header.jsp rename to ONAP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/header.jsp diff --git a/ONAP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/left-menu.jsp b/ONAP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/left-menu.jsp new file mode 100644 index 000000000..edb040504 --- /dev/null +++ b/ONAP-SDK-APP/src/main/webapp/WEB-INF/fusion/jsp/ds2/left-menu.jsp @@ -0,0 +1,778 @@ +<%-- + ================================================================================ + onap Portal SDK + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + 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. + ================================================================================ + --%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> +<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%> +<%@ page isELIgnored="false"%> +<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties"%> +<%@ page import="org.openecomp.portalsdk.core.onboarding.util.PortalApiProperties"%> +<%@ page import="org.openecomp.portalsdk.core.onboarding.util.PortalApiConstants"%> +<%@ page import="org.openecomp.portalsdk.core.domain.MenuData"%> + + + + + + + + + + + +" /> +" /> + +<% + String contactUsLink = SystemProperties.getProperty(SystemProperties.CONTACT_US_LINK); + String redirectUrl = PortalApiProperties.getProperty(PortalApiConstants.ONAP_REDIRECT_URL); + String portalUrl = redirectUrl.substring(0, redirectUrl.lastIndexOf('/')) + "/process_csp"; + String getAccessLink = redirectUrl.substring(0, redirectUrl.lastIndexOf('/')) + "/get_access"; +%> + + + + + + +<%@include file="/WEB-INF/fusion/jsp/ebz/loginSnippet.html" %> + +
    +
    + +
    +
    +
    + + +
    +
    +
    +
    +
  • + + ONAP Portal +
  • +
    +
    + +
    +
    + + +
    + + +
    +
    +
    +
  • + Unable to load menus +
  • +
    + +
    +
  • +
    + + +
    +
  • +
  •  
  • +
    + +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + +     {{app_name}} + +
    +
    +
    +
    + + + + + +
    +
    +
    +
    +
    +
    +
    +
    + + \ No newline at end of file diff --git a/ONAP-SDK-APP/src/main/webapp/WEB-INF/fusion/orm/RNoteBookIntegration.hbm.xml b/ONAP-SDK-APP/src/main/webapp/WEB-INF/fusion/orm/RNoteBookIntegration.hbm.xml new file mode 100644 index 000000000..984e2369b --- /dev/null +++ b/ONAP-SDK-APP/src/main/webapp/WEB-INF/fusion/orm/RNoteBookIntegration.hbm.xml @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ONAP-SDK-APP/src/main/webapp/WEB-INF/index.jsp b/ONAP-SDK-APP/src/main/webapp/WEB-INF/index.jsp new file mode 100644 index 000000000..ac19fd94a --- /dev/null +++ b/ONAP-SDK-APP/src/main/webapp/WEB-INF/index.jsp @@ -0,0 +1,24 @@ +<%-- + ================================================================================ + onap Portal SDK + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + 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. + ================================================================================ + --%> +<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> + +<%-- Redirected because we can't set the welcome page to a virtual URL. --%> +<%-- Forward to the intended start page to reduce frustration for new users. --%> + diff --git a/ONAP-SDK-APP/src/main/webapp/WEB-INF/jsp/login.jsp b/ONAP-SDK-APP/src/main/webapp/WEB-INF/jsp/login.jsp new file mode 100644 index 000000000..2d6c95115 --- /dev/null +++ b/ONAP-SDK-APP/src/main/webapp/WEB-INF/jsp/login.jsp @@ -0,0 +1,113 @@ +<%-- + ================================================================================ + ONAP Portal SDK + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + 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. + ================================================================================ +--%> +<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties"%> + +<% + // Name is defined by app; do not throw if missing + final String appDisplayName = SystemProperties.containsProperty(SystemProperties.APP_DISPLAY_NAME) + ? SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + : SystemProperties.APP_DISPLAY_NAME; +%> + + + + + + + Login + + + + +
    +
    +
    ${model.error}
    +
    +
    +
    +
    +
    +
    + + + diff --git a/ONAP-SDK-APP/src/main/webapp/WEB-INF/jsp/login_external.jsp b/ONAP-SDK-APP/src/main/webapp/WEB-INF/jsp/login_external.jsp new file mode 100644 index 000000000..cb980c625 --- /dev/null +++ b/ONAP-SDK-APP/src/main/webapp/WEB-INF/jsp/login_external.jsp @@ -0,0 +1,117 @@ +<%-- + ================================================================================ + ONAP Portal SDK + ================================================================================ + Copyright (C) 2017 AT&T Intellectual Property + ================================================================================ + 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. + ================================================================================ +--%> +<%@ page import="org.openecomp.portalsdk.core.util.SystemProperties"%> + +<% + // Name is defined by app; do not throw if missing + final String appDisplayName = SystemProperties.containsProperty(SystemProperties.APP_DISPLAY_NAME) + ? SystemProperties.getProperty(SystemProperties.APP_DISPLAY_NAME) + : SystemProperties.APP_DISPLAY_NAME; +%> + + + + + + + + + + + +
    +
    +
    ${model.error}
    +
    +
    +
    +
    +
    +
    + + + diff --git a/ONAP-SDK-APP/src/main/webapp/WEB-INF/web.xml b/ONAP-SDK-APP/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 000000000..31b096049 --- /dev/null +++ b/ONAP-SDK-APP/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,17 @@ + + + + onap-sdk-app-os + + + + + + 7 + COOKIE + + + \ No newline at end of file diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/font_icons.css b/ONAP-SDK-APP/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/font_icons.css similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/font_icons.css rename to ONAP-SDK-APP/src/main/webapp/app/fusion/external/b2b/css/b2b-angular/font_icons.css diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/digital-ng-library/ionicons.css b/ONAP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/digital-ng-library/ionicons.css similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/digital-ng-library/ionicons.css rename to ONAP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/digital-ng-library/ionicons.css diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.eot b/ONAP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.eot similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.eot rename to ONAP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.eot diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.svg b/ONAP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.svg similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.svg rename to ONAP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.svg diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.ttf b/ONAP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.ttf similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.ttf rename to ONAP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.ttf diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.woff b/ONAP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.woff similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.woff rename to ONAP-SDK-APP/src/main/webapp/app/fusion/external/ds2/css/fonts/ionicons.woff diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-controllers/ds-profile/post-controller.js b/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-controllers/ds-profile/post-controller.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-controllers/ds-profile/post-controller.js rename to ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-controllers/ds-profile/post-controller.js diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-controllers/samplePage-route.js b/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-controllers/samplePage-route.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-controllers/samplePage-route.js rename to ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-controllers/samplePage-route.js diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-services/postSearch.js b/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-services/postSearch.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-services/postSearch.js rename to ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-services/postSearch.js diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-profile/post.html b/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-profile/post.html similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-profile/post.html rename to ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-profile/post.html diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-profile/profile_searchDS2.html b/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-profile/profile_searchDS2.html similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-profile/profile_searchDS2.html rename to ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-profile/profile_searchDS2.html diff --git a/ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-profile/self_profile.html b/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-profile/self_profile.html similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-profile/self_profile.html rename to ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-profile/self_profile.html diff --git a/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-samplePages/samplePage.html b/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-samplePages/samplePage.html new file mode 100644 index 000000000..523bfe71e --- /dev/null +++ b/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/ds2-samplePages/samplePage.html @@ -0,0 +1,62 @@ + + + + + + + Sample Page + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +
    + + + diff --git a/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/footer.html b/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/footer.html new file mode 100644 index 000000000..f219b1b0b --- /dev/null +++ b/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/DS2-view-models/footer.html @@ -0,0 +1,13 @@ +
    +
    + +
    +
    \ No newline at end of file diff --git a/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/utils/page-resource-ds2.js b/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/utils/page-resource-ds2.js new file mode 100644 index 000000000..21b6b0dc1 --- /dev/null +++ b/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/utils/page-resource-ds2.js @@ -0,0 +1,97 @@ +function loadjscssfile(filename, filetype){ + if (filetype=="js"){ //if filename is a external JavaScript file + var done = false; + var script = document.createElement('script'); + script.src = filename; + script.async = false; + document.head.appendChild(script); + }else if (filetype=="css"){ //if filename is an external CSS file + var fileref=document.createElement("link") + fileref.setAttribute("rel", "stylesheet") + fileref.setAttribute("type", "text/css") + fileref.setAttribute("async", false) + fileref.setAttribute("href", filename) + document.head.appendChild(fileref); + } +} + +function loadResource(){ + /*********************AngularJs***************************/ + loadjscssfile("./app/fusion/external/angular-1.5/angular.min.js", "js"); + loadjscssfile("./app/fusion/external/angular-1.5/angular-messages.js", "js"); + loadjscssfile("./app/fusion/external/angular-1.5/angular-touch.js", "js"); + loadjscssfile("./app/fusion/external/angular-1.5/angular-sanitize.min.js", "js"); + loadjscssfile("./app/fusion/external/angular-1.5/angular-route.min.js", "js"); + loadjscssfile("./app/fusion/external/angular-1.5/angular-cookies.min.js", "js"); + + loadjscssfile("./app/fusion/external/ds2/js/b2b-angular/b2b-library.min.js", "js"); +/* loadjscssfile("./app/fusion/external/ds2/js/digital-ng-library/digital.ng.library.min.js", "js"); +*/ + loadjscssfile("./app/fusion/external/jquery/dist/jquery.min.js", "js"); + + /*********************Angular Gridster***************************/ + loadjscssfile("./app/fusion/external/angular-gridster/dist/angular-gridster.min.css", "css"); + loadjscssfile("./app/fusion/external/angular-bootstrap/ui-bootstrap-csp.css", "css"); + loadjscssfile("./app/fusion/external/javascript-detect-element-resize/jquery.resize.js", "js"); + loadjscssfile("./app/fusion/external/angular-bootstrap/ui-bootstrap-tpls.min.js", "js"); + loadjscssfile("./app/fusion/external/angular-gridster/dist/angular-gridster.min.js", "js"); + + /*********************Angular UI grid***************************/ + loadjscssfile("./app/fusion/external/angular-ui-grid/ui-grid.js", "js"); + loadjscssfile("./app/fusion/external/angular-ui-grid/ui-grid.css", "css"); + + loadjscssfile("./app/fusion/external/ds2/js/appDS2.js", "js"); + + loadjscssfile("./app/fusion/scripts/DS2-services/headerServiceDS2.js", "js"); + loadjscssfile("./app/fusion/scripts/DS2-services/leftMenuServiceDS2.js", "js"); + loadjscssfile("./app/fusion/scripts/DS2-services/manifestService.js", "js"); + loadjscssfile("./app/fusion/scripts/DS2-directives/footer.js", "js"); + loadjscssfile("./app/fusion/scripts/DS2-directives/ds2Header.js", "js"); + loadjscssfile("./app/fusion/scripts/DS2-directives/ds2LeftMenu.js", "js"); + loadjscssfile("./app/fusion/external/ds2/js/digital-ng-library/digital-design-library.js", "js"); + + /*******DS2 styles*******/ + loadjscssfile("./app/fusion/external/ds2/css/b2b-angular/b2b-angular.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/extras/ds2-accordion.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/extras/ds2-bootstrap-datepicker.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/extras/ds2-cc-input-field.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/extras/ds2-tooltip.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/extras/x-tabs-pills.css", "css"); + + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-accordion.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-bootstrap-datepicker.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-c2c.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-cc-input-field.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-filmstrip.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-filters.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-legacynav-fix.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-marquee.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-pagination.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-popover.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-progressbar.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ds2-tooltip.css", "css"); + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/global.css", "css"); + + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/digital-design-library.css", "css"); + /*******DS2 ICONS*******/ + + loadjscssfile("./app/fusion/external/ds2/css/digital-ng-library/ionicons.css", "css"); + loadjscssfile("./app/fusion/styles/onap.css", "css"); + loadjscssfile("./app/fusion/external/angular-gridster/dist/angular-gridster.min.css", "css"); + +} + +window.onload = loadResource(); +/*window.onload = function(){ + var appLoadingInterval = setInterval(function(){ loadApp() }, 10000); + var count=0; + function loadApp(){ + count++ + if(typeof angular !== 'undefined') { + angular.bootstrap(document, ['abs']); + clearInterval(appLoadingInterval); + }else if(count>10){ + clearInterval(appLoadingInterval); + } + } +}*/ \ No newline at end of file diff --git a/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/view-models/footer.html b/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/view-models/footer.html new file mode 100644 index 000000000..5e42f0015 --- /dev/null +++ b/ONAP-SDK-APP/src/main/webapp/app/fusion/scripts/view-models/footer.html @@ -0,0 +1,17 @@ + + + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    + \ No newline at end of file diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/css/att_angular_gridster/sandbox-gridster.css b/ONAP-SDK-APP/src/main/webapp/static/fusion/css/att_angular_gridster/sandbox-gridster.css similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/css/att_angular_gridster/sandbox-gridster.css rename to ONAP-SDK-APP/src/main/webapp/static/fusion/css/att_angular_gridster/sandbox-gridster.css diff --git a/ONAP-SDK-APP/src/main/webapp/static/fusion/css/att_angular_gridster/ui-gridster.css b/ONAP-SDK-APP/src/main/webapp/static/fusion/css/att_angular_gridster/ui-gridster.css new file mode 100644 index 000000000..b237f3056 --- /dev/null +++ b/ONAP-SDK-APP/src/main/webapp/static/fusion/css/att_angular_gridster/ui-gridster.css @@ -0,0 +1,116 @@ +/* ui-gridster.css */ +.gridster-container { + background-color: #EFEFEF; + color: #fff; + border: 1px dashed; + overflow-y: auto; + overflow-x: hidden; } + +/* app css for attGridtser */ +.gridster-item-container { + background-color: #FFFFFF; + position: relative; + margin-left: auto; + margin-right: auto; + min-height: 79px; + height: 100%; } + .gridster-item-container .gridster-item-header { + /* gridster-item Header */ + position: relative; + height: 50px !important; + border: 1px solid #d3d3d3; + border-bottom: 0; + background-color: #E5E5E5; + white-space: nowrap; + text-overflow: ellipsis; + z-index: 1; + -webkit-border-radius: 2px 2px 0 0; + -moz-border-radius: 2px 2px 0 0; + -ms-border-radius: 2px 2px 0 0; + -o-border-radius: 2px 2px 0 0; + border-radius: 2px 2px 0 0; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + overflow: hidden; + /* IE6-8 */ } + .gridster-item-container .gridster-item-header .gridster-item-handle { + cursor: move; + margin: 12px; + position: absolute; + top: 0; + left: 0; + border: 0; + vertical-align: middle; + -ms-interpolation-mode: bicubic; + display: block; } + .gridster-item-container .gridster-item-header .gridster-item-header-content { + line-height: 44px; + margin-left: 26px; + font-family: "Omnes-ONAP-W02", Arial; + font-size: 18px; + color: #444444; + float: left; } + .gridster-item-container .gridster-item-header .gridster-item-sub-header-content { + position: absolute; + top: 29.5px; + left: 26px; + font-family: "Omnes-ONAP-W02", Arial; + font-size: 12px; + color: #444444; } + .gridster-item-container .gridster-item-header .gridster-item-header-buttons-container { + position: absolute; + right: 10px; + top: 10px; + overflow: hidden; + text-align: right; + height: 30px; + color: #444444; } + .gridster-item-container .gridster-item-body { + /* gridster-item Body */ + position: absolute; + width: 100%; + top: 50px; + left: 0; + right: 0; + bottom: 29px; + border: 1px solid #d3d3d3; + box-sizing: border-box; + overflow: auto; + color: #444444; + /* text-align: center; */ } + .gridster-item-container .gridster-item-footer { + /* gridster-item Footer */ + position: absolute; + bottom: 0; + width: 100%; + height: 29px !important; + text-align: left; + cursor: pointer; + border: 1px solid #d3d3d3; + border-top: 0; + background-color: #F2F2F2; + -webkit-border-radius: 0 0 2px 2px; + -moz-border-radius: 0 0 2px 2px; + -ms-border-radius: 0 0 2px 2px; + -o-border-radius: 0 0 2px 2px; + border-radius: 0 0 2px 2px; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; + text-decoration: none; + /* IE6-8 */ } + .gridster-item-container .gridster-item-footer:hover { + background-color: #E5E5E5; + color: #565656; + text-decoration: underline; } + .gridster-item-container .gridster-item-footer .gridster-item-footer-content { + line-height: 30px; + font-family: "Omnes-ONAP-W02", Arial; + font-size: 12px; + color: #565656; + margin: 20px; + text-decoration: none; } + .gridster-item-container .gridster-item-footer .gridster-item-footer-content:hover { + color: #199ddf; + text-decoration: underline; } diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/css/fusion-sunny.css b/ONAP-SDK-APP/src/main/webapp/static/fusion/css/fusion-sunny.css similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/css/fusion-sunny.css rename to ONAP-SDK-APP/src/main/webapp/static/fusion/css/fusion-sunny.css diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/images/att_angular_gridster/grips.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/images/att_angular_gridster/grips.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/images/att_angular_gridster/grips.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/images/att_angular_gridster/grips.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/images/ecomp-login-550x360.jpg b/ONAP-SDK-APP/src/main/webapp/static/fusion/images/onap-login-550x360.jpg similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/images/ecomp-login-550x360.jpg rename to ONAP-SDK-APP/src/main/webapp/static/fusion/images/onap-login-550x360.jpg diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/images/ecomp-login.jpg b/ONAP-SDK-APP/src/main/webapp/static/fusion/images/onap-login.jpg similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/images/ecomp-login.jpg rename to ONAP-SDK-APP/src/main/webapp/static/fusion/images/onap-login.jpg diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/images/ecomp.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/images/onap.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/images/ecomp.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/images/onap.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/images/ecomp_trans.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/images/onap_trans.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/images/ecomp_trans.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/images/onap_trans.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/js/att_angular_gridster/angular-gridster.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/js/att_angular_gridster/angular-gridster.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/js/att_angular_gridster/angular-gridster.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/js/att_angular_gridster/angular-gridster.js diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/js/att_angular_gridster/ui-gridster-tpls.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/js/att_angular_gridster/ui-gridster-tpls.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/js/att_angular_gridster/ui-gridster-tpls.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/js/att_angular_gridster/ui-gridster-tpls.js diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/images/blank.gif b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/css/images/blank.gif similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/images/blank.gif rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/css/images/blank.gif diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/scribble.css b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/css/scribble.css similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/scribble.css rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/css/scribble.css diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/slider.css b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/css/slider.css similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/slider.css rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/css/slider.css diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/spacegallery.css b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/css/spacegallery.css similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/spacegallery.css rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/css/spacegallery.css diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/welcome.css b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/css/welcome.css similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/css/welcome.css rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/css/welcome.css diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/area_chart.html b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/area_chart.html similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/area_chart.html rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/area_chart.html diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/bar_chart.html b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/bar_chart.html similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/bar_chart.html rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/bar_chart.html diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/d3_gauges_demo.html b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/d3_gauges_demo.html similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/d3_gauges_demo.html rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/d3_gauges_demo.html diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/speedometer2.csv b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/speedometer2.csv similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/speedometer2.csv rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/speedometer2.csv diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/speedometer3.csv b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/speedometer3.csv similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/speedometer3.csv rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/speedometer3.csv diff --git a/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/worddata.csv b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/worddata.csv new file mode 100644 index 000000000..f9a8669ba --- /dev/null +++ b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/data/worddata.csv @@ -0,0 +1 @@ +text,frequency service,98 portal,70 management,70 virtual,56 design,56 VNF,56 studio,42 operations,42 inventory,42 POLO,42 D2.0,42 ASDC,42 router,28 restart,28 process,28 platform,28 manage,28 loop,28 licensing,28 license,28 integrated,28 flow-through,28 enable,28 data,28 controller,28 control,28 configure,28 component,28 common,28 asset,28 application,28 ONAP,28 workflow,14 waterfall,14 visual,14 view,14 vCTS,14 utilization,14 user,14 usage,14 troubleshoot,14 transformation,14 track,14 topolgies,14 topics,14 time,14 tickets,14 thresholds,14 templates,14 structures,14 standards-based,14 software,14 reuse,14 repository,14 reports,14 release,14 recipes,14 real-time,14 provisioning,14 properties,14 project-based,14 processes,14 physical,14 oversight,14 openl-loop,14 network,14 monitor,14 modeling,14 model-driven,14 model,14 message,14 maximize,14 manually,14 machine,14 layer,14 interact,14 instances,14 initiate,14 increase,14 imported,14 impacts,14 host,14 function,14 feeds,14 features,14 faults,14 extended,14 engines,14 engine,14 dynamic,14 document-driven,14 determine,14 dashboard,14 current,14 creation,14 created,14 create,14 configuration,14 composer,14 components,14 collective,14 certification,14 bus,14 basis,14 available,14 automation,14 automated,14 associated,14 assignment,14 appropriate,14 against,14 aervice,14 adminstrators,14 activation,14 action,14 VMs,14 VM,14 VLAN,14 SDN,14 SDK,14 SBG,14 SAM,14 RUBY,14 Policy,14 PODS,14 Ops,14 GFP,14 F5FW,14 DMaaP,14 DCAE,14 DBC,14 CPADS,14 AT&T,14 APP-C,14 AOTS-TM,14 ALTS,14 A&AI,14 diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/donut_d3.html b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/donut_d3.html similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/donut_d3.html rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/donut_d3.html diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/area_chart.min.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/area_chart.min.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/area_chart.min.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/area_chart.min.js diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/donut.min.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/donut.min.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/donut.min.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/donut.min.js diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/gauges.min.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/gauges.min.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/gauges.min.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/gauges.min.js diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/line_chart.min.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/line_chart.min.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/line_chart.min.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/line_chart.min.js diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/pie_chart.min.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/pie_chart.min.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/pie_chart.min.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/pie_chart.min.js diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/worddata.min.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/worddata.min.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/worddata.min.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/js/worddata.min.js diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/line_chart.html b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/line_chart.html similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/line_chart.html rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/line_chart.html diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/pie_chart.html b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/pie_chart.html similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/html/pie_chart.html rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/pie_chart.html diff --git a/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/wordcloud.html b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/wordcloud.html new file mode 100644 index 000000000..120c1e30b --- /dev/null +++ b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/html/wordcloud.html @@ -0,0 +1,36 @@ + + + Word Cloud Example + + + + + + + + + +
    + + +
    +
    + +
    + + + +
    + + \ No newline at end of file diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/Calendar-16x16.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/Calendar-16x16.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/Calendar-16x16.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/Calendar-16x16.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/arrow-next.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/arrow-next.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/arrow-next.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/arrow-next.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/arrow-prev.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/arrow-prev.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/arrow-prev.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/arrow-prev.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_drive_test_map.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_drive_test_map.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_drive_test_map.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_drive_test_map.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_eppt_county.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_eppt_county.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_eppt_county.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_eppt_county.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_eppt_regression.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_eppt_regression.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_eppt_regression.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_eppt_regression.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_ios_throughput.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_ios_throughput.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_ios_throughput.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_ios_throughput.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_lata_map.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_lata_map.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_lata_map.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_lata_map.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_lata_map_legend.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_lata_map_legend.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_lata_map_legend.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_lata_map_legend.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_nova_sdn_map.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_nova_sdn_map.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_nova_sdn_map.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/carousel/slide_b_nova_sdn_map.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/copyicon.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/copyicon.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/copyicon.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/copyicon.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/deleteicon.gif b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/deleteicon.gif similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/deleteicon.gif rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/deleteicon.gif diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/example-frame.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/example-frame.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/example-frame.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/example-frame.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/loading.gif b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/loading.gif similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/loading.gif rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/loading.gif diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/1_mon.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/1_mon.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/1_mon.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/1_mon.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/2_tue.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/2_tue.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/2_tue.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/2_tue.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/3_wed.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/3_wed.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/3_wed.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/3_wed.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/4_thu.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/4_thu.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/4_thu.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/4_thu.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/5_fri.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/5_fri.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/5_fri.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/5_fri.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/6_sat.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/6_sat.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/6_sat.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/6_sat.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/7_sun.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/7_sun.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/7_sun.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/7_sun.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_DLSTX_IN.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_DLSTX_IN.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_DLSTX_IN.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_DLSTX_IN.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_DLSTX_OUT.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_DLSTX_OUT.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_DLSTX_OUT.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_DLSTX_OUT.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_Nat.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_Nat.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_Nat.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_Nat.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_Nat_Def.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_Nat_Def.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_Nat_Def.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_Nat_Def.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_Nat_Priority.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_Nat_Priority.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_Nat_Priority.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/images/tunnels/BH_Nat_Priority.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/FusionCharts.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/js/FusionCharts.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/FusionCharts.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/js/FusionCharts.js diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/charts.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/js/charts.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/charts.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/js/charts.js diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/jquery.flexslider-min.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/js/jquery.flexslider-min.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/jquery.flexslider-min.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/js/jquery.flexslider-min.js diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/scribble.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/js/scribble.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/scribble.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/js/scribble.js diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/slides.min.jquery.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/js/slides.min.jquery.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/slides.min.jquery.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/js/slides.min.jquery.js diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/spacegallery.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/js/spacegallery.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/js/spacegallery.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/js/spacegallery.js diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/bootstrap.min.css b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/bootstrap.min.css similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/bootstrap.min.css rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/bootstrap.min.css diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/custom.css b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/custom.css similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/custom.css rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/custom.css diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/jquery.jOrgChart.css b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/jquery.jOrgChart.css similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/jquery.jOrgChart.css rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/jquery.jOrgChart.css diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/prettify.css b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/prettify.css similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/prettify.css rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/css/prettify.css diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/example.html b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/example.html similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/example.html rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/example.html diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/example_vsp.html b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/example_vsp.html similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/example_vsp.html rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/example_vsp.html diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/images/bkgd.png b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/images/bkgd.png similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/images/bkgd.png rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/images/bkgd.png diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/images/raspberry.jpg b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/images/raspberry.jpg similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/images/raspberry.jpg rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/images/raspberry.jpg diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/jquery.jOrgChart.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/jquery.jOrgChart.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/jquery.jOrgChart.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/jquery.jOrgChart.js diff --git a/ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/prettify.js b/ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/prettify.js similarity index 100% rename from ECOMP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/prettify.js rename to ONAP-SDK-APP/src/main/webapp/static/fusion/sample/org_chart/prettify.js diff --git a/ONAP-SDK-APP/xacml.admin.properties b/ONAP-SDK-APP/xacml.admin.properties new file mode 100644 index 000000000..0f285b694 --- /dev/null +++ b/ONAP-SDK-APP/xacml.admin.properties @@ -0,0 +1,203 @@ +### +# ============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========================================================= +### + +# +# This file is set to the defaults one can use to run the XACML-PAP-ADMIN for testing and development. +# +# It is not recommended to modify this file directly, but rather copy it to another location and make any modifications +# necessary to run the application in a development or a production environment. You can set the Java VM System +# property to change where the application can find the file. For example: +# +#-Dxacml.properties=/opt/app/xacml/etc/xacml.admin.properties +# +# +# Standard API Factories +# +xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory +xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory +xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory +xacml.pipFinderFactory=com.att.research.xacml.std.pip.StdPIPFinderFactory +# +# AT&T PDP Implementation Factories +# +xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory +xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory +xacml.att.functionDefinitionFactory=org.onap.policy.xacml.custom.OnapFunctionDefinitionFactory +xacml.att.policyFinderFactory=com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory + +# +# This is an extremely simple policy to demonstrate authorization +# within the Admin Console. +# +xacml.rootPolicies=admin +# +# PAP Servlet properties +# +xacml.PAP.papEngineFactory=org.onap.policy.xacml.std.pap.StdEngineFactory + +# +# Admin Console properties +# +xacml.AC.papEngineFactory=org.onap.policy.xacml.admin.util.RESTfulPAPFactory + +# Set your domain here: +xacml.rest.admin.domain=com +# +# +# Property to declare the max time frame for logs. +# +xacml.log.timeframe=30 +# +# +# +xacml.rest.admin.closedLoopJSON =JSONConfig.json +xacml.rest.admin.microServiceModel=model.properties +xacm.restful.interface.file=RESTful.interface.properties +# +#If the Audit is set false, then Audit function will not work at the Server Run time. +#This will Syncronize the data between Roles and Userinfo Table +xacml.audit.userInfo = true +# +#The Test Environment User Login LoginIU Should provide below on seperating with Comma +# +xacml.testEnvironment.loginId = + +#Log DB properties +xacml.log.db.driver=org.mariadb.jdbc.Driver +xacml.log.db.url=jdbc:mariadb://localhost:3306/log?failOverReadOnly=false&autoReconnect=true +xacml.log.db.user=policy_user +xacml.log.db.password=policy_user + +xacml.att.log.timeframe=150 + +javax.persistence.jdbc.driver=com.mysql.jdbc.Driver +javax.persistence.jdbc.url=jdbc:mysql://localhost:3306/onap_sdk +javax.persistence.jdbc.user=policy_user +javax.persistence.jdbc.password=policy_user + +# Dashboard refresh rate in miliseconds +xacml.refresh.rate=40000 +xacml.user.column.count=3 +xacml.sqlcontainer.page.length=75 +xacm.xcor.required.pattern=1,1 +xacm.cache.live.time=2 +xacml.max.priority.count=10 + +# +# These can be set so the Admin Console knows who is logged on. Ideally, you can run the console in a J2EE +# container and setup authentication as you please. Setting HttpSession attribute values will override these +# values set in the properties files. +# +# ((HttpServletRequest) request).getSession().setAttribute("xacml.rest.admin.user.name", "Homer"); +# +# The default policy: Policy-Admin.xml is extremely simple. +# +# You can test authorization within the Admin Console by changing the user id. +# There are 3 supported user ids: +# guest - Read only access +# editor - Read/Write access +# admin - Read/Write/Admin access +# +# An empty or null value for xacml.rest.admin.user.id results in no access to the application at all. +# +# This is for development/demonstration purposes only. A production environment should provide authentication which is +# outside the scope of this application. This application can be used to develop a XACML policy for user authorization +# within this application. +# +#xacml.rest.admin.user.name=Guest +#xacml.rest.admin.user.id=guest +#xacml.rest.admin.user.name=Editor +#xacml.rest.admin.user.id=editor +xacml.rest.admin.user.name=Administrator +xacml.rest.admin.user.id=super-admin +xacml.rest.admin.user.email= + +# +# URL location for the PAP servlet. +# +xacml.rest.pap.url=http://localhost:8070/pap/ + +# id PAP +xacml.rest.pap.userid=testpap +# pass PAP +xacml.rest.pap.password=alpha123 + +# new Property Please mention your PAP-REST webapps Location here. + +xacml.rest.config.webapps=/home/users/PolicyEngine/webapps/ConfigPAP/ + +# pdps file - Needs to have the location of the PDPs File of the PAP-REST +xacml.rest.pdp.idfile=test.properties + +#Template Versions +xacml.rest.closedLoopFault=OpenSource.version.1 +xacml.rest.closedLoopPM=OpenSource.version.1 +xacml.rest.microServices=OpenSource.version.1 +xacml.rest.gocPolicy=OpenSource.version.1 +xacml.rest.firewallPolicy=OpenSource.version.1 + +#***Properties for IntegrityMonitor integration defined in XACMLRestProperties.java*** + +#The name of the Admin. Must be unique across the system +xacml.rest.admin.resource.name=site_1.admin_1 + +#The site name for the Admin +site_name=site_1 + +#Has to be one of pdp_xacml, pdp_drools, pap, pap_admin, logparser, brms_gateway, astra_gateway, elk_server +node_type=pap_admin + +# The (optional) period of time in seconds between executions of the integrity audit. +# Value < 0 : Audit does not run (default value if property is not present = -1) +# Value = 0 : Audit runs continuously +# Value > 0 : The period of time in seconds between execution of the audit on a particular node +integrity_audit_period_seconds=-1 + +#Automatic Policy Distribution +xacml.att.automatic.push = false + + +#Dashboard Tab Limit +xacml.onap.dashboard.logTableLimit = 5000 +xacml.onap.dashboard.systemAlertTableLimit = 2000 + + +#Diff of policies for Firewall feature +FW_GETURL=https://todo_enter_the_firewallurl +FW_AUTHOURL=https://todo_enter_the_firewallAuthurl +FW_PROXY=todo_enter_the_proxy +FW_PORT=8080 + +#SMTP Server Details for Java Mail +onap.smtp.host = smtp_host +onap.smtp.port = smtp_port +onap.smtp.userName = smtp_username +onap.smtp.password = smtp_password +onap.smtp.emailExtension=smtp_emailExtension +onap.application.name = smtp_AppName + +#Dialect for Database +onap.dialect = org.hibernate.dialect.MySQLDialect + +policyAdapter.impl.className = org.onap.policy.admin.PolicyAdapter + +#Micro Service Model Properties +xacml.policy.msOnapName=http://org.onap +xacml.policy.msPolicyName=http://org.onap.policy \ No newline at end of file diff --git a/ECOMP-XACML/.gitignore b/ONAP-XACML/.gitignore similarity index 100% rename from ECOMP-XACML/.gitignore rename to ONAP-XACML/.gitignore diff --git a/ONAP-XACML/config_testing/test_PolicyEngine.xml b/ONAP-XACML/config_testing/test_PolicyEngine.xml new file mode 100644 index 000000000..b5206a89a --- /dev/null +++ b/ONAP-XACML/config_testing/test_PolicyEngine.xml @@ -0,0 +1,595 @@ + + + + + Test Policies for the ProtoType PolicyEngineAPI + + + + Check if the CPU Utilization or Memory reach the threshold values. + + CPU + + + + 95 + + + Memory + + + + 95 + + + + + + Spinoff if the VM if CPU or memory value reaches the threshold + + CPU + + + + 90 + + + Memory + + + + 90 + + + + + Json Test + + + + + JSON + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_json.json + + + + + + Json + Config test + + + + + JSON + + + + JSONconfig + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_json.json + + + + + + XML test + + + + + XML + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_xml.xml + + + + + + XML + Config test + + + + + XML + + + + XMLConfig + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_xml.xml + + + + + + Properties Test + + + + + Properties + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_prop.properties + + + + + + Properties + Config Test + + + + + Properties + + + + PropConfig + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_prop.properties + + + + + + Other Test + + + + + Other + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_other.txt + + + + + + Other + Config Test + + + + + Other + + + + OtherConfig + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + http://localhost:5443/config/test_other.txt + + + + + + JSON + Attributes + + + + + JSON + + + + JSONconfig + + + + TestSubject + + + + ACCESS + + + + TestJSON + + + + Config + + + + Test + + + + + + + + + Configuration + + + http://localhost:5443/config/test_json.json + + + + + + XML + Attributes + + + + + XML + + + + XMLConfig + + + + TestSubject + + + + ACCESS + + + + TestJSON + + + + Config + + + + Test + + + + + + + + + Configuration + + + http://localhost:5443/config/test_xml.xml + + + + + + Prop + Attributes + + + + + Properties + + + + PropConfig + + + + TestSubject + + + + ACCESS + + + + TestJSON + + + + Config + + + + Test + + + + + + + + + Configuration + + + http://localhost:5443/config/test_prop.properties + + + + + + Other + Attributes + + + + + Other + + + + Otherconfig + + + + TestSubject + + + + ACCESS + + + + TestJSON + + + + Config + + + + Test + + + + + + + + + Configuration + + + http://localhost:5443/config/test_other.txt + + + + + + + Permit to RESET VM if the values reach the threshold settings. + + + + + Restart + + + + + + + + Restart VM if this condition is met + + true + + + + + + Restart + + + + + + + + + Permit to SpinOff VM if the values reach the threshold settings. + + + + + SpinOff + + + + + + + + SpinOff VM if this condition is met + + true + + + + + + SpinOff + + + PDPAction + + + REST + + + + + + GET + + + http://localhost:8635/RESTjson/PDP/VM/$com.att.labs.onap.obligation.spinoff/$com.att.labs.onap.obligation.server + + + + + + Deny all the other requests. + + + diff --git a/ONAP-XACML/config_testing/xacml.pip.properties b/ONAP-XACML/config_testing/xacml.pip.properties new file mode 100644 index 000000000..868488fc7 --- /dev/null +++ b/ONAP-XACML/config_testing/xacml.pip.properties @@ -0,0 +1,19 @@ +### +# ============LICENSE_START======================================================= +# ONAP-XACML +# ================================================================================ +# 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========================================================= +### diff --git a/ONAP-XACML/config_testing/xacml.policy.properties b/ONAP-XACML/config_testing/xacml.policy.properties new file mode 100644 index 000000000..09c580341 --- /dev/null +++ b/ONAP-XACML/config_testing/xacml.policy.properties @@ -0,0 +1,23 @@ +### +# ============LICENSE_START======================================================= +# ONAP-XACML +# ================================================================================ +# 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========================================================= +### + +xacml.referencedPolicies=test_PolicyEngine.xml +xacml.rootPolicies=test_PolicyEngine.xml +test_PolicyEngine.xml.file=config_testing\\test_PolicyEngine.xml diff --git a/ONAP-XACML/policyLogger.properties b/ONAP-XACML/policyLogger.properties new file mode 100644 index 000000000..6bb54e22e --- /dev/null +++ b/ONAP-XACML/policyLogger.properties @@ -0,0 +1,44 @@ +### +# ============LICENSE_START======================================================= +# ONAP-XACML +# ================================================================================ +# 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========================================================= +### + +################################### Set concurrentHashMap and timer info ####################### +#Timer initial delay and the delay between in milliseconds before task is to be execute. +timer.delay.time=1000 +#Timer scheduleAtFixedRate period - time in milliseconds between successive task executions. +check.interval= 30000 +#Longest time an event info can be stored in the concurrentHashMap for logging - in seconds. +event.expired.time=86400 +#Size of the concurrentHashMap which stores the event starting time, etc - when its size reaches this limit, the Timer gets executed +#to remove all expired records from this concurrentHashMap. +concurrentHashMap.limit=5000 +#Size of the concurrentHashMap - when its size drops to this point, stop the Timer +stop.check.point=2500 +################################### Set logging format ############################################# +# set EELF for EELF logging format, set LOG4J for using log4j, set SYSTEMOUT for using system.out.println +logger.type=EELF +#################################### Set level for EELF or SYSTEMOUT logging ################################## +# Set level for debug file. Set DEBUG to enable .info, .warn and .debug; set INFO for enable .info and .warn; set OFF to disable all +debugLogger.level=INFO +# Set level for metrics file. Set OFF to disable; set ON to enable +metricsLogger.level=ON +# Set level for error file. Set OFF to disable; set ON to enable +error.level=ON +# Set level for audit file. Set OFF to disable; set ON to enable +audit.level=ON diff --git a/ONAP-XACML/pom.xml b/ONAP-XACML/pom.xml new file mode 100644 index 000000000..d51cac9fe --- /dev/null +++ b/ONAP-XACML/pom.xml @@ -0,0 +1,88 @@ + + + + + + + 4.0.0 + + org.onap.policy.engine + PolicyEngineSuite + 1.1.0-SNAPSHOT + + ONAP-XACML + jar + + + org.onap.policy.engine + ${project.version} + PolicyEngineUtils + + + commons-cli + commons-cli + 1.2 + + + commons-io + commons-io + 2.4 + + + org.apache.httpcomponents + httpcore + 4.4.4 + + + junit + junit + 4.11 + test + + + org.mockito + mockito-core + 2.7.22 + + + org.springframework + spring-mock + 2.0.8 + + + commons-logging + commons-logging + + + + + com.mockrunner + mockrunner + 0.3.1 + + + com.att.research.xacml + xacml + 1.0.0 + + + diff --git a/ECOMP-XACML/sql/xacmlTest.mv.db b/ONAP-XACML/sql/xacmlTest.mv.db similarity index 100% rename from ECOMP-XACML/sql/xacmlTest.mv.db rename to ONAP-XACML/sql/xacmlTest.mv.db diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/XACMLErrorConstants.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/XACMLErrorConstants.java new file mode 100644 index 000000000..77c0da401 --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/XACMLErrorConstants.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.api; + +/** + * List of Error Classifications + * PE100 - Permissions + * PE200 - System Error (such as availability, timeout, configuration, etc...) + * PE300 - Data Issue( such as request for REST/JSON ) + * PE400 - Schema validation + * PE500 - Process Flow issues + * PE900 - Default/Unknown Errors + * + * + */ +public class XACMLErrorConstants { + //Captures all the errors related to Authentication, Authorizations and Permissions in the PolicyEngine Process + public static final String ERROR_PERMISSIONS = "PE100 - Permissions Error: "; + + //Captures all the errors related to availability, timeout configuration variables, etc... in the PolicyEngine + public static final String ERROR_SYSTEM_ERROR = "PE200 - System Error: "; + + /* + * Captures all the errors related to configuration values from properties files and data from the interfacing System + * like REST/JSON values + */ + public static final String ERROR_DATA_ISSUE = "PE300 - Data Issue: "; + + //Captures all the errors related to the XML schemas and/or REST/JSON structures + public static final String ERROR_SCHEMA_INVALID = "PE400 - Schema validation Error: "; + + //Captures all the errors related to the Process, when data from one Process to another Process does not flow + public static final String ERROR_PROCESS_FLOW = "PE500 - Process Flow Issue: "; + + //Captures all the errors that not related to the list of above error codes + public static final String ERROR_UNKNOWN = "PE900 - Unknown Error: "; + + +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactory.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactory.java new file mode 100644 index 000000000..bd9531532 --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/ONAPPapEngineFactory.java @@ -0,0 +1,38 @@ +package org.onap.policy.xacml.api.pap; + +import java.util.Properties; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.util.FactoryException; +import com.att.research.xacml.util.FactoryFinder; + +public abstract class ONAPPapEngineFactory{ + + /** + * Creates a new PAPEngineFactory instance using the given class name and the default thread class loader. + * + * @param factoryClassName the String name of the factory class to instantiate + * @return an instance of an object that extends ONAPPapEngineFactory to use in creating PAPPolicyEngine objects. + */ + public static ONAPPapEngineFactory newInstance(String factoryClassName) throws FactoryException { + return FactoryFinder.newInstance(factoryClassName, ONAPPapEngineFactory.class, null, true); + } + + /** + * Creates a new PAPPolicyEngine based on the configured ONAPPapEngineFactory. + * + * @return a new PAPPolicyEngine + * @throws PAPException + */ + public abstract PAPPolicyEngine newEngine() throws FactoryException, PAPException; + + /** + * Creates a new PAPPolicyEngine based on the configured ONAPPapEngineFactory. + * + * @return a new PAPPolicyEngine + * @throws PAPException + */ + public abstract PAPPolicyEngine newEngine(Properties properties) throws FactoryException, PAPException; + + +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPAPPolicy.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPAPPolicy.java new file mode 100644 index 000000000..78ce354e0 --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPAPPolicy.java @@ -0,0 +1,89 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.api.pap; + +import java.net.URI; +import java.util.List; +import java.util.Map; + +import org.onap.policy.xacml.std.pap.StdPAPPolicy; + +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import com.fasterxml.jackson.annotation.JsonSubTypes.Type; + +/* + * The following allows us to use Jackson to convert sub-types of this type into JSON and back to objects. + */ +@JsonTypeInfo( + use = JsonTypeInfo.Id.NAME, + include = JsonTypeInfo.As.PROPERTY, + property = "PAPPolicyType") +@JsonSubTypes({ + @Type(value = StdPAPPolicy.class, name = "StdPAPPolicy") }) +public interface OnapPAPPolicy { + + public String getPolicyName(); + public String getOldPolicyFileName(); + public String getPolicyDescription(); + public String getOnapName(); + public String getConfigName(); + public Map getDynamicFieldConfigAttributes(); + public Map getDynamicSettingsMap(); + public List getDynamicRuleAlgorithmLabels(); + public List getDynamicRuleAlgorithmCombo(); + public List getDynamicRuleAlgorithmField1(); + public List getDynamicRuleAlgorithmField2(); + public List getDynamicVariableList(); + public List getDataTypeList(); + public String getConfigBodyData(); + public String getPolicyID(); + public String getRuleID(); + public String getConfigType(); + public Boolean isEditPolicy(); + public Boolean isDraft(); + public String getVersion(); + public String getDomainDir(); + public String getConfigPolicyType(); + public String getJsonBody(); + public Integer getHighestVersion(); + public URI getLocation(); + public String getActionPerformer(); + public String getActionAttribute(); + public String getActionBody(); + public Map getDropDownMap(); + public String getActionDictHeader(); + public String getActionDictType(); + public String getActionDictUrl(); + public String getActionDictMethod(); + public String getServiceType(); + public String getUuid(); + public String getMsLocation(); + public String getPriority(); + public String getDeleteCondition(); + public String getDictionaryType(); + public String getDictionary(); + public String getDictionaryFields(); + + public String getRiskLevel(); + public String getGuard(); + public String getRiskType(); + public String getTTLDate(); +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDP.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDP.java new file mode 100644 index 000000000..65db0b980 --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDP.java @@ -0,0 +1,44 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.api.pap; + +import org.onap.policy.xacml.std.pap.StdPDP; + +import com.att.research.xacml.api.pap.PDP; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonSubTypes.Type; +import com.fasterxml.jackson.annotation.JsonTypeInfo; + +/* + * The following allows us to use Jackson to convert sub-types of this type into JSON and back to objects. + */ +@JsonTypeInfo( + use = JsonTypeInfo.Id.NAME, + include = JsonTypeInfo.As.PROPERTY, + property = "PDPType") +@JsonSubTypes({ + @Type(value = StdPDP.class, name = "StdPDP") }) +public interface OnapPDP extends PDP { + + public Integer getJmxPort(); + + public void setJmxPort(Integer jmxport); + +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDPGroup.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDPGroup.java new file mode 100644 index 000000000..3c9bdb355 --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/OnapPDPGroup.java @@ -0,0 +1,15 @@ +package org.onap.policy.xacml.api.pap; + +import java.util.Set; + +import com.att.research.xacml.api.pap.PDPGroup; +import com.att.research.xacml.api.pap.PDPPolicy; + +public interface OnapPDPGroup extends PDPGroup { + + public Set getOnapPdps(); + + public Set getSelectedPolicies(); + + public String getOperation(); +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/PAPPolicyEngine.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/PAPPolicyEngine.java new file mode 100644 index 000000000..4f1cfaf4b --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/api/pap/PAPPolicyEngine.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.api.pap; + +import java.io.InputStream; +import java.util.Set; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.api.pap.PDPStatus; + +public interface PAPPolicyEngine{ + + public OnapPDPGroup getDefaultGroup() throws PAPException; + + public void SetDefaultGroup(OnapPDPGroup group) throws PAPException; + + public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) throws PAPException, NullPointerException; + + public void newGroup(String name, String description) throws PAPException, NullPointerException; + + public OnapPDPGroup getGroup(String id) throws PAPException; + + public Set getOnapPDPGroups() throws PAPException; + + public OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException; + + public PDPStatus getStatus(OnapPDP pdp) throws PAPException; + + public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException; + + public void updatePDP(OnapPDP pdp) throws PAPException; + + public void removePDP(OnapPDP pdp) throws PAPException; + + public OnapPDP getPDP(String pdpId) throws PAPException; + + public void updateGroup(OnapPDPGroup group) throws PAPException; + + public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException, NullPointerException; + +public void publishPolicy(String id, String name, boolean isRoot, InputStream policy, OnapPDPGroup group) throws PAPException; + + // copy the given policy file into the group's directory, but do not include the policy in the group's policy set + public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException; + + public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException; + +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngine.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngine.java new file mode 100644 index 000000000..3132b8cac --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngine.java @@ -0,0 +1,1034 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.std.pap; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.TreeSet; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +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.PDPGroup; +import com.att.research.xacml.api.pap.PDPPIPConfig; +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.google.common.base.Joiner; +import com.google.common.base.Splitter; +import com.google.common.collect.Sets; + +/** + * This is a simple PAP engine that uses some property files and a simple directory + * structure in the file system to manage a policy repository and set of PDP nodes. + * + * + */ +public class StdEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine { + public static final String pipPropertyFile = "pip.properties"; + + private static Log logger = LogFactory.getLog(StdEngine.class); + + public static String PROP_PAP_REPO = "xacml.pap.pdps"; + public static String PROP_PAP_GROUPS = "xacml.pap.groups"; + public static String PROP_PAP_GROUPS_DEFAULT = "xacml.pap.groups.default"; + public static String PROP_PAP_GROUPS_DEFAULT_NAME = "default"; + //this value will be accessed from XacmlPapServlet so that we know if a default group did not exist + //and was just added. This way, we can add the new group to the database. + public boolean wasDefaultGroupJustAdded = false; + + protected final Path repository; + protected Set groups; + + public StdEngine() throws PAPException, IOException { + // + // Get the location in the file system of our repository + // + this.repository = Paths.get(XACMLProperties.getProperty(PROP_PAP_REPO)); + // + // Initialize + // + this.intialize(); + } + + public StdEngine(Properties properties) throws PAPException, IOException { + // + // Get the location in the file system of our repository + // + this.repository = Paths.get(properties.getProperty(PROP_PAP_REPO)); + // + // Initialize + // + this.intialize(); + } + + public StdEngine(Path repository) throws PAPException, IOException { + // + // Save our location + // + this.repository = repository; + // + // Initialize + // + this.intialize(); + } + + private void intialize() throws PAPException, IOException { + // + // Sanity check the repository path + // + if (this.repository == null) { + throw new PAPException ("No repository specified."); + } + if (Files.notExists(this.repository)) { + Files.createDirectory(repository); + } + if (Files.isDirectory(this.repository) == false) { + throw new PAPException ("Repository is NOT a directory: " + this.repository.toAbsolutePath()); + } + if (Files.isWritable(this.repository) == false) { + throw new PAPException ("Repository is NOT writable: " + this.repository.toAbsolutePath()); + } + // + // Load our groups + // + this.loadGroups(); + } + + private void loadGroups() throws PAPException { + // + // Create a properties object + // + Properties properties = new Properties(); + Path file = Paths.get(this.repository.toString(), XACMLProperties.XACML_PROPERTIES_NAME); + try { + // + // Load the properties + // + try (InputStream is = new FileInputStream(file.toFile())) { + properties.load(is); + } + + // + // Parse it + // + this.groups = this.readProperties(this.repository, properties); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to load properties file"); + this.groups = new HashSet<>(); + } + // + // Initialize the default group + // + PDPGroup defaultGroup = this.initializeDefaultGroup(file, properties); + logger.info("Default group is: " + defaultGroup.getId() + "=" + defaultGroup.getName()); + } + + private PDPGroup initializeDefaultGroup(Path file, Properties properties) throws PAPException { + wasDefaultGroupJustAdded = false; + // + // Make sure we have the default group + // + PDPGroup group = this.getDefaultGroup(); + if (group != null) { + return group; + } + // + // We don't have the default group, create it + // + String defaultId = properties.getProperty(PROP_PAP_GROUPS_DEFAULT, PROP_PAP_GROUPS_DEFAULT_NAME); + if(defaultId == null){ + defaultId = PROP_PAP_GROUPS_DEFAULT_NAME; + } + if(defaultId.equals("")){ + defaultId = PROP_PAP_GROUPS_DEFAULT_NAME; + } + //we're going to check one more time in case the PROP_PAP_GROUPS_DEFAULT_NAME doesn't exist + if(defaultId == null){ + defaultId = "default"; + } + if(defaultId.equals("")){ + defaultId = "default"; + } + logger.warn("Default group does NOT exist, creating " + defaultId); + Path defaultPath = Paths.get(this.repository.toString(), defaultId); + try { + // + // Does it exist? + // + if (Files.notExists(defaultPath)) { + // + // Create its directory + // + Files.createDirectory(defaultPath); + // + // Create property files + // + { + Properties props = new Properties(); + props.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, ""); + props.setProperty(XACMLProperties.PROP_ROOTPOLICIES, ""); + Path policyPath = Paths.get(defaultPath.toAbsolutePath().toString(), "xacml.policy.properties"); + Files.createFile(policyPath); + try (OutputStream os = Files.newOutputStream(policyPath)) { + props.store(os, ""); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to write default policy properties"); + } + } + { + Properties props = new Properties(); + props = setPIPProperties(props); + Path pipPath = Paths.get(defaultPath.toAbsolutePath().toString(), "xacml.pip.properties"); + Files.createFile(pipPath); + try (OutputStream os = Files.newOutputStream(pipPath)) { + props.store(os, ""); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to write default pip properties"); + } + } + } + // + // Create the default group + // + StdPDPGroup newDefault = new StdPDPGroup(defaultId, true, "default", "The default group where new PDP's are put.", defaultPath); + // + // Add it to our list + // + this.groups.add(newDefault); + // + // Save our properties out since we have + // a new default group. + // + StdEngine.setGroupProperties(newDefault, properties); + // + // Save it to disk + // + try { + try (OutputStream os = Files.newOutputStream(file)) { + properties.store(os, ""); + } + } catch (IOException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdEngine", "Failed to save properties with new default group information."); + } + // + // Return it + // + wasDefaultGroupJustAdded = true; + return newDefault; + } catch (IOException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdEngine", "Failed to create default group"); + throw new PAPException("Failed to create default group"); + } + } + + @Override + public OnapPDPGroup getDefaultGroup() throws PAPException{ + for (OnapPDPGroup group : this.groups) { + if (group.isDefaultGroup()) { + return group; + } + } + // + // Default group doesn't exist + // + return null; + } + + @Override + public OnapPDPGroup getGroup(String id) throws PAPException { + for (OnapPDPGroup g: this.groups) { + if (g.getId().equals(id)) { + return g; + } + } + return null; + } + + @Override + public void newGroup(String name, String description) throws PAPException, NullPointerException{ + // + // Null check + // + if (name == null) { + throw new NullPointerException(); + } + // + // Do we already have this group? + // + for (PDPGroup group : this.groups) { + if (group.getName().equals(name)) { + throw new PAPException("Group with this name=" + name + " already exists."); + } + } + + + // create an Id that can be used as a file name and a properties file key. + // Ids must not contain \/:*?"<>|=,; + // The ID must also be unique within the current set of PDPGroups. + String id = createNewPDPGroupId(name); + + + // + // Construct the directory path + // + Path groupPath = Paths.get(this.repository.toString(), id); + // + // If it exists already + // + if (Files.exists(groupPath)) { + logger.warn("addGroup " + id + " directory exists" + groupPath.toString()); + } else { + try { + // + // Create the directory + // + Files.createDirectory(groupPath); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to create " + groupPath); + throw new PAPException("Failed to create " + id); + } + } + // + // Create the Policies + // + + Path policyProperties = Paths.get(groupPath.toString(), "xacml.policy.properties"); + if (Files.exists(policyProperties)) { + logger.warn("addGroup " + id + " file exists: " + policyProperties.toString()); + } else { + Properties props = new Properties(); + props.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, ""); + props.setProperty(XACMLProperties.PROP_ROOTPOLICIES, ""); + try { + Files.createFile(policyProperties); + try (OutputStream os = Files.newOutputStream(policyProperties)) { + props.store(os, ""); + } + } catch (IOException e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "StdEngine", "Failed to create " + policyProperties); + throw new PAPException("Failed to create " + id); + } + } + // + // Create the PIP config + // + Path pipProperties = Paths.get(groupPath.toString(), "xacml.pip.properties"); + Properties props = new Properties(); + if (Files.exists(pipProperties)) { + logger.warn("addGroup " + id + " file exists: " + pipProperties.toString()); + } else { + try { + props = setPIPProperties(props); + Files.createFile(pipProperties); + try (OutputStream os = Files.newOutputStream(pipProperties)) { + props.store(os, ""); + } + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to create " + pipProperties); + throw new PAPException("Failed to create " + id); + } + + } + // + // Ok now add it + // + StdPDPGroup newGroup = new StdPDPGroup(id, name, description, groupPath); + // Add the default PIP configuration. + String list = props.getProperty(XACMLProperties.PROP_PIP_ENGINES); + if (list != null && list.length() > 0) { + Set pipConfigs = new HashSet<>(); + for (String pipID : list.split("[,]")) { + StdPDPPIPConfig config = new StdPDPPIPConfig(pipID, props); + if (config.isConfigured()) { + pipConfigs.add(config); + } + } + newGroup.setPipConfigs(pipConfigs); + } + if (this.groups.add(newGroup)) { + // save the new group in our properties and notify any listeners of the change + groupChanged(newGroup); + } + + } + + + + + /** + * Helper to create a new Group ID. + * Use the Name field to create the Id. + * The Name is expected to not be null; if it is then this method throws an exception. + * The name is supposed to be unique within the current set of groups, + * so creating the ID based on the name will create a unique string. + * + * @param name + * @return + */ + private String createNewPDPGroupId(String name) { + String id = name; + // replace "bad" characters with sequences that will be ok for file names and properties keys. + id = id.replace(" ", "_sp_"); + id = id.replace("\t", "_tab_"); + id = id.replace("\\", "_bksl_"); + id = id.replace("/", "_sl_"); + id = id.replace(":", "_col_"); + id = id.replace("*", "_ast_"); + id = id.replace("?", "_q_"); + id = id.replace("\"", "_quo_"); + id = id.replace("<", "_lt_"); + id = id.replace(">", "_gt_"); + id = id.replace("|", "_bar_"); + id = id.replace("=", "_eq_"); + id = id.replace(",", "_com_"); + id = id.replace(";", "_scom_"); + + return id; + } + + + @Override + public OnapPDP getPDP(String pdpId) throws PAPException { + for (OnapPDPGroup group : this.groups) { + for (OnapPDP pdp : group.getOnapPdps()) { + if (pdp.getId().equals(pdpId)) { + return pdp; + } + } + } + return null; + } + + + @Override + public void movePDP(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException { + if (newGroup == null) { + throw new NullPointerException("You must specify which group the PDP will belong to."); + } + PDPGroup currentGroup = this.getPDPGroup(pdp); + if (currentGroup == null) { + throw new PAPException("PDP must already belong to a group."); + } + if (currentGroup.equals(newGroup)) { + logger.warn("Already in that group."); + return; + } + if (currentGroup instanceof StdPDPGroup && newGroup instanceof StdPDPGroup) { + if (((StdPDPGroup) currentGroup).removePDP(pdp)) { + boolean result = ((StdPDPGroup) newGroup).addPDP(pdp); + if (result) { + // + // Save the configuration + // + this.doSave(); + } else { + PolicyLogger.error("Failed to add to new group, putting back into original group."); + if (((StdPDPGroup) currentGroup).removePDP(pdp) == false) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Failed to put PDP back into original group."); + } + } + } + } else { + String message = "Unknown PDP group class: " + newGroup.getClass().getCanonicalName() + " and " + currentGroup.getClass().getCanonicalName(); + logger.warn(message); + throw new PAPException(message); + } + } + + + @Override + public void updatePDP(OnapPDP pdp) throws PAPException { + PDP currentPDP = this.getPDP(pdp.getId()); + if (currentPDP == null) { + String message = "Unknown PDP id '" + pdp.getId() + "'"; + logger.warn(message); + throw new PAPException(message); + } + + // the only things that the user can change are name and description + currentPDP.setDescription(pdp.getDescription()); + currentPDP.setName(pdp.getName()); + if (currentPDP instanceof OnapPDP && pdp instanceof OnapPDP) { + ((OnapPDP)currentPDP).setJmxPort(((OnapPDP)pdp).getJmxPort()); + } + this.doSave(); + } + + @Override + public void removePDP(OnapPDP pdp) throws PAPException { + PDPGroup group = this.getPDPGroup(pdp); + if (group == null) { + throw new NullPointerException(); + } + if (group instanceof StdPDPGroup) { + boolean result = ((StdPDPGroup) group).removePDP(pdp); + if (result) { + this.doSave(); + } + return; + } + String message = "Unknown PDP group class: " + group.getClass().getCanonicalName(); + logger.warn(message); + throw new PAPException(message); + } + + + @Override + /** + * Should never be called - Detailed status is held on the PDP, not the PAP + */ + public PDPStatus getStatus(OnapPDP pdp) throws PAPException { + return getPDP(pdp.getId()).getStatus(); + } + + @Override + public void publishPolicy(String id, String name, boolean isRoot, InputStream policy, OnapPDPGroup group) throws PAPException { + if (group == null) { + throw new NullPointerException(); + } + if (group instanceof StdPDPGroup && this.groups.contains(group)) { + ((StdPDPGroup) group).publishPolicy(id, name, isRoot, policy); + return; + } + logger.warn("unknown PDP Group: " + group); + throw new PAPException("Unknown PDP Group: " + group.getId()); + } + + // Currently not used on the PAP side. This is done by ((StdPDPGroup) group).copyPolicyToFile + @Override + public void copyPolicy(PDPPolicy policy, OnapPDPGroup group) + throws PAPException { + } + + + @Override + public void removePolicy(PDPPolicy policy, OnapPDPGroup group) throws PAPException { + if (group == null) { + throw new NullPointerException(); + } + if (group instanceof StdPDPGroup && this.groups.contains(group)) { + ((StdPDPGroup) group).removePolicy(policy); + return; + } + logger.warn("unknown PDP Group: " + group); + throw new PAPException("Unknown PDP Group: " + group.getId()); + } + + + // + // HELPER methods + // + + private Set readProperties(Path repository, Properties properties) throws PAPException { + Set groups = new HashSet<>(); + // + // See if there is a groups property + // + String groupList = properties.getProperty(PROP_PAP_GROUPS, ""); + if (groupList == null) { + logger.warn("null group list " + PROP_PAP_GROUPS); + groupList = ""; + } + if (logger.isDebugEnabled()) { + logger.debug("group list: " + groupList); + } + // + // Iterate the groups, converting to a set ensures we have unique groups. + // + for (String id : Splitter.on(',').trimResults().omitEmptyStrings().split(groupList)) { + // + // Add our Group Object + // + StdPDPGroup g = new StdPDPGroup(id.trim(), + id.equals(properties.getProperty(PROP_PAP_GROUPS_DEFAULT, PROP_PAP_GROUPS_DEFAULT_NAME)), + properties, + Paths.get(repository.toString(), id)); + + // + // Add it in + // + groups.add(g); + } + // + // Dump what we got + // + if (logger.isDebugEnabled()) { + logger.debug("PDP Group List: " + groups.toString()); + } + return groups; + } + + private void saveConfiguration() throws PAPException, IOException { + // + // Create our properties object + // + Properties properties = new Properties() { + private static final long serialVersionUID = 1L; + // For Debugging it is helpful for the file to be in a sorted order, + // any by returning the keys in the natural Alpha order for strings we get close enough. + // TreeSet is sorted, and this just overrides the normal Properties method to get the keys. + @Override + public synchronized Enumeration keys() { + return Collections.enumeration(new TreeSet(super.keySet())); + } + }; + // + // Iterate our groups + // + List ids = new ArrayList<>(); + for (PDPGroup group : this.groups) { + ids.add(group.getId()); + properties.setProperty(group.getId() + ".name", (group.getName() == null ? "" : group.getName())); + properties.setProperty(group.getId() + ".description", (group.getDescription() == null ? "" : group.getDescription())); + // + // Iterate its PDPs + // + List pdps = new ArrayList<>(); + for (PDP pdp : group.getPdps()) { + pdps.add(pdp.getId()); + properties.setProperty(pdp.getId() + ".name", (pdp.getName() == null ? "" : pdp.getName())); + properties.setProperty(pdp.getId() + ".description", (pdp.getDescription() == null ? "" : pdp.getDescription())); + if (pdp instanceof OnapPDP) { + properties.setProperty(pdp.getId() + ".jmxport", (((OnapPDP)pdp).getJmxPort()==0 ? "" : ((OnapPDP)pdp).getJmxPort()).toString()); + } + } + String pdpList = ""; + if (pdps.size() == 1) { + pdpList = pdps.get(0); + } else if (pdps.size() > 1) { + pdpList = Joiner.on(',').skipNulls().join(pdps); + } + if (logger.isDebugEnabled()) { + logger.debug("Group " + group.getId() + " PDPS: " + pdpList); + } + properties.setProperty(group.getId() + ".pdps", pdpList); + } + if (ids.isEmpty()) { + throw new PAPException("Inconsistency - we have NO groups. We should have at least one."); + } + String groupList = ""; + if (ids.size() == 1) { + groupList = ids.get(0); + } else if (ids.size() > 1){ + groupList = Joiner.on(',').skipNulls().join(ids); + } + logger.info("New Group List: " + groupList); + + properties.setProperty(PROP_PAP_GROUPS, groupList); + // + // Get the default group + // + PDPGroup defaultGroup = this.getDefaultGroup(); + if (defaultGroup == null) { + throw new PAPException("Invalid state - no default group."); + } + properties.setProperty(PROP_PAP_GROUPS_DEFAULT, defaultGroup.getId()); + // + // Now we can save the file + // + Path file = Paths.get(this.repository.toString(), "xacml.properties"); + try (OutputStream os = Files.newOutputStream(file)) { + properties.store(os, ""); + } + } + + public static void removeGroupProperties(String id, Properties properties) { + for (Object key : properties.keySet()) { + if (key.toString().startsWith(id + ".")) { + properties.remove(key); + } + } + } + + public static void setGroupProperties(PDPGroup group, Properties properties) { + // + // make sure its in the list of groups + // + Iterable groups = Splitter.on(',').trimResults().omitEmptyStrings().split( properties.getProperty(PROP_PAP_GROUPS, "")); + boolean inList = false; + for (String g : groups) { + if (g.equals(group.getId())) { + inList = true; + } + } + if (inList == false) { + Set grps = Sets.newHashSet(groups); + grps.add(group.getId()); + String newGroupList = "";; + if (grps.size() == 1) { + newGroupList = grps.iterator().next(); + } else if (grps.size() > 1) { + newGroupList = Joiner.on(',').skipNulls().join(grps); + } + logger.info("New Group List: " + newGroupList); + properties.setProperty(PROP_PAP_GROUPS, newGroupList); + } + // + // Set its properties + // + properties.setProperty(group.getId() + ".name", group.getName()); + properties.setProperty(group.getId() + ".description", group.getDescription()); + // + // Set its PDP list + // + if (group.getPdps().size() > 0) { + String pdpList = ""; + if (group.getPdps().size() == 1) { + pdpList = group.getPdps().iterator().next().getId(); + } else if (group.getPdps().size() > 1) { + Set ids = new HashSet<>(); + for (PDP pdp : group.getPdps()) { + ids.add(pdp.getId()); + } + pdpList = Joiner.on(',').skipNulls().join(ids); + } + properties.setProperty(group.getId() + ".pdps", pdpList); + } else { + properties.setProperty(group.getId() + ".pdps", ""); + } + } + + + public void changed() { + if (logger.isDebugEnabled()) { + logger.debug("changed"); + } + this.doSave(); + this.fireChanged(); + } + + public void groupChanged(OnapPDPGroup group) { + if (logger.isDebugEnabled()) { + logger.debug("groupChanged: " + group); + } + this.doSave(); + this.firePDPGroupChanged(group); + } + + + public void pdpChanged(OnapPDP pdp) { + if (logger.isDebugEnabled()) { + logger.debug("pdpChanged: " + pdp); + } + this.doSave(); + this.firePDPChanged(pdp); + } + + private void doSave() { + try { + // + // Save the configuration + // + this.saveConfiguration(); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdEngine", "Failed to save configuration"); + } catch (PAPException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdEngine", "Failed to save configuration"); + } + } + + private Properties setPIPProperties(Properties props){ + props.setProperty(XACMLProperties.PROP_PIP_ENGINES, "AAF"); + props.setProperty("AAF.name", "AAFEngine"); + props.setProperty("AAF.description", "AAFEngine to communicate with AAF to take decisions"); + props.setProperty("AAF.classname","org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine"); + // read from PIP properties file. + Path file = Paths.get(pipPropertyFile); + if (!Files.notExists(file)) { + InputStream in; + Properties prop = new Properties(); + try { + in = new FileInputStream(file.toFile()); + prop.load(in); + } catch (IOException e) { + PolicyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "can not load the pip properties from file" +e); + } + props = prop; + } + return props; + } + + + @Override + public Set getOnapPDPGroups() throws PAPException { + final Set grps = new HashSet<>(); + for (OnapPDPGroup g : this.groups) { + grps.add(g); + } + return Collections.unmodifiableSet(grps); + } + + @Override + public OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException { + for (OnapPDPGroup group : this.groups) { + if (group.getPdps().contains(pdp)) { + return group; + } + } + return null; + } + + @Override + public void SetDefaultGroup(OnapPDPGroup group) throws PAPException { + boolean changesMade = false; + for (OnapPDPGroup aGroup : groups) { + if (aGroup.getId().equals(group.getId())) { + if ( ! aGroup.isDefaultGroup()) { + if (aGroup instanceof StdPDPGroup) { + ((StdPDPGroup) aGroup).setDefault(true); + changesMade = true; + } else { + throw new IllegalArgumentException("Group in groups of unknown type '" + aGroup.getClass().getName() + "'"); + } + } + } else { + // not the new default group + if (aGroup.isDefaultGroup()) { + if (aGroup instanceof StdPDPGroup) { + ((StdPDPGroup) aGroup).setDefault(false); + changesMade = true; + } else { + throw new IllegalArgumentException("Group in groups of unknown type '" + aGroup.getClass().getName() + "'"); + } + } + } + } + if (changesMade) { + this.doSave(); + } + + return; + + } + + @Override + public void newPDP(String id, OnapPDPGroup group, String name, String description, int jmxport) + throws PAPException, NullPointerException { + if (group == null) { + throw new PAPException("You must specify which group the PDP will belong to."); + } + if (this.groups.contains(group) == false) { + throw new PAPException("Unknown group, not in our list."); + } + for (OnapPDP p : group.getOnapPdps()) { + if (p.getId().equals(id)) { + throw new PAPException("A PDP with this ID exists."); + } + } + if (group instanceof StdPDPGroup) { + StdPDP pdp = new StdPDP(id, name, description, jmxport); + if (((StdPDPGroup) group).addPDP(pdp)) { + // + // Save the properties and notify any listeners + // + pdpChanged(pdp); + return; + } + } + return; + + } + + @Override + public void updateGroup(OnapPDPGroup group) throws PAPException { + if (group == null || group.getId() == null) { + throw new PAPException("Group or id is null"); + } + if (group.getName() == null || group.getName().trim().length() == 0) { + throw new PAPException("New name for group cannot be null or blank"); + } + StdPDPGroup existingGroup = (StdPDPGroup)getGroup(group.getId()); + if (existingGroup == null) { + throw new PAPException("Update found no existing group with id '" + group.getId() + "'"); + } + + + // We do dramatically different things when the Name changes + // because the Name is essentially the identity of the group (as the User knows it) so when the Identity changes we have to change the group ID. + if (group.getName().equals(existingGroup.getName())) { + + // update the disk + try { + ((StdPDPGroup)group).saveGroupConfiguration(); + } catch (IOException e) { + throw new PAPException("Unable to save new configuration for '" + group.getName() + "': " + e.getMessage()); + } + // update the group in the set by simply replacing the old instance with the new one + this.groups.remove(existingGroup); + this.groups.add((StdPDPGroup)group); + + } else { + // the name/identity of the group has changed + // generate the new id + String newId = createNewPDPGroupId(group.getName()); + + // make sure no other group uses the new id + for (OnapPDPGroup g : groups) { + if (g.getId().equals(newId)) { + throw new PAPException("Replacement name maps to ID '" + newId + "' which is already in use"); + } + } + ((StdPDPGroup)group).setId(newId); + + // rename the existing directory to the new id + Path oldPath = existingGroup.getDirectory(); + Path newPath = Paths.get(oldPath.getParent().toString(), newId); + ((StdPDPGroup)group).setDirectory(newPath); + + try { + boolean success = oldPath.toFile().renameTo(newPath.toFile()); + if ( ! success) { + throw new PAPException("Unable to rename directory; reason unknown"); + } + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdEngine", "Unable to rename directory"); + throw new PAPException("Unable to move directory from '" + oldPath + "' to '" + newPath + "': " + e.getMessage()); + } + // update the disk + try { + ((StdPDPGroup)group).saveGroupConfiguration(); + } catch (IOException e) { + throw new PAPException("Unable to save new configuration for '" + group.getName() + "': " + e.getMessage()); + } + + // save the new group into the Set + groups.remove(existingGroup); + groups.add((StdPDPGroup)group); + + } + + // perhaps only the group changed, but if the name/id changed it may look to a listener like more than one group + changed(); + + + } + + @Override + public void removeGroup(OnapPDPGroup group, OnapPDPGroup newGroup) throws PAPException, NullPointerException { + if (group == null) { + throw new NullPointerException(); + } + // + // Does this group exist? + // + if (this.groups.contains(group) == false) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "This group doesn't exist."); + throw new PAPException("The group '" + group.getId() + "' does not exist"); + } + // + // Is it the default group? + // + if (group.isDefaultGroup()) { + throw new PAPException("You cannot delete the default group."); + } + Set pdps = group.getOnapPdps(); + // + // Are there PDPs? If so, then we need a target group + // + if (pdps.isEmpty() == false && newGroup == null) { + throw new NullPointerException("Group targeted for deletion has PDPs, you must provide a new group for them."); + } + // + // Move the PDPs + // + if (pdps.isEmpty() == false) { + if (! (newGroup instanceof StdPDPGroup)) { + throw new PAPException("Unexpected class for newGroup: " + newGroup.getClass().getCanonicalName()); + } + // The movePDP function will modify the set of PDPs in the group. + // To avoid concurrent modification exceptions we need to duplicate the list before calling that function. + List pdpList = new ArrayList<>(); + for (OnapPDP pdp : pdps) { + pdpList.add(pdp); + } + // now we can use the PDPs from the list without having ConcurrentAccessExceptions + for (OnapPDP pdp : pdpList) { + this.movePDP(pdp, newGroup); + } + } + // + // remove the directory for the group + // + String id = group.getId(); + Path groupPath = Paths.get(this.repository.toString(), id); + // + // If it exists already + // + if ( ! Files.exists(groupPath)) { + logger.warn("removeGroup " + id + " directory does not exist" + groupPath.toString()); + } else { + try { + Files.walkFileTree(groupPath, new SimpleFileVisitor() { + + @Override + public FileVisitResult visitFile(Path file, + BasicFileAttributes attrs) throws IOException { + Files.delete(file); + return super.visitFile(file, attrs); + } + + }); + // + // delete the directory + // + Files.delete(groupPath); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdEngine", "Failed to delete " + groupPath); + throw new PAPException("Failed to delete " + id); + } + } + + // remove the group from the set of all groups + groups.remove(group); + + // + // Save changes + // + changed(); + this.doSave(); + return; + + } + +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngineFactory.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngineFactory.java new file mode 100644 index 000000000..ee6785611 --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdEngineFactory.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.std.pap; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + +import java.io.IOException; +import java.util.Properties; + +import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory; +import org.onap.policy.xacml.api.pap.PAPPolicyEngine; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.util.FactoryException; + +public class StdEngineFactory extends ONAPPapEngineFactory { + + @Override + public PAPPolicyEngine newEngine() throws FactoryException, PAPException { + try { + return (PAPPolicyEngine) new StdEngine(); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "StdEngineFactory", "Failed to create engine"); + return null; + } + } + + @Override + public PAPPolicyEngine newEngine(Properties properties) throws FactoryException, + PAPException { + try { + return (PAPPolicyEngine) new StdEngine(properties); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "StdEngineFactory", "Failed to create engine"); + return null; + } + } + +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java new file mode 100644 index 000000000..d69f38d95 --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPAPPolicy.java @@ -0,0 +1,910 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.std.pap; + +import java.io.Serializable; +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.onap.policy.xacml.api.pap.OnapPAPPolicy; + +public class StdPAPPolicy implements OnapPAPPolicy, Serializable{ + private static final long serialVersionUID = 5260230629397322000L; + + private String policyName = null; + private String oldPolicyFileName = null; + private String policyDescription = null; + private String onapName = null; + private String configName = null; + private Map dyanamicFieldConfigAttributes = new HashMap<>(); + private Map dropDownMap = new HashMap<>(); + private Map dynamicSettingsMap = new HashMap<>(); + private List dynamicRuleAlgorithmLabels; + private List dynamicRuleAlgorithmCombo; + private List dynamicRuleAlgorithmField1; + private List dynamicRuleAlgorithmField2; + private List dynamicVariableList; + private List dataTypeList; + private String configBodyData = null; + private String policyID = null; + private String ruleID = null; + private String brmsController; + private ArrayList brmsDependency; + private String configType = null; + private Boolean editPolicy = false; + private Boolean draft = false; + private String version = null; + private String domain = null; + private String configPolicyType = null; + private String jsonBody = null; + private String serviceType = null; + private Integer highestVersion = null; + private URI location = null; + private String actionPerformer = null; + private String actionAttribute = null; + private String actionBody = null; + private String actionDictHeader = null; + private String actionDictType = null; + private String actionDictUrl = null; + private String actionDictMethod = null; + private String uuid = null; + private String msLocation = null; + private String priority = null; + private Map drlRuleAndUIParams=null; + private String deleteCondition = null; + private String dictionaryType = null; + private String dictionary = null; + private String dictionaryFields = null; + private String providerComboBox = null; + private String riskType = null; + private String guard = null; + private String riskLevel; + private String ttlDate = null; + + + public StdPAPPolicy() { + + } + + //Constructor for sending location when pushing policies + public StdPAPPolicy(URI location) { + this.location = location; + } + + //Constructor for Validating Config Policies + public StdPAPPolicy(String policyName, String body, String configType, String configPolicyType) { + this.policyName = policyName; + this.configBodyData = body; + this.configType = configType; + this.configPolicyType = configPolicyType; + } + + //convenience constructor + public StdPAPPolicy(String configPolicyType, String policyName, String description, String onapName, String configName, Map attributes, String configType, + String body, Boolean editPolicy, String domain, String riskLevel, String riskType, String guard, String ttlDate){ + this(configPolicyType, policyName, description, onapName, configName, attributes, configType, + body, editPolicy, domain, 1, riskLevel, riskType, guard, ttlDate); + } + + //Constructor for Create/Update Action Policies from API + public StdPAPPolicy(String policyName, String description, Map attributes, List dynamicRuleAlgorithmLabels, List dynamicRuleAlgorithmCombo, + List dynamicRuleAlgorithmField1, List dynamicRuleAlgorithmField2, String actionPerformer,String actionAttribute, Boolean editPolicy, + String domain, int highestVersion) { + + this.policyName = policyName; + this.policyDescription = description; + this.dyanamicFieldConfigAttributes = attributes; + this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; + this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; + this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; + this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; + this.actionPerformer = actionPerformer; + this.actionAttribute = actionAttribute; + this.editPolicy = editPolicy; + this.domain = domain; + this.highestVersion = highestVersion; + + } + + //Constructor for Create/Update Decision Policies from Admin Console + public StdPAPPolicy(String policyName, String description, String onapName, String providerComboBox, Map attributes, Map settings, + List dynamicRuleAlgorithmLabels, List dynamicRuleAlgorithmCombo, List dynamicRuleAlgorithmField1, + List dynamicRuleAlgorithmField2, Map dropDownMap, List dynamicVariableList, + List dataTypeList, Boolean editPolicy, String domain, int highestVersion) { + + this.policyName = policyName; + this.policyDescription = description; + this.onapName = onapName; + this.setProviderComboBox(providerComboBox); + this.dyanamicFieldConfigAttributes = attributes; + this.dynamicSettingsMap = settings; + this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; + this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; + this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; + this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; + this.dynamicVariableList = dynamicVariableList; + this.dataTypeList = dataTypeList; + this.dropDownMap = dropDownMap; + this.editPolicy = editPolicy; + this.domain = domain; + this.highestVersion = highestVersion; + + } + + + //Constructor for Create Config Policies from API and Admin Console + //Constructor for Updating Config Policies from the API + public StdPAPPolicy(String configPolicyType, String policyName, String description, String onapName, String configName, Map attributes, String configType, + String body, Boolean editPolicy, String domain, int highestVersion, String riskLevel, String riskType, String guard, String ttlDate) { + + this.configPolicyType = configPolicyType; + this.policyName = policyName; + this.policyDescription = description; + this.onapName = onapName; + this.configName = configName; + this.dyanamicFieldConfigAttributes = attributes; + this.configType = configType; + this.configBodyData = body; + this.editPolicy = editPolicy; + this.domain = domain; + this.highestVersion = highestVersion; + this.riskLevel = riskLevel; + this.riskType = riskType; + this.guard = guard; + this.ttlDate = ttlDate; + } + + //convenience constructor + public StdPAPPolicy (String configPolicyType, String policyName, String description, String onapName, String configName, Map attributes, String body, String policyID, + String ruleID, String configType, Boolean editPolicy, String version, String domain, String riskLevel, String riskType, String guard, String ttlDate) { + this (configPolicyType, policyName, description, onapName, configName, attributes, body, policyID, + ruleID, configType, editPolicy, version, domain, 1, riskLevel, riskType, guard, ttlDate); + } + + //Constructor for Updating Config Policies from Admin Console + public StdPAPPolicy (String configPolicyType, String policyName, String description, String onapName, String configName, Map attributes, String body, String policyID, + String ruleID, String configType, Boolean editPolicy, String version, String domain, int highestVersion, String riskLevel, String riskType, String guard, String ttlDate) { + + this.configPolicyType = configPolicyType; + this.policyName = policyName; + this.policyDescription = description; + this.onapName = onapName; + this.configName = configName; + this.dyanamicFieldConfigAttributes = attributes; + this.configBodyData = body; + this.policyID = policyID; + this.ruleID = ruleID; + this.configType = configType; + this.editPolicy = editPolicy; + this.version = version; + this.domain = domain; + this.highestVersion = highestVersion; + this.riskLevel = riskLevel; + this.riskType = riskType; + this.guard = guard; + this.ttlDate = ttlDate; + } + + + //Constructor for Creating Config Firewall Policies + public StdPAPPolicy (String configPolicyType, String policyName, String description, String configName, + Boolean editPolicy, String domain, String jsonBody, Integer highestVersion, String riskLevel, String riskType, String guard, String ttlDate) { + + this.configPolicyType = configPolicyType; + this.policyName = policyName; + this.policyDescription = description; + this.configName = configName; + this.editPolicy = editPolicy; + this.domain = domain; + this.jsonBody = jsonBody; + this.highestVersion = highestVersion; + this.riskLevel = riskLevel; + this.riskType = riskType; + this.guard = guard; + this.ttlDate = ttlDate; + + } + + //Constructor for Creating Goc Policies + public StdPAPPolicy (String configPolicyType, String policyName, String description, String configName, + Boolean editPolicy, String domain, String jsonBody, Integer highestVersion, String eCompName, String riskLevel, String riskType, String guard, String ttlDate) { + + this.configPolicyType = configPolicyType; + this.policyName = policyName; + this.policyDescription = description; + this.configName = configName; + this.editPolicy = editPolicy; + this.domain = domain; + this.jsonBody = jsonBody; + this.highestVersion = highestVersion; + this.onapName=eCompName; + this.riskLevel = riskLevel; + this.riskType = riskType; + this.guard = guard; + this.ttlDate = ttlDate; + } + + //Constructor for Creating BRMS Policies from the Admin Console + public StdPAPPolicy (String configPolicyType, String policyName, String description, + String configName, Boolean editPolicy, String domain, + Map dyanamicFieldConfigAttributes, Integer highestVersion, String eCompName, + String configBodyData, String riskLevel, String riskType, String guard, String ttlDate, String brmsController, ArrayList brmsDependency) { + + this.configPolicyType = configPolicyType; + this.policyName = policyName; + this.policyDescription = description; + this.configName = configName; + this.editPolicy = editPolicy; + this.domain = domain; + this.dyanamicFieldConfigAttributes = dyanamicFieldConfigAttributes; + this.highestVersion = highestVersion; + this.onapName=eCompName; + this.configBodyData=configBodyData; + this.riskLevel = riskLevel; + this.riskType = riskType; + this.guard = guard; + this.ttlDate = ttlDate; + this.brmsController = brmsController; + this.brmsDependency = brmsDependency; + } + + //Constructor for Creating BRMS Param Policies from the Admin Console + public StdPAPPolicy (String configPolicyType, String policyName, String description, + String configName, Boolean editPolicy, String domain, + Map dyanamicFieldConfigAttributes, Integer highestVersion, String eCompName, + String configBodyData,Map drlRuleAndUIParams, String riskLevel, String riskType, String guard, String ttlDate, String brmsController, ArrayList brmsDependency) { + + this.configPolicyType = configPolicyType; + this.policyName = policyName; + this.policyDescription = description; + this.configName = configName; + this.editPolicy = editPolicy; + this.domain = domain; + this.dyanamicFieldConfigAttributes = dyanamicFieldConfigAttributes; + this.highestVersion = highestVersion; + this.onapName=eCompName; + this.configBodyData=configBodyData; + this.drlRuleAndUIParams=drlRuleAndUIParams; + this.riskLevel = riskLevel; + this.riskType = riskType; + this.guard = guard; + this.ttlDate = ttlDate; + this.brmsController = brmsController; + this.brmsDependency = brmsDependency; + } + + //Constructor for Creating CloseLoop_Fault and Performance Metric Policies + public StdPAPPolicy (String configPolicyType, String policyName, String description, String onapName, + String jsonBody, Boolean draft, String oldPolicyFileName, String serviceType, Boolean editPolicy, + String domain, Integer highestVersion, String riskLevel, String riskType, String guard, String ttlDate) { + + this.configPolicyType = configPolicyType; + this.policyName = policyName; + this.policyDescription = description; + this.onapName = onapName; + this.jsonBody = jsonBody; + this.draft = draft; + this.oldPolicyFileName = oldPolicyFileName; + this.serviceType = serviceType; + this.editPolicy = editPolicy; + this.domain = domain; + this.highestVersion = highestVersion; + this.riskLevel = riskLevel; + this.riskType = riskType; + this.guard = guard; + this.ttlDate = ttlDate; + } + + //Constructor for Updating Config Firewall Policies from the Admin Console + public StdPAPPolicy (String configPolicyType, String policyName, String description, String configName, Boolean editPolicy, String domain, String policyID, + String ruleID, String version, String jsonBody, Integer highestVersion, String riskLevel, String riskType, String guard, String ttlDate) { + + this.configPolicyType = configPolicyType; + this.policyName = policyName; + this.policyDescription = description; + this.configName = configName; + this.editPolicy = editPolicy; + this.domain = domain; + this.policyID = policyID; + this.ruleID = ruleID; + this.version = version; + this.jsonBody = jsonBody; + this.highestVersion = highestVersion; + this.riskLevel = riskLevel; + this.riskType = riskType; + this.guard = guard; + this.ttlDate = ttlDate; + } + + //Constructor for Micro Service Creating/Updating Policies from the Admin Console + public StdPAPPolicy(String configPolicyType, String policyName, String description, String onapName, String configName, String serviceType, String uuid, + String msLocation, String jsonBody, String priority, String version, Boolean editPolicy, String domain, int highestVersion, String riskLevel, + String riskType, String guard, String ttlDate) { + + this.configPolicyType = configPolicyType; + this.policyName = policyName; + this.policyDescription = description; + this.onapName = onapName; + this.configName = configName; + this.serviceType = serviceType; + this.uuid = uuid; + this.msLocation = msLocation; + this.priority = priority; + this.version = version; + this.jsonBody = jsonBody; + this.editPolicy = editPolicy; + this.domain = domain; + this.highestVersion = highestVersion; + this.riskLevel = riskLevel; + this.riskType = riskType; + this.guard = guard; + this.ttlDate = ttlDate; + } + + //Constructor for Updating Goc Policies from the Admin Console + public StdPAPPolicy (String configPolicyType, String policyName, String description, + String configName, Boolean editPolicy, String domain, + String policyID, String ruleID, String version, + String jsonBody, Integer highestVersion, String eCompName,String riskLevel, String riskType, String guard, String ttlDate) { + + this.configPolicyType = configPolicyType; + this.policyName = policyName; + this.policyDescription = description; + this.configName = configName; + this.editPolicy = editPolicy; + this.domain = domain; + this.policyID = policyID; + this.ruleID = ruleID; + this.version = version; + this.jsonBody = jsonBody; + this.highestVersion = highestVersion; + this.onapName=eCompName; + this.riskLevel = riskLevel; + this.riskType = riskType; + this.guard = guard; + this.ttlDate = ttlDate; + } + + //Constructor for Updating Brms Policies from the Admin Console + public StdPAPPolicy (String configPolicyType, String policyName, String description, + String configName, Boolean editPolicy, String domain, + String policyID, String ruleID, String version, + Map dyanamicFieldConfigAttributes, Integer highestVersion, String eCompName, + String configBodyData , String riskLevel, String riskType, String guard, String ttlDate + ) { + this.configPolicyType = configPolicyType; + this.policyName = policyName; + this.policyDescription = description; + this.configName = configName; + this.editPolicy = editPolicy; + this.domain = domain; + this.policyID = policyID; + this.ruleID = ruleID; + this.version = version; + this.dyanamicFieldConfigAttributes = dyanamicFieldConfigAttributes; + this.highestVersion = highestVersion; + this.onapName=eCompName; + this.configBodyData=configBodyData; + this.riskLevel = riskLevel; + this.riskType = riskType; + this.guard = guard; + this.ttlDate = ttlDate; + } + + //Constructor for Updating Brms Param Policies from the Admin Console + public StdPAPPolicy (String configPolicyType, String policyName, String description, + String configName, Boolean editPolicy, String domain, + String policyID, String ruleID, String version, + Map dyanamicFieldConfigAttributes, Integer highestVersion, String eCompName, + Map drlRuleAndUIParams, String riskLevel, String riskType, String guard, String ttlDate + ) { + this.configPolicyType = configPolicyType; + this.policyName = policyName; + this.policyDescription = description; + this.configName = configName; + this.editPolicy = editPolicy; + this.domain = domain; + this.policyID = policyID; + this.ruleID = ruleID; + this.version = version; + this.dyanamicFieldConfigAttributes = dyanamicFieldConfigAttributes; + this.highestVersion = highestVersion; + this.onapName=eCompName; + this.drlRuleAndUIParams=drlRuleAndUIParams; + this.riskLevel = riskLevel; + this.riskType = riskType; + this.guard = guard; + this.ttlDate = ttlDate; + } + + // Constructor for deleting policies from the API + public StdPAPPolicy(String policyName, String deleteCondition) { + this.policyName = policyName; + this.deleteCondition = deleteCondition; + } + + // Constructor for creating dictionary items from the API> + public StdPAPPolicy(String dictionaryType, String dictionary, String dictionaryFields) { + this.dictionaryType = dictionaryType; + this.dictionary = dictionary; + this.dictionaryFields = dictionaryFields; + } + + @Override + public String getPolicyName() { + return policyName; + } + + @Override + public String getPolicyDescription() { + return policyDescription; + } + + @Override + public String getOnapName() { + return onapName; + } + + @Override + public String getConfigName() { + return configName; + } + + @Override + public Map getDynamicFieldConfigAttributes() { + return dyanamicFieldConfigAttributes; + } + + @Override + public String getConfigBodyData() { + return configBodyData; + } + + @Override + public String getPolicyID() { + return policyID; + } + + @Override + public String getRuleID() { + return ruleID; + } + + @Override + public String getConfigType() { + return configType; + } + + @Override + public Boolean isEditPolicy() { + return editPolicy; + } + + @Override + public Boolean isDraft() { + return draft; + } + + @Override + public String getVersion() { + return version; + } + + @Override + public String getDomainDir() { + return domain; + } + + @Override + public String getConfigPolicyType() { + return configPolicyType; + } + + @Override + public String getJsonBody() { + return jsonBody; + } + + @Override + public Integer getHighestVersion() { + return highestVersion; + } + + @Override + public URI getLocation() { + return location; + } + + @Override + public List getDynamicRuleAlgorithmLabels() { + return dynamicRuleAlgorithmLabels; + } + + @Override + public List getDynamicRuleAlgorithmCombo() { + return dynamicRuleAlgorithmCombo; + } + + @Override + public List getDynamicRuleAlgorithmField1() { + return dynamicRuleAlgorithmField1; + } + + @Override + public List getDynamicRuleAlgorithmField2() { + return dynamicRuleAlgorithmField2; + } + + @Override + public String getActionPerformer() { + return actionPerformer; + } + + @Override + public String getActionAttribute() { + return actionAttribute; + } + + @Override + public String getActionBody() { + return actionBody; + } + + @Override + public Map getDropDownMap() { + return dropDownMap; + } + + @Override + public String getActionDictHeader() { + return actionDictHeader; + } + + @Override + public String getActionDictType() { + return actionDictType; + } + + @Override + public String getActionDictUrl() { + return actionDictUrl; + } + + @Override + public String getActionDictMethod() { + return actionDictMethod; + } + + @Override + public Map getDynamicSettingsMap() { + return dynamicSettingsMap; + } + + @Override + public List getDynamicVariableList() { + return dynamicVariableList; + } + + @Override + public List getDataTypeList() { + return dataTypeList; + } + + @Override + public String getOldPolicyFileName() { + return oldPolicyFileName; + } + + @Override + public String getServiceType() { + return serviceType; + } + + @Override + public String getUuid() { + return uuid; + } + + @Override + public String getMsLocation() { + return msLocation; + } + + @Override + public String getPriority() { + return priority; + } + + @Override + public String getDeleteCondition() { + return deleteCondition; + } + + @Override + public String getDictionaryType() { + return dictionaryType; + } + + @Override + public String getDictionary() { + return dictionary; + } + + @Override + public String getTTLDate(){ + return ttlDate; + } + + @Override + public String getDictionaryFields() { + return dictionaryFields; + } + + @Override + public String getRiskType() { + return riskType; + } + + @Override + public String getRiskLevel() { + return riskLevel; + } + + @Override + public String getGuard() { + return guard; + } + + @Override + public String toString() { + return "StdPAPPolicy [policyName=" + policyName + ", policyDescription=" + policyDescription + ", onapName=" + + onapName + ", configName=" + configName + ", dyanamicFieldConfigAttributes=" + dyanamicFieldConfigAttributes + ", configBodyData=" + configBodyData + + ", policyID=" + policyID + ", ruleID=" + ruleID + ", configType=" + configType + ", editPolicy=" + ", version=" + ", domain=" + domain + + ", configPolicyType=" + configPolicyType + ", jsonBody=" + jsonBody + ", highestVersion=" + highestVersion + ", location=" + location + + ",dynamicRuleAlgorithmLabels=" + dynamicRuleAlgorithmLabels + ",dynamicRuleAlgorithmCombo=" + dynamicRuleAlgorithmCombo + + ",dynamicRuleAlgorithmField1=" + dynamicRuleAlgorithmField1 + ",dynamicRuleAlgorithmField2=" + dynamicRuleAlgorithmField2 + + ",actionPerformer=" + actionPerformer + ",actionAttribute=" + actionAttribute + ",actionBody=" + actionBody + ",dropDownMap=" + dropDownMap + + ",actionDictHeader=" + actionDictHeader + ",actionDictType=" + actionDictType + ",actionDictUrl=" + actionDictUrl + + ",actionDictMethod=" + actionDictMethod + ",dynamicSettingsMap=" + dynamicSettingsMap + ",dynamicVariableList=" + dynamicVariableList + ",providerComboBox=" + providerComboBox + + ",dataTypeList=" + dataTypeList + ",draft=" + ",oldPolicyFileName=" + oldPolicyFileName + ",serviceType=" + serviceType + + ",uuid=" + uuid + ",msLocation=" + msLocation + ",priority=" + priority + ",deleteCondition=" + deleteCondition + ",dictionaryType=" + dictionaryType + + ",dictionary=" + dictionary + ",dictionaryFields=" + dictionaryFields + ",uuid=" + uuid + ",msLocation=" + msLocation + ",priority=" + + priority + ",deleteCondition=" + deleteCondition + ",riskType="+riskType + ",riskLevel="+riskLevel + ",guard="+ guard + ",ttlDate="+ ttlDate + "]"; + } + + // Methods needed for JSON Deserialization + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + + public void setPolicyDescription(String policyDescription) { + this.policyDescription = policyDescription; + } + + public void setOnapName(String onapName) { + this.onapName = onapName; + } + + public void setConfigName(String configName) { + this.configName = configName; + } + + public void setDyanamicFieldConfigAttributes( + Map dyanamicFieldConfigAttributes) { + this.dyanamicFieldConfigAttributes = dyanamicFieldConfigAttributes; + } + + public void setConfigBodyData(String configBodyData) { + this.configBodyData = configBodyData; + } + + public void setPolicyID(String policyID) { + this.policyID = policyID; + } + + public void setRuleID(String ruleID) { + this.ruleID = ruleID; + } + + public void setConfigType(String configType) { + this.configType = configType; + } + + public void setEditPolicy(Boolean editPolicy) { + this.editPolicy = editPolicy; + } + + public void setVersion(String version) { + this.version = version; + } + + public void setDomainDir(String domain) { + this.domain = domain; + } + + public void setConfigPolicyType(String configPolicyType) { + this.configPolicyType = configPolicyType; + } + + public void setJsonBody(String jsonBody) { + this.jsonBody = jsonBody; + } + + public void setHighestVersion(Integer highestVersion) { + this.highestVersion = highestVersion; + } + + public void setLocation (URI location) { + this.location = location; + } + + public void setDynamicRuleAlgorithmLabels( + List dynamicRuleAlgorithmLabels) { + this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; + } + + public void setDynamicRuleAlgorithmCombo(List dynamicRuleAlgorithmCombo) { + this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; + } + + public void setDynamicRuleAlgorithmField1( + List dynamicRuleAlgorithmField1) { + this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; + } + + public void setDynamicRuleAlgorithmField2( + List dynamicRuleAlgorithmField2) { + this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; + } + + public void setActionPerformer(String actionPerformer) { + this.actionPerformer = actionPerformer; + } + + public void setActionAttribute(String actionAttribute) { + this.actionAttribute = actionAttribute; + } + + public void setActionBody(String actionBody) { + this.actionBody = actionBody; + } + + public void setDropDownMap(Map dropDownMap) { + this.dropDownMap = dropDownMap; + } + + public void setActionDictHeader(String actionDictHeader) { + this.actionDictHeader = actionDictHeader; + } + + public void setActionDictType(String actionDictType) { + this.actionDictType = actionDictType; + } + + public void setActionDictUrl(String actionDictUrl) { + this.actionDictUrl = actionDictUrl; + } + + public void setActionDictMethod(String actionDictMethod) { + this.actionDictMethod = actionDictMethod; + } + + public void setDynamicSettingsMap(Map dynamicSettingsMap) { + this.dynamicSettingsMap = dynamicSettingsMap; + } + + public void setDynamicVariableList(List dynamicVariableList) { + this.dynamicVariableList = dynamicVariableList; + } + + public void setDataTypeList(List dataTypeList) { + this.dataTypeList = dataTypeList; + } + + public void setDraft(Boolean draft) { + this.draft = draft; + } + + public void setOldPolicyFileName(String oldPolicyFileName) { + this.oldPolicyFileName = oldPolicyFileName; + } + + public void setServiceType(String serviceType) { + this.serviceType = serviceType; + } + + public Map getDrlRuleAndUIParams() { + return drlRuleAndUIParams; + } + + public void setDrlRuleAndUIParams(Map drlRuleAndUIParams) { + this.drlRuleAndUIParams = drlRuleAndUIParams; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public void setMsLocation(String msLocation) { + this.msLocation = msLocation; + } + + public void setPriority(String priority) { + this.priority = priority; + } + + public void setDeleteCondition(String deleteCondition) { + this.deleteCondition = deleteCondition; + } + + public void setDictionaryType(String dictionaryType) { + this.dictionaryType = dictionaryType; + } + + public void setDictionary(String dictionary) { + this.dictionary = dictionary; + } + + public void setDictionaryFields(String dictionaryFields) { + this.dictionaryFields = dictionaryFields; + } + + public String getProviderComboBox() { + return providerComboBox; + } + + public void setProviderComboBox(String providerComboBox) { + this.providerComboBox = providerComboBox; + } + + public void setRiskType(String riskType){ + this.riskType = riskType; + } + + public void setRiskLevel(String riskLevel){ + this.riskLevel = riskLevel; + } + + public void setGuard(String guard){ + this.guard = guard; + } + + public void setTTLDate(String ttlDate){ + this.ttlDate = ttlDate; + } + + public String getBrmsController() { + return brmsController; + } + + public void setBrmsController(String brmsController) { + this.brmsController = brmsController; + } + + public ArrayList getBrmsDependency() { + return brmsDependency; + } + + public void setBrmsDependency(ArrayList brmsDependency) { + this.brmsDependency = brmsDependency; + } +} \ No newline at end of file diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDP.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDP.java new file mode 100644 index 000000000..20dbfae07 --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDP.java @@ -0,0 +1,222 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.std.pap; + +import java.io.Serializable; +import java.util.Collections; +import java.util.HashSet; +import java.util.Properties; +import java.util.Set; + +import org.onap.policy.xacml.api.pap.OnapPDP; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import com.att.research.xacml.api.pap.PDPPIPConfig; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.api.pap.PDPStatus; + +public class StdPDP extends StdPDPItemSetChangeNotifier implements OnapPDP, Comparable, Serializable { + private static final long serialVersionUID = 1L; + private static Logger logger = FlexLogger.getLogger(StdPDP.class); + + private String id; + + private String name; + + private String description; + + private Integer jmxport = 0; + + private PDPStatus status = new StdPDPStatus(); + + private Set policies = new HashSet<>(); + + private Set pipConfigs = new HashSet<>(); + + public StdPDP() { + + } + + public StdPDP(String id, Integer jmxport) { + this(id, null, null, jmxport); + } + + public StdPDP(String id, String name, Integer jmxport) { + this(id, name, null, jmxport); + } + + public StdPDP(String id, String name, String description, Integer jmxport) { + this.id = id; + this.name = name; + this.description = description; + if(jmxport != null){ + this.jmxport = jmxport; + } + } + + public StdPDP(String id, Properties properties) { + this(id, 0); + + this.initialize(properties); + } + + public void initialize(Properties properties) { + for (Object key : properties.keySet()) { + if (key.toString().startsWith(this.id + ".")) { + if (logger.isDebugEnabled()) { + logger.debug("Found: " + key); + } + if (key.toString().endsWith(".name")) { + this.name = properties.getProperty(key.toString()); + } else if (key.toString().endsWith(".description")) { + this.description = properties.getProperty(key.toString()); + }else if (key.toString().endsWith(".jmxport")) { + //todo fix this hackjob + if (properties.getProperty(key.toString()) != null && properties.getProperty(key.toString()).trim().length() > 0){ + logger.debug("initialize before: " + this.jmxport); + this.jmxport = Integer.valueOf( properties.getProperty(key.toString())); + logger.debug("initialize after: " + this.jmxport); + }else{ + this.jmxport = 0; + } + } + } + } + } + + @Override + public String getId() { + return this.id; + } + + public void setId(String id) { + this.id=id; + } + + @Override + public String getName() { + return this.name; + } + + @Override + public void setName(String name) { + this.name = name; + this.firePDPChanged(this); + } + + @Override + public String getDescription() { + return this.description; + } + + @Override + public void setDescription(String description) { + this.description = description; + this.firePDPChanged(this); + } + + @Override + public PDPStatus getStatus() { + return this.status; + } + + public void setStatus(PDPStatus status) { + this.status = status; + } + + @Override + public Set getPolicies() { + return Collections.unmodifiableSet(this.policies); + } + + public void setPolicies(Set policies) { + this.policies = policies; + } + + @Override + public Set getPipConfigs() { + return Collections.unmodifiableSet(this.pipConfigs); + } + + public void setPipConfigs(Set pipConfigs) { + this.pipConfigs = pipConfigs; + } + public void setJmxPort(Integer jmxport) { + this.jmxport = jmxport; + } + @Override + public Integer getJmxPort() { + return this.jmxport; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + StdPDP other = (StdPDP) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } + + @Override + public String toString() { + return "StdPDP [id=" + id + ", name=" + name + ", description=" + + description + ", jmxport=" + jmxport + ", status=" + status + ", policies=" + policies + + ", pipConfigs=" + pipConfigs + "]"; + } + + // + // Comparable interface + // + @Override + public int compareTo(StdPDP o) { + if (o == null) { + return -1; + } + if ( ! (o instanceof StdPDP)) { + return -1; + } + if (((StdPDP)o).name == null) { + return -1; + } + if (name == null) { + return 1; + } + return name.compareTo(((StdPDP)o).name); + } + +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroup.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroup.java new file mode 100644 index 000000000..63cc4b4fc --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroup.java @@ -0,0 +1,1058 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.std.pap; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.Serializable; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.List; +import java.util.Properties; +import java.util.Set; +import java.util.TreeSet; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +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.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener; + +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.PDPGroupStatus; +import com.att.research.xacml.api.pap.PDPGroupStatus.Status; +import com.att.research.xacml.api.pap.PDPPIPConfig; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.google.common.base.Joiner; +import com.google.common.base.Splitter; +import com.google.common.io.ByteStreams; + +public class StdPDPGroup extends StdPDPItemSetChangeNotifier implements OnapPDPGroup, StdItemSetChangeListener, Comparable, Serializable { + private static final long serialVersionUID = 1L; + private static Log logger = LogFactory.getLog(StdPDPGroup.class); + + private String id; + + private boolean isDefault = false; + + private String name; + + private String description; + + private StdPDPGroupStatus status = new StdPDPGroupStatus(Status.UNKNOWN); + + private Set pdps = new HashSet<>(); + + private Set policies = new HashSet<>(); + + private Set selectedPolicies = new HashSet<>(); + + private Set pipConfigs = new HashSet<>(); + + private String operation; + + @JsonIgnore + private Path directory; + + @JsonIgnore + private Integer jmxport; + + + public StdPDPGroup(String id, Path directory) { + this.id = id; + this.directory = directory; + } + + public StdPDPGroup(String id, boolean isDefault, Path directory) { + this(id, directory); + this.isDefault = isDefault; + } + + public StdPDPGroup(String id, boolean isDefault, String name, String description, Path directory) { + this(id, isDefault, directory); + this.name = name; + // force all policies to have a name + if (name == null) { + this.name = id; + } + this.description = description; + } + + public StdPDPGroup(String id, String name, String description, Path directory) { + this(id, false, name, description, directory); + this.resetStatus(); + } + + public StdPDPGroup(String id, boolean isDefault, Properties properties, Path directory) throws PAPException { + this(id, isDefault, directory); + this.initialize(properties, directory); + this.resetStatus(); + } + + private void initialize(Properties properties, Path directory) throws PAPException { + if (this.id == null || this.id.length() == 0) { + logger.warn("Cannot initialize with a null or zero length id"); + return; + } + // + // Pull the group's properties + // + for (Object key : properties.keySet()) { + if (key.toString().startsWith(this.id + ".")) { + if (key.toString().endsWith(".name")) { + this.name = properties.getProperty(key.toString()); + } else if (key.toString().endsWith(".description")) { + this.description = properties.getProperty(key.toString()); + } else if (key.toString().endsWith(".pdps")) { + String pdpList = properties.getProperty(key.toString()); + if (pdpList != null && pdpList.length() > 0) { + for (String id : Splitter.on(',').omitEmptyStrings().trimResults().split(pdpList)) { + StdPDP pdp = new StdPDP(id, properties); + pdp.addItemSetChangeListener(this); + this.pdps.add(pdp); + } + } + } + } + // force all policies to have a name + if (this.name == null) { + this.name = this.id; + } + } + // + // Validate our directory + // + if (Files.notExists(directory)) { + logger.warn("Group directory does NOT exist: " + directory.toString()); + try { + Files.createDirectory(directory); + this.status.addLoadWarning("Group directory does NOT exist"); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Group directory does NOT exist"); + this.status.addLoadError("Group directory does NOT exist"); + this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); + } + } + // + // Parse policies + // + this.loadPolicies(Paths.get(directory.toString(), "xacml.policy.properties")); + // + // Parse pip config + // + this.loadPIPConfig(Paths.get(directory.toString(), "xacml.pip.properties")); + } + + public void loadPolicies(Path file) throws PAPException { + // + // Read the Groups Policies + // + Properties policyProperties = new Properties(); + if ( ! file.toFile().exists()) { + // need to create the properties file with default values + policyProperties.setProperty(XACMLProperties.PROP_ROOTPOLICIES, ""); + policyProperties.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, ""); + // save properties to file + try (OutputStream os = Files.newOutputStream(file)) { + policyProperties.store(os, ""); + } catch (Exception e) { + throw new PAPException("Failed to create new default policy properties file '" + file +"'"); + } + } else { + // load previously existing file + try { + // + // Load the properties + // + try (InputStream is = Files.newInputStream(file)) { + policyProperties.load(is); + } + // + // Parse the policies + // + this.readPolicyProperties(directory, policyProperties); + } catch (IOException e) { + logger.warn("Failed to load group policy properties file: " + file, e); + this.status.addLoadError("Not policy properties defined"); + this.status.setStatus(Status.LOAD_ERRORS); + throw new PAPException("Failed to load group policy properties file: " + file); + } + } + } + + public void loadPIPConfig(Path file) throws PAPException { + // + // Read the Groups' PIP configuration + // + Properties pipProperties = new Properties(); + if ( ! file.toFile().exists()) { + // need to create the properties file with no values + pipProperties = setPIPProperties(pipProperties); + // save properties to file + try { + try (OutputStream os = Files.newOutputStream(file)) { + pipProperties.store(os, ""); + } + } catch (Exception e) { + throw new PAPException("Failed to create new default pip properties file '" + file +"'"); + } + //Even if we create a new pip file, we still need to parse and load the properties + try{ + this.readPIPProperties(directory, pipProperties); + }catch(Exception e){ + throw new PAPException("Failed to load the new pip properties file"); + } + } else { + try { + // + // Load the properties + // + try (InputStream is = Files.newInputStream(file)) { + pipProperties.load(is); + } + // For all old PIP config's modify to the new PIP Configuration. + // If PIP is empty add the new values and save it. + if(pipProperties.get(XACMLProperties.PROP_PIP_ENGINES).toString().trim().equals("")){ + pipProperties = setPIPProperties(pipProperties); + try (OutputStream os = Files.newOutputStream(file)) { + pipProperties.store(os, ""); + } + } + // + // Parse the pips + // + this.readPIPProperties(directory, pipProperties); + } catch (IOException e) { + logger.warn("Failed to open group PIP Config properties file: " + file, e); + this.status.addLoadError("Not PIP config properties defined"); + this.status.setStatus(Status.LOAD_ERRORS); + throw new PAPException("Failed to load group policy properties file: " + file); + + } + } + } + + public void resetStatus() { +// // +// // If we are updating, don't allow reset +// // +// if (this.status.getStatus() == Status.UPDATING_CONFIGURATION) { +// logger.warn("We are updating, chill."); +// return; +// } +// // +// // Load errors take precedence +// // +// if (this.status.getStatus() == Status.LOAD_ERRORS) { +// logger.warn("We had load errors."); +// return; +// } + // + // Reset our status object + // + this.status.reset(); + // + // Determine our status + // + for (PDP pdp : this.pdps) { + switch (pdp.getStatus().getStatus()) { + case OUT_OF_SYNCH: + this.status.addOutOfSynchPDP(pdp); + break; + case LAST_UPDATE_FAILED: + this.status.addLastUpdateFailedPDP(pdp); + break; + case LOAD_ERRORS: + this.status.addFailedPDP(pdp); + break; + case UPDATING_CONFIGURATION: + this.status.addUpdatingPDP(pdp); + break; + case UP_TO_DATE: + this.status.addInSynchPDP(pdp); + break; + case UNKNOWN: + case CANNOT_CONNECT: + case NO_SUCH_HOST: + default: + this.status.addUnknownPDP(pdp); + break; + } + } + + // priority is worst-cast to best case + if (this.status.getUnknownPDPs().size() > 0) { + this.status.setStatus(Status.UNKNOWN); + } else if (this.status.getFailedPDPs().size() > 0 || this.status.getLastUpdateFailedPDPs().size() > 0) { + this.status.setStatus(Status.LOAD_ERRORS); + } else if (this.status.getOutOfSynchPDPs().size() > 0) { + this.status.setStatus(Status.OUT_OF_SYNCH); + } else if (this.status.getUpdatingPDPs().size() > 0) { + this.status.setStatus(Status.UPDATING_CONFIGURATION); + } else { + this.status.setStatus(Status.OK); + } + } + + @Override + public String getId() { + return this.id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public boolean isDefaultGroup() { + return this.isDefault; + } + + public void setDefaultGroup(boolean isDefault) { + this.isDefault = isDefault; + // + // Cannot fire this because 2 operations have + // to occur: 1) old default=false (don't want to fire) and + // then 2) new default=true (yes fire - but we'll have to do that + // elsewhere. + //this.firePDPGroupChanged(this); + } + + @Override + public String getName() { + return name; + } + + @Override + public void setName(String groupName) { + this.name = groupName; + this.firePDPGroupChanged(this); + } + + @Override + public String getDescription() { + return this.description; + } + + @Override + public void setDescription(String groupDescription) { + this.description = groupDescription; + this.firePDPGroupChanged(this); + } + + public Path getDirectory() { + return this.directory; + } + + public void setDirectory(Path groupDirectory) { + this.directory = groupDirectory; + // this is used only for transmission on the RESTful interface, so no need to fire group changed? + } + + @Override + public PDPGroupStatus getStatus(){ + return this.status; + } + + @Override + public Set getSelectedPolicies() { + return this.selectedPolicies; + } + + @Override + public String getOperation() { + return this.operation; + } + + @Override + public Set getPdps() { + return Collections.unmodifiableSet(pdps); + } + + public void setOnapPdps(Set pdps) { + this.pdps = pdps; + } + + public Set getOnapPdps(){ + return Collections.unmodifiableSet(pdps); + } + + public boolean addPDP(OnapPDP pdp) { + return this.pdps.add(pdp); + } + + public boolean removePDP(PDP pdp) { + return this.pdps.remove(pdp); + } + + @Override + public Set getPolicies() { + return Collections.unmodifiableSet(this.policies); + } + + @Override + public PDPPolicy getPolicy(String id) { + for (PDPPolicy policy : this.policies) { + if (policy.getId().equals(id)) { + return policy; + } + } + return null; + } + + public Properties getPolicyProperties() + { + Properties properties = new Properties(){ + private static final long serialVersionUID = 1L; + // For Debugging it is helpful for the file to be in a sorted order, + // any by returning the keys in the natural Alpha order for strings we get close enough. + // TreeSet is sorted, and this just overrides the normal Properties method to get the keys. + @Override + public synchronized Enumeration keys() { + return Collections.enumeration(new TreeSet(super.keySet())); + } + };; + List roots = new ArrayList(); + List refs = new ArrayList(); + + for (PDPPolicy policy : this.policies) { + // for all policies need to tell PDP the "name", which is the base name for the file id + if (policy.getName() != null) { + properties.setProperty(policy.getId() + ".name", policy.getName()); + } + // put the policy on the correct list + if (policy.isRoot()) { + roots.add(policy.getId()); + } else { + refs.add(policy.getId()); + } + } + + properties.setProperty(XACMLProperties.PROP_ROOTPOLICIES, Joiner.on(',').join(roots)); + properties.setProperty(XACMLProperties.PROP_REFERENCEDPOLICIES, Joiner.on(',').join(refs)); + + return properties; + } + + public PDPPolicy publishPolicy(String id, String name, boolean isRoot, InputStream policy) throws PAPException { + // + // Does it exist already? + // + if (this.getPolicy(id) != null) { + throw new PAPException("Policy with id " + id + " already exists - unpublish it first."); + } + Path tempFile = null; + try { + // + // Copy the policy over + // + tempFile = Files.createFile(Paths.get(this.directory.toAbsolutePath().toString(), id)); + long num; + try (OutputStream os = Files.newOutputStream(tempFile)) { + num = ByteStreams.copy(policy, os); + } + logger.info("Copied " + num + " bytes for policy " + name); + + StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, isRoot, name, tempFile.toUri()); + if (tempRootPolicy.isValid() == false) { + try { + Files.delete(tempFile); + } catch(Exception ee) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, "StdPDPGroup", "Policy was invalid, could NOT delete it."); + } + throw new PAPException("Policy is invalid"); + } + // + // Add it in + // + this.policies.add(tempRootPolicy); + // + // We are changed + // + this.firePDPGroupChanged(this); + // + // Return our new object. + // + return tempRootPolicy; + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdPDPGroup", "Failed to publishPolicy"); + } + return null; + } + + /** + * Copy one policy file into the Group's directory but do not change the configuration. + * This is one part of a multi-step process of publishing policies. + * There may be multiple changes in the group (adding multiple policies, deleting policies, changine root<->referenced) + * that must be done all at once, so we just copy the file in preparation for a later "update whole group" operation. + * + * @param id + * @param name + * @param isRoot + * @param policy + * @return + * @throws PAPException + */ + public void copyPolicyToFile(String id, InputStream policy) throws PAPException { + try { + // + // Copy the policy over + // + long num; + Path policyFilePath = Paths.get(this.directory.toAbsolutePath().toString(), id); + + Path policyFile; + if (Files.exists(policyFilePath)) { + policyFile = policyFilePath; + } else { + policyFile = Files.createFile(policyFilePath); + } + + try (OutputStream os = Files.newOutputStream(policyFile)) { + num = ByteStreams.copy(policy, os); + } + + logger.info("Copied " + num + " bytes for policy " + name); + + for (PDPPolicy p : policies) { + if (p.getId().equals(id)) { + // we just re-copied/refreshed/updated the policy file for a policy that already exists in this group + logger.info("Policy '" + id + "' already exists in group '" + getId() + "'"); + return; + } + } + + // policy is new to this group + StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, true, name, policyFile.toUri()); + if (tempRootPolicy.isValid() == false) { + try { + Files.delete(policyFile); + } catch(Exception ee) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, "StdPDPGroup", "Policy was invalid, could NOT delete it."); + } + throw new PAPException("Policy is invalid"); + } + // + // Add it in + // + this.policies.add(tempRootPolicy); + // + // We are changed + // + this.firePDPGroupChanged(this); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to copyPolicyToFile"); + throw new PAPException("Failed to copy policy to file: " + e); + } + return; + } + + /** + * Policy Engine API Copy one policy file into the Group's directory but do not change the configuration. + * + * @param id + * @param name + * @param policy + * @return + * @throws PAPException + */ + public void copyPolicyToFile(String id, String name, InputStream policy) throws PAPException { + try { + // + // Copy the policy over + // + long num; + Path policyFilePath = Paths.get(this.directory.toAbsolutePath().toString(), id); + + Path policyFile; + if (Files.exists(policyFilePath)) { + policyFile = policyFilePath; + } else { + policyFile = Files.createFile(policyFilePath); + } + + try (OutputStream os = Files.newOutputStream(policyFile)) { + num = ByteStreams.copy(policy, os); + } + + logger.info("Copied " + num + " bytes for policy " + name); + for (PDPPolicy p : policies) { + if (p.getId().equals(id)) { + // we just re-copied/refreshed/updated the policy file for a policy that already exists in this group + logger.info("Policy '" + id + "' already exists in group '" + getId() + "'"); + return; + } + } + + // policy is new to this group + StdPDPPolicy tempRootPolicy = new StdPDPPolicy(id, true, name, policyFile.toUri()); + if (tempRootPolicy.isValid() == false) { + try { + Files.delete(policyFile); + } catch(Exception ee) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, ee, "StdPDPGroup", "Policy was invalid, could NOT delete it."); + } + throw new PAPException("Policy is invalid"); + } + // + // Add it in + // + this.policies.add(tempRootPolicy); + // + // We are changed + // + this.firePDPGroupChanged(this); + + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to copyPolicyToFile"); + throw new PAPException("Failed to copy policy to file: " + e); + } + return; + } + + public boolean removePolicyFromGroup(PDPPolicy policy) { + PolicyLogger.info("policy: " + policy.getId()); + PolicyLogger.info("Policy ID:" + policy.getPolicyId()); + PolicyLogger.info("Policy Version: " + policy.getVersion()); + PolicyLogger.info("StdPDPPolicy Class cast: " + this.getPolicy(policy.getId()).toString()); + StdPDPPolicy currentPolicy = (StdPDPPolicy) this.getPolicy(policy.getId()); + if (currentPolicy == null) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Policy " + policy.getId() + " does not exist."); + return false; + } + try { + // + // Remove it from our list + // + this.policies.remove(currentPolicy); + // + // We are changed + // + this.firePDPGroupChanged(this); + return true; + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to delete policy"); + } + return false; + } + + public boolean removePolicy(PDPPolicy policy) { + StdPDPPolicy currentPolicy = (StdPDPPolicy) this.getPolicy(policy.getId()); + if (currentPolicy == null) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Policy " + policy.getId() + " does not exist."); + return false; + } + try { + // + // Delete it on disk + // + Files.delete(Paths.get(currentPolicy.getLocation())); + // + // Remove it from our list + // + this.policies.remove(currentPolicy); + // + // We are changed + // + this.firePDPGroupChanged(this); + return true; + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to delete policy " + policy); + } + return false; + } + + @Override + public Set getPipConfigs() { + return Collections.unmodifiableSet(this.pipConfigs); + } + + @Override + public PDPPIPConfig getPipConfig(String id) { + for (PDPPIPConfig config : this.pipConfigs) { + if (config.getId().equals(id)) { + return config; + } + } + return null; + } + + public void setPipConfigs(Set pipConfigs) { + this.pipConfigs = pipConfigs; + this.firePDPGroupChanged(this); + } + + public void removeAllPIPConfigs() { + this.pipConfigs.clear(); + this.firePDPGroupChanged(this); + } + + public Properties getPipConfigProperties() { + Properties properties = new Properties(); + List configs = new ArrayList(); + + for (PDPPIPConfig config : this.pipConfigs) { + configs.add(config.getId()); + properties.putAll(config.getConfiguration()); + } + + properties.setProperty(XACMLProperties.PROP_PIP_ENGINES, Joiner.on(',').join(configs)); + + return properties; + } + + @Override + public void repair() { + // + // Reset the status object + // + this.status.reset(); + // + // Validate our directory + // + boolean fire = false; + if (Files.notExists(directory)) { + logger.warn("Group directory does NOT exist: " + directory.toString()); + try { + Files.createDirectory(directory); + fire = true; + this.status.addLoadWarning("Created missing group directory"); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to create missing Group directory."); + this.status.addLoadError("Failed to create missing Group directory."); + this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); + } + } + // + // Validate our PIP config file + // + Path pipPropertiesFile = Paths.get(directory.toString(), "xacml.pip.properties"); + if (Files.notExists(pipPropertiesFile)) { + try { + Files.createFile(pipPropertiesFile); + fire = true; + this.status.addLoadWarning("Created missing PIP properties file"); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to create missing PIP properties file"); + this.status.addLoadError("Failed to create missing PIP properties file"); + this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); + } + } + // + // Valid our policy properties file + // + Path policyPropertiesFile = Paths.get(directory.toString(), "xacml.policy.properties"); + if (Files.notExists(policyPropertiesFile)) { + try { + Files.createFile(policyPropertiesFile); + fire = true; + this.status.addLoadWarning("Created missing Policy properties file"); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to create missing Policy properties file"); + this.status.addLoadError("Failed to create missing Policy properties file"); + this.status.setStatus(PDPGroupStatus.Status.LOAD_ERRORS); + } + } + this.resetStatus(); + if (fire) { + this.fireChanged(); + } + } + + private void readPolicyProperties(Path directory, Properties properties) { + // + // There are 2 property values that hold policies, root and referenced + // + String[] lists = new String[2]; + lists[0] = properties.getProperty(XACMLProperties.PROP_ROOTPOLICIES); + lists[1] = properties.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); + // + // Iterate each policy list + // + boolean isRoot = true; + for (String list : lists) { + // + // Was there actually a property? + // + if (list == null || list.length() == 0) { + isRoot = false; + continue; + } + // + // Parse it out + // + Iterable policyList = Splitter.on(',').trimResults().omitEmptyStrings().split(list); + // + // Was there actually a list + // + if (policyList == null) { + isRoot = false; + continue; + } + for (String id : policyList) { + // + // Construct the policy filename + // + Path policyPath = Paths.get(directory.toString(), id ); + // + // Create the Policy Object + // + StdPDPPolicy policy; + try { + policy = new StdPDPPolicy(id, isRoot, policyPath.toUri(), properties); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Failed to create policy object"); + policy = null; + } + // + // Is it valid? + // + if (policy != null && policy.isValid()) { + this.policies.add(policy); + this.status.addLoadedPolicy(policy); + } else { + this.status.addFailedPolicy(policy); + this.status.setStatus(Status.LOAD_ERRORS); + } + // force all policies to have a name + if (policy!=null && policy.getName() == null) { + policy.setName(policy.getId()); + } + } + isRoot = false; + } + } + + private void readPIPProperties(Path directory, Properties properties) { + String list = properties.getProperty(XACMLProperties.PROP_PIP_ENGINES); + if (list == null || list.length() == 0) { + return; + } + for (String id : list.split("[,]")) { + StdPDPPIPConfig config = new StdPDPPIPConfig(id, properties); + if (config.isConfigured()) { + this.pipConfigs.add(config); + this.status.addLoadedPipConfig(config); + } else { + this.status.addFailedPipConfig(config); + this.status.setStatus(Status.LOAD_ERRORS); + } + } + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + StdPDPGroup other = (StdPDPGroup) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + return true; + } + + @Override + public String toString() { + return "StdPDPGroup [id=" + id + ", isDefault=" + isDefault + ", name=" + + name + ", description=" + description + ", status=" + status + + ", pdps=" + pdps + ", policies=" + policies + ", pipConfigs=" + + pipConfigs + ", directory=" + directory + ",selectedPolicies=" + + selectedPolicies + ",operation=" + operation + "]"; + } + + @Override + public void changed() { + + // save the (changed) properties + try { + saveGroupConfiguration(); + } catch (PAPException | IOException e) { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "StdPDPGroup", "Unable to save group configuration change"); + // don't notify other things of change if we cannot save it??? + return; + } + + this.firePDPGroupChanged(this); + + } + + @Override + public void groupChanged(OnapPDPGroup group) { + this.changed(); + } + + @Override + public void pdpChanged(OnapPDP pdp) { + // + // If one of the group's PDP's changed, then the group changed + // + this.changed(); + } + + + // + // Methods needed for JSON deserialization + // + public StdPDPGroup() { + + } + + public StdPDPGroup(OnapPDPGroup group) { + this.id = group.getId(); + this.name = group.getName(); + this.description = group.getDescription(); + this.isDefault = group.isDefaultGroup(); + this.pdps = group.getOnapPdps(); + this.policies = group.getPolicies(); + this.pipConfigs = group.getPipConfigs(); + } + + public boolean isDefault() { + return isDefault; + } + public void setDefault(boolean isDefault) { + this.isDefault = isDefault; + } + public void setStatus(PDPGroupStatus status) { + this.status = new StdPDPGroupStatus(status); + } + public void setPolicies(Set policies) { + this.policies = policies; + } + public void setSelectedPolicies(Set selectedPolicies) { + this.selectedPolicies = selectedPolicies; + } + public void setOperation(String operation) { + this.operation = operation; + } + + public void saveGroupConfiguration() throws PAPException, IOException { + + // First save the Policy properties + + // save the lists of policies + Properties policyProperties = this.getPolicyProperties(); + + // save info about each policy + for (PDPPolicy policy : this.policies){ + policyProperties.put(policy.getId() + ".name", policy.getName()); + } + + // + // Now we can save the file + // + Path file = Paths.get(this.directory.toString(), "xacml.policy.properties"); + try (OutputStream os = Files.newOutputStream(file)) { + policyProperties.store(os, ""); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "STdPDPGroup", "Group Policies Config save failed"); + throw new PAPException("Failed to save policy properties file '" + file +"'"); + } + + + // Now save the PIP Config properties + Properties pipProperties = this.getPipConfigProperties(); + + // + // Now we can save the file + // + file = Paths.get(this.directory.toString(), "xacml.pip.properties"); + try (OutputStream os = Files.newOutputStream(file)) { + pipProperties.store(os, ""); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "StdPDPGroup", "Group PIP Config save failed"); + throw new PAPException("Failed to save pip properties file '" + file +"'"); + } + } + + // + // Comparable Interface + // + @Override + public int compareTo(Object arg0) { + if (arg0 == null) { + return -1; + } + if ( ! (arg0 instanceof StdPDPGroup)) { + return -1; + } + if (((StdPDPGroup)arg0).name == null) { + return -1; + } + if (name == null) { + return 1; + } + + return name.compareTo(((StdPDPGroup)arg0).name); + } + + //Adding Default PIP engine(s) while Loading initially. We don't want + // Programmer intervention with the PIP engines. + private Properties setPIPProperties(Properties props){ + props.setProperty("AAF.name", "AAFEngine"); + props.setProperty("AAF.description", "AAFEngine to communicate with AAF to take decisions"); + props.setProperty("AAF.classname","org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine"); + props.setProperty(XACMLProperties.PROP_PIP_ENGINES, "AAF"); + // read from PIP properties file. + Path file = Paths.get(StdEngine.pipPropertyFile); + if (!Files.notExists(file)) { + InputStream in; + Properties prop = new Properties(); + try { + in = new FileInputStream(file.toFile()); + prop.load(in); + } catch (IOException e) { + PolicyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "can not load the pip properties from file" +e); + } + props = prop; + } + return props; + } + + +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroupStatus.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroupStatus.java new file mode 100644 index 000000000..296f738f4 --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPGroupStatus.java @@ -0,0 +1,405 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.std.pap; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import com.att.research.xacml.api.pap.PDP; +import com.att.research.xacml.api.pap.PDPGroupStatus; +import com.att.research.xacml.api.pap.PDPPIPConfig; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.fasterxml.jackson.annotation.JsonIgnore; + +public class StdPDPGroupStatus implements PDPGroupStatus { + + private Status status = Status.UNKNOWN; + + private Set loadErrors = new HashSet<>(); + + private Set loadWarnings = new HashSet<>(); + + private Set loadedPolicies = new HashSet<>(); + + private Set failedPolicies = new HashSet<>(); + + private Set loadedPIPConfigs = new HashSet<>(); + + private Set failedPIPConfigs = new HashSet<>(); + + private Set inSynchPDPs = new HashSet<>(); + + private Set outOfSynchPDPs = new HashSet<>(); + + private Set failedPDPs = new HashSet<>(); + + private Set updatingPDPs = new HashSet<>(); + + private Set lastUpdateFailedPDPs = new HashSet<>(); + + private Set unknownPDPs = new HashSet<>(); + + + // Constructor needed for JSON deserialization + public StdPDPGroupStatus() { + + } + + public StdPDPGroupStatus(Status status) { + this.status = status; + } + + public StdPDPGroupStatus(PDPGroupStatus stat) { + this.status = stat.getStatus(); + this.failedPDPs.clear(); this.failedPDPs.addAll(stat.getFailedPDPs()); + this.failedPIPConfigs.clear(); this.failedPIPConfigs.addAll(stat.getFailedPipConfigs()); + this.failedPolicies.clear(); this.failedPolicies.addAll(stat.getFailedPolicies()); + this.inSynchPDPs.clear(); this.inSynchPDPs.addAll(stat.getInSynchPDPs()); + this.lastUpdateFailedPDPs.clear(); this.lastUpdateFailedPDPs.addAll(stat.getLastUpdateFailedPDPs()); + this.loadedPIPConfigs.clear(); this.loadedPIPConfigs.addAll(stat.getLoadedPipConfigs()); + this.loadedPolicies.clear(); this.loadedPolicies.addAll(stat.getLoadedPolicies()); + this.loadErrors.clear(); this.loadErrors.addAll(stat.getLoadErrors()); + this.loadWarnings.clear(); this.loadWarnings.addAll(stat.getLoadWarnings()); + this.outOfSynchPDPs.clear(); this.outOfSynchPDPs.addAll(stat.getOutOfSynchPDPs()); + this.unknownPDPs.clear(); this.unknownPDPs.addAll(stat.getUpdatingPDPs()); + this.updatingPDPs.clear(); this.updatingPDPs.addAll(stat.getUpdatingPDPs()); + } + + public Set getLoadedPIPConfigs() { + return loadedPIPConfigs; + } + public void setLoadedPIPConfigs(Set loadedPIPConfigs) { + this.loadedPIPConfigs = loadedPIPConfigs; + } + public Set getFailedPIPConfigs() { + return failedPIPConfigs; + } + public void setFailedPIPConfigs(Set failedPIPConfigs) { + this.failedPIPConfigs = failedPIPConfigs; + } + public Set getUnknownPDPs() { + return unknownPDPs; + } + public void setUnknownPDPs(Set unknownPDPs) { + this.unknownPDPs = unknownPDPs; + } + public void setLoadErrors(Set loadErrors) { + this.loadErrors = loadErrors; + } + public void setLoadWarnings(Set loadWarnings) { + this.loadWarnings = loadWarnings; + } + public void setLoadedPolicies(Set loadedPolicies) { + this.loadedPolicies = loadedPolicies; + } + public void setFailedPolicies(Set failedPolicies) { + this.failedPolicies = failedPolicies; + } + public void setInSynchPDPs(Set inSynchPDPs) { + this.inSynchPDPs = inSynchPDPs; + } + public void setOutOfSynchPDPs(Set outOfSynchPDPs) { + this.outOfSynchPDPs = outOfSynchPDPs; + } + public void setFailedPDPs(Set failedPDPs) { + this.failedPDPs = failedPDPs; + } + public void setUpdatingPDPs(Set updatingPDPs) { + this.updatingPDPs = updatingPDPs; + } + public void setLastUpdateFailedPDPs(Set lastUpdateFailedPDPs) { + this.lastUpdateFailedPDPs = lastUpdateFailedPDPs; + } + + + @Override + public Status getStatus() { + return status; + } + + public void setStatus(Status status) { + this.status = status; + } + + @Override + public Set getLoadErrors() { + return Collections.unmodifiableSet(this.loadErrors); + } + + public void addLoadError(String error) { + this.loadErrors.add(error); + } + + @Override + public Set getLoadWarnings() { + return Collections.unmodifiableSet(this.loadWarnings); + } + + public void addLoadWarning(String warning) { + this.loadWarnings.add(warning); + } + + @Override + public Set getLoadedPolicies() { + return Collections.unmodifiableSet(this.loadedPolicies); + } + + public void addLoadedPolicy(PDPPolicy policy) { + this.loadedPolicies.add(policy); + } + + @Override + public Set getFailedPolicies() { + return Collections.unmodifiableSet(this.failedPolicies); + } + + public void addFailedPolicy(PDPPolicy policy) { + this.failedPolicies.add(policy); + } + + @Override + public boolean policiesOK() { + if (this.failedPolicies.size() > 0) { + return false; + } + return true; + } + + @Override + public Set getLoadedPipConfigs() { + return Collections.unmodifiableSet(this.loadedPIPConfigs); + } + + public void addLoadedPipConfig(PDPPIPConfig config) { + this.loadedPIPConfigs.add(config); + } + + @Override + public Set getFailedPipConfigs() { + return Collections.unmodifiableSet(this.failedPIPConfigs); + } + + public void addFailedPipConfig(PDPPIPConfig config) { + this.failedPIPConfigs.add(config); + } + + @Override + public boolean pipConfigOK() { + if (this.failedPIPConfigs.size() > 0) { + return false; + } + return true; + } + + @Override + public Set getInSynchPDPs() { + return Collections.unmodifiableSet(this.inSynchPDPs); + } + + public void addInSynchPDP(PDP pdp) { + this.inSynchPDPs.add(pdp); + } + + @Override + public Set getOutOfSynchPDPs() { + return Collections.unmodifiableSet(this.outOfSynchPDPs); + } + + public void addOutOfSynchPDP(PDP pdp) { + this.outOfSynchPDPs.add(pdp); + } + + @Override + public Set getFailedPDPs() { + return Collections.unmodifiableSet(this.failedPDPs); + } + + public void addFailedPDP(PDP pdp) { + this.failedPDPs.add(pdp); + } + + @Override + public Set getUpdatingPDPs() { + return Collections.unmodifiableSet(this.updatingPDPs); + } + + public void addUpdatingPDP(PDP pdp) { + this.updatingPDPs.add(pdp); + } + + @Override + public Set getLastUpdateFailedPDPs() { + return Collections.unmodifiableSet(this.lastUpdateFailedPDPs); + } + + public void addLastUpdateFailedPDP(PDP pdp) { + this.lastUpdateFailedPDPs.add(pdp); + } + + @Override + @JsonIgnore + public Set getUnknownStatusPDPs() { + return Collections.unmodifiableSet(this.unknownPDPs); + } + + public void addUnknownPDP(PDP pdp) { + this.unknownPDPs.add(pdp); + } + + @Override + public boolean pdpsOK() { + if (this.outOfSynchPDPs.size() > 0) { + return false; + } + if (this.failedPDPs.size() > 0) { + return false; + } + if (this.lastUpdateFailedPDPs.size() > 0) { + return false; + } + if (this.unknownPDPs.size() > 0) { + return false; + } + return true; + } + + @Override + @JsonIgnore + public boolean isGroupOk() { + if (this.policiesOK() == false) { + return false; + } + if (this.pipConfigOK() == false) { + return false; + } + if (this.pdpsOK() == false) { + return false; + } + if (this.loadErrors.isEmpty() == false) { + return false; + } + return (this.status == Status.OK); + } + + public void reset() { + this.status = Status.OK; + + this.loadErrors.clear(); + this.loadWarnings.clear(); + this.loadedPolicies.clear(); + this.failedPolicies.clear(); + this.loadedPIPConfigs.clear(); + this.failedPIPConfigs.clear(); + this.inSynchPDPs.clear(); + this.outOfSynchPDPs.clear(); + this.failedPDPs.clear(); + this.updatingPDPs.clear(); + this.lastUpdateFailedPDPs.clear(); + this.unknownPDPs.clear(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + + (failedPDPs.hashCode()); + result = prime + * result + + (failedPIPConfigs.hashCode()); + result = prime * result + + (failedPolicies.hashCode()); + result = prime * result + + (inSynchPDPs.hashCode()); + result = prime + * result + + (lastUpdateFailedPDPs.hashCode()); + result = prime * result + + (loadErrors.hashCode()); + result = prime * result + + (loadWarnings.hashCode()); + result = prime + * result + + (loadedPIPConfigs.hashCode()); + result = prime * result + + (loadedPolicies.hashCode()); + result = prime * result + + (outOfSynchPDPs.hashCode()); + result = prime * result + (status.hashCode()); + result = prime * result + + (unknownPDPs.hashCode()); + result = prime * result + + (updatingPDPs.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + StdPDPGroupStatus other = (StdPDPGroupStatus) obj; + if (!failedPDPs.equals(other.failedPDPs)) + return false; + if (!failedPIPConfigs.equals(other.failedPIPConfigs)) + return false; + if (!failedPolicies.equals(other.failedPolicies)) + return false; + if (!inSynchPDPs.equals(other.inSynchPDPs)) + return false; + if (!lastUpdateFailedPDPs.equals(other.lastUpdateFailedPDPs)) + return false; + if (!loadErrors.equals(other.loadErrors)) + return false; + if (!loadWarnings.equals(other.loadWarnings)) + return false; + if (!loadedPIPConfigs.equals(other.loadedPIPConfigs)) + return false; + if (!loadedPolicies.equals(other.loadedPolicies)) + return false; + if (!outOfSynchPDPs.equals(other.outOfSynchPDPs)) + return false; + if (status != other.status) + return false; + if (!unknownPDPs.equals(other.unknownPDPs)) + return false; + if (!updatingPDPs.equals(other.updatingPDPs)) + return false; + return true; + } + + @Override + public String toString() { + return "StdPDPGroupStatus [status=" + status + ", loadErrors=" + + loadErrors + ", loadWarnings=" + loadWarnings + + ", loadedPolicies=" + loadedPolicies + ", failedPolicies=" + + failedPolicies + ", loadedPIPConfigs=" + loadedPIPConfigs + + ", failedPIPConfigs=" + failedPIPConfigs + ", inSynchPDPs=" + + inSynchPDPs + ", outOfSynchPDPs=" + outOfSynchPDPs + + ", failedPDPs=" + failedPDPs + ", updatingPDPs=" + + updatingPDPs + ", lastUpdateFailedPDPs=" + + lastUpdateFailedPDPs + ", unknownPDPs=" + unknownPDPs + "]"; + } + +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java new file mode 100644 index 000000000..d23501f26 --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPItemSetChangeNotifier.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.std.pap; + +import java.util.Collection; +import java.util.LinkedList; + +import org.onap.policy.xacml.api.pap.OnapPDP; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; + +public class StdPDPItemSetChangeNotifier { + + private Collection listeners = null; + + public interface StdItemSetChangeListener { + + public void changed(); + + public void groupChanged(OnapPDPGroup group); + + public void pdpChanged(OnapPDP pdp); + + } + + public void addItemSetChangeListener(StdItemSetChangeListener listener) { + if (this.listeners == null) { + this.listeners = new LinkedList(); + } + this.listeners.add(listener); + } + + public void removeItemSetChangeListener(StdItemSetChangeListener listener) { + if (this.listeners != null) { + this.listeners.remove(listener); + } + } + + public void fireChanged() { + if (this.listeners == null) { + return; + } + for (StdItemSetChangeListener l : this.listeners) { + l.changed(); + } + } + + public void firePDPGroupChanged(OnapPDPGroup group) { + if (this.listeners == null) { + return; + } + for (StdItemSetChangeListener l : this.listeners) { + l.groupChanged(group); + } + } + + public void firePDPChanged(OnapPDP pdp) { + if (this.listeners == null) { + return; + } + for (StdItemSetChangeListener l : this.listeners) { + l.pdpChanged(pdp); + } + } +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPIPConfig.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPIPConfig.java new file mode 100644 index 000000000..f04384620 --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPIPConfig.java @@ -0,0 +1,216 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.std.pap; + +import java.io.Serializable; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import com.att.research.xacml.api.pap.PDPPIPConfig; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +public class StdPDPPIPConfig implements PDPPIPConfig, Serializable { + private static final long serialVersionUID = 1L; + private static Logger logger = FlexLogger.getLogger(StdPDPPIPConfig.class); + + private String id; + + private String name; + + private String description; + + private String classname; + + private Map config = new HashMap<>(); + + public StdPDPPIPConfig() { + + } + + public StdPDPPIPConfig(String id) { + this.id = id; + } + + public StdPDPPIPConfig(String id, String name, String description) { + this(id); + this.name = name; + this.description = description; + } + + public StdPDPPIPConfig(String id, Properties properties) { + this(id); + if ( ! this.initialize(properties) ) { + throw new IllegalArgumentException("PIP Engine '" + id + "' has no classname property in config"); + } + } + + public boolean initialize(Properties properties) { + boolean classnameSeen = false; + for (Object key : properties.keySet()) { + if (key.toString().startsWith(this.id + ".")) { + if (logger.isDebugEnabled()) { + logger.debug("Found: " + key); + } + if (key.toString().equals(this.id + ".name")) { + this.name = properties.getProperty(key.toString()); + } else if (key.toString().equals(this.id + ".description")) { + this.description = properties.getProperty(key.toString()); + } else if (key.toString().equals(this.id + ".classname")) { + this.classname = properties.getProperty(key.toString()); + classnameSeen = true; + } + // all properties, including the special ones located above, are included in the properties list + this.config.put(key.toString(), properties.getProperty(key.toString())); + } + } + return classnameSeen; + } + + @Override + public String getId() { + return this.id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + @Override + public String getClassname() { + return classname; + } + + public void setClassname(String classname) { + this.classname = classname; + } + + @Override + @JsonIgnore + public Map getConfiguration() { + return Collections.unmodifiableMap(this.config); + } + + public void setValues(Map config) { + this.config = config; + } + + @Override + @JsonIgnore + public boolean isConfigured() { + // + // Also include this in the JSON I/O if it is a data field rather than calculated + // + return true; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + + ((classname == null) ? 0 : classname.hashCode()); + result = prime * result + ((config == null) ? 0 : config.hashCode()); + result = prime * result + + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + StdPDPPIPConfig other = (StdPDPPIPConfig) obj; + if (classname == null) { + if (other.classname != null) + return false; + } else if (!classname.equals(other.classname)) + return false; + if (config == null) { + if (other.config != null) + return false; + } else if (!config.equals(other.config)) + return false; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + @Override + public String toString() { + return "StdPDPPIPConfig [id=" + id + ", name=" + name + + ", description=" + description + ", classname=" + classname + + ", config=" + config + "]"; + } + + + + // + // Methods needed for JSON serialization/deserialization + // + + public Map getConfig() { + return config; + } + public void setConfig(Map config) { + this.config = config; + } + +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicy.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicy.java new file mode 100644 index 000000000..892211a4c --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPPolicy.java @@ -0,0 +1,366 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.std.pap; + +import org.onap.policy.common.logging.eelf.PolicyLogger; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; +import java.net.URI; +import java.net.URL; +import java.util.ArrayList; +import java.util.Properties; + +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.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.xacml.util.XACMLPolicyScanner; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.google.common.base.Splitter; +import com.google.common.collect.Lists; + + +public class StdPDPPolicy implements PDPPolicy, Serializable { + private static final long serialVersionUID = 1L; + private static Log logger = LogFactory.getLog(StdPDPPolicy.class); + + private String id = null; + + private String name = null; + + private String policyId = null; + + private String description = null; + + private int[] version = null; + + private boolean isRoot = false; + + private boolean isValid = false; + + private URI location = null; + + + public StdPDPPolicy(String id, boolean isRoot) { + this.id = id; + this.isRoot = isRoot; + } + + public StdPDPPolicy(String id, boolean isRoot, String name) { + this(id, isRoot); + this.name = name; + } + + + public StdPDPPolicy(String id, boolean isRoot, String name, URI location) throws IOException { + this(id, isRoot); + this.name = name; + this.location = location; + + // + // Read the policy data + // + String theID = this.readPolicyData(); + + if (this.id == null) { + logger.debug("id is null so we are calling readPolicyData() to get the policyID"); + this.id = theID; + } + + logger.debug("The final outcome of the constructor returned the following: id = " + id + + ", location = " + location + ", name = " + name); + + } + + public StdPDPPolicy(String id, boolean isRoot, String name, URI location, boolean isValid, String policyId, + String description, String version) throws IOException { + this(id, isRoot); + this.name = name; + this.location = location; + this.policyId = policyId; + this.description = description; + this.version = versionStringToArray(version); + this.isValid = isValid; + + logger.debug("The final outcome of the constructor returned the following: id = " + id + + ", location = " + location + ", name = " + name + ", policyId = " + policyId + + ", description = " + description + ", Version = " + version); + + } + + public StdPDPPolicy(String id, boolean isRoot, String name, URI location, boolean isFromAPI) throws IOException { + this(id, isRoot); + this.name = name; + this.location = location; + this.isValid = isFromAPI; + + logger.debug("The final outcome of the constructor returned the following: id = " + id + + ", location = " + location + ", name = " + name); + + } + + public StdPDPPolicy(String id, boolean isRoot, URI location, Properties properties) throws IOException { + this(id, isRoot); + this.location = location; + // + // Read the policy data + // + this.readPolicyData(); + // + // See if there's a name + // + for (Object key : properties.keySet()) { + if (key.toString().equals(id + ".name")) { + this.name = properties.getProperty(key.toString()); + break; + } + } + } + + + private String readPolicyData() throws IOException { + // + // Extract XACML policy information + // + URL url = this.location.toURL(); + Object rootElement = XACMLPolicyScanner.readPolicy(url.openStream()); + if (rootElement == null || + ( + ! (rootElement instanceof PolicySetType) && + ! (rootElement instanceof PolicyType) + ) ) { + logger.warn("No root policy element in URI: " + this.location.toString() + " : " + rootElement); + this.isValid = false; + } else { + this.version = versionStringToArray(XACMLPolicyScanner.getVersion(rootElement)); + if (rootElement instanceof PolicySetType) { + this.policyId = ((PolicySetType)rootElement).getPolicySetId(); + this.description = ((PolicySetType)rootElement).getDescription(); + this.isValid = true; + this.version = versionStringToArray(((PolicySetType)rootElement).getVersion()); + } else if (rootElement instanceof PolicyType) { + this.policyId = ((PolicyType)rootElement).getPolicyId(); + this.description = ((PolicyType)rootElement).getDescription(); + this.version = versionStringToArray(((PolicyType)rootElement).getVersion()); + this.isValid = true; + } else { + PolicyLogger.error("Unknown root element: " + rootElement.getClass().getCanonicalName()); + } + } + if (this.policyId != null) { + ArrayList foo = Lists.newArrayList(Splitter.on(':').split(this.policyId)); + if (foo.isEmpty() == false) { + return foo.get(foo.size() - 1); + } + } + return null; + } + + @Override + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + @Override + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String getPolicyId() { + return this.policyId; + } + + @Override + public String getDescription() { + return this.description; + } + + @Override + public String getVersion() { + return versionArrayToString(this.version); + } + + @Override + @JsonIgnore + public int[] getVersionInts() { + return version; + } + + @Override + public boolean isRoot() { + return this.isRoot; + } + + @Override + public boolean isValid() + { + return this.isValid; + } + + @Override + @JsonIgnore + public InputStream getStream() throws PAPException, IOException { + try { + if (this.location != null) { + URL url = this.location.toURL(); + return url.openStream(); + } + return null; + } catch (FileNotFoundException e) { + throw new PAPException(e); + } + } + + @Override + public URI getLocation() throws PAPException { + return this.location; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((id == null) ? 0 : id.hashCode()); + result = prime * result + + ((policyId == null) ? 0 : policyId.hashCode()); + result = prime * result; + if (version != null) { + for (int i = 0; i < version.length; i++) { + result += version[i]; + } + } + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + StdPDPPolicy other = (StdPDPPolicy) obj; + if (id == null) { + if (other.id != null) + return false; + } else if (!id.equals(other.id)) + return false; + if (policyId == null) { + if (other.policyId != null) + return false; + } else if (!policyId.equals(other.policyId)) + return false; + if (version != other.version) + return false; + return true; + } + + @Override + public String toString() { + return "StdPDPPolicy [id=" + id + ", name=" + name + ", policyId=" + + policyId + ", description=" + description + ", version=" + + this.getVersion() + ", isRoot=" + isRoot + ", isValid=" + isValid + + ", location=" + location + "]"; + } + + + /** + * Given a version string consisting of integers with dots between them, convert it into an array of ints. + * + * @param version + * @return + * @throws NumberFormatException + */ + public static int[] versionStringToArray(String version) throws NumberFormatException { + if (version == null || version.length() == 0) { + return new int[0]; + } + String[] stringArray = version.split("\\."); + int[] resultArray = new int[stringArray.length]; + for (int i = 0; i < stringArray.length; i++) { + resultArray[i] = Integer.parseInt(stringArray[i]); + } + return resultArray; + } + + /** + * Given an array representing a version, create the corresponding dot-separated string. + * + * @param array + * @return + */ + public static String versionArrayToString(int[] array) { + if (array == null || array.length == 0) { + return ""; + } + String versionString = ""; + if (array.length > 0) { + versionString = "" + array[0]; + for (int i = 1; i < array.length; i++) { + versionString += "." + array[i]; + } + } + return versionString; + } + + + + // + // Methods needed for JSON Deserialization + // + public StdPDPPolicy() {} + + public void setPolicyId(String policyId) { + this.policyId = policyId; + } + public void setDescription(String description) { + this.description = description; + } + public void setVersion(String version) { + this.version = versionStringToArray(version); + } + public void setRoot(boolean isRoot) { + this.isRoot = isRoot; + } + public void setValid(boolean isValid) { + this.isValid = isValid; + } + public void setLocation(URI location) { + this.location = location; + } + +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPStatus.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPStatus.java new file mode 100644 index 000000000..f8759956c --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pap/StdPDPStatus.java @@ -0,0 +1,265 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.std.pap; + +import java.io.Serializable; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import com.att.research.xacml.api.pap.PDPPIPConfig; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.api.pap.PDPStatus; +import com.fasterxml.jackson.annotation.JsonIgnore; + +public class StdPDPStatus implements Serializable, PDPStatus { + private static final long serialVersionUID = 1L; + + private Status status = Status.UNKNOWN; + + private Set loadErrors = new HashSet<>(); + + private Set loadWarnings = new HashSet<>(); + + private Set loadedPolicies = new HashSet<>(); + + private Set loadedRootPolicies = new HashSet<>(); + + private Set failedPolicies = new HashSet<>(); + + private Set loadedPIPConfigs = new HashSet<>(); + + private Set failedPIPConfigs = new HashSet<>(); + + public StdPDPStatus() { + } + + public void set(StdPDPStatus newStatus) { + this.status = newStatus.status; + this.loadErrors.clear(); + this.loadErrors.addAll(newStatus.getLoadErrors()); + this.loadWarnings.clear(); + this.loadWarnings.addAll(newStatus.getLoadWarnings()); + this.loadedPolicies.clear(); + this.loadedPolicies.addAll(newStatus.getLoadedPolicies()); + this.loadedRootPolicies.clear(); + this.loadedRootPolicies.addAll(newStatus.getLoadedRootPolicies()); + this.failedPolicies.clear(); + this.failedPolicies.addAll(newStatus.getFailedPolicies()); + this.loadedPIPConfigs.clear(); + this.loadedPIPConfigs.addAll(newStatus.getLoadedPipConfigs()); + this.failedPIPConfigs.clear(); + this.failedPIPConfigs.addAll(newStatus.getFailedPipConfigs()); + } + + + + @Override + public Status getStatus() { + return this.status; + } + + public void setStatus(Status status) { + this.status = status; + } + + @Override + public Set getLoadErrors() { + return Collections.unmodifiableSet(this.loadErrors); + } + + public void setLoadErrors(Set errors) { + this.loadErrors = errors; + } + + public void addLoadError(String error) { + this.loadErrors.add(error); + } + + @Override + public Set getLoadWarnings() { + return Collections.unmodifiableSet(this.loadWarnings); + } + + public void setLoadWarnings(Set warnings) { + this.loadWarnings = warnings; + } + + public void addLoadWarning(String warning) { + this.loadWarnings.add(warning); + } + + @Override + public Set getLoadedPolicies() { + return Collections.unmodifiableSet(this.loadedPolicies); + } + + public void setLoadedPolicies(Set policies) { + this.loadedPolicies = policies; + } + + public void addLoadedPolicy(PDPPolicy policy) { + this.loadedPolicies.add(policy); + } + + @Override + public Set getLoadedRootPolicies() { + return Collections.unmodifiableSet(this.loadedRootPolicies); + } + + public void setLoadedRootPolicies(Set policies) { + this.loadedRootPolicies = policies; + } + + public void addRootPolicy(PDPPolicy policy) { + this.loadedRootPolicies.add(policy); + } + + public void addAllLoadedRootPolicies(Set policies) { + this.loadedRootPolicies.addAll(policies); + } + + @Override + public Set getFailedPolicies() { + return Collections.unmodifiableSet(this.failedPolicies); + } + + public void setFailedPolicies(Set policies) { + this.failedPolicies = policies; + } + + public void addFailedPolicy(PDPPolicy policy) { + this.failedPolicies.add(policy); + } + + @Override + public boolean policiesOK() { + if (this.failedPolicies.size() > 0) { + return false; + } + return true; + } + + @Override + public Set getLoadedPipConfigs() { + return Collections.unmodifiableSet(this.loadedPIPConfigs); + } + + public void setLoadedPipConfigs(Set configs) { + this.loadedPIPConfigs = configs; + } + + public void addLoadedPipConfig(PDPPIPConfig config) { + this.loadedPIPConfigs.add(config); + } + + @Override + public Set getFailedPipConfigs() { + return Collections.unmodifiableSet(this.failedPIPConfigs); + } + + public void setFailedPipConfigs(Set configs) { + this.failedPIPConfigs = configs; + } + + public void addFailedPipConfig(PDPPIPConfig config) { + this.failedPIPConfigs.add(config); + } + + @Override + public boolean pipConfigOK() { + if (this.failedPIPConfigs.size() > 0) { + return false; + } + return true; + } + + @Override + @JsonIgnore + public boolean isOk() { + if (this.policiesOK() == false) { + return false; + } + if (this.pipConfigOK() == false) { + return false; + } + return (this.status == Status.UP_TO_DATE); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime + * result + + (failedPIPConfigs.hashCode()); + result = prime * result + + (failedPolicies.hashCode()); + result = prime * result + + (loadErrors.hashCode()); + result = prime * result + + (loadWarnings.hashCode()); + result = prime + * result + + (loadedPIPConfigs.hashCode()); + result = prime * result + + (loadedPolicies.hashCode()); + result = prime * result + (status.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + StdPDPStatus other = (StdPDPStatus) obj; + if (!failedPIPConfigs.equals(other.failedPIPConfigs)) + return false; + if (!failedPolicies.equals(other.failedPolicies)) + return false; + if (!loadErrors.equals(other.loadErrors)) + return false; + if (!loadWarnings.equals(other.loadWarnings)) + return false; + if (!loadedPIPConfigs.equals(other.loadedPIPConfigs)) + return false; + if (!loadedPolicies.equals(other.loadedPolicies)) + return false; + if (status != other.status) + return false; + return true; + } + + @Override + public String toString() { + return "StdPDPStatus [status=" + status + ", loadErrors=" + loadErrors + + ", loadWarnings=" + loadWarnings + ", loadedPolicies=" + + loadedPolicies + ", loadedRootPolicies=" + loadedRootPolicies + + ", failedPolicies=" + failedPolicies + + ", loadedPIPConfigs=" + loadedPIPConfigs + + ", failedPIPConfigs=" + failedPIPConfigs + "]"; + } + + +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/OperationHistoryEngine.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/OperationHistoryEngine.java new file mode 100644 index 000000000..f99855cf9 --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/OperationHistoryEngine.java @@ -0,0 +1,297 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.std.pip.engines; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Properties; +import java.util.Set; + +import javax.persistence.EntityManager; +import javax.persistence.Persistence; +import javax.persistence.Query; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.eclipse.persistence.config.PersistenceUnitProperties; + +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.XACML; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.api.pip.PIPException; +import com.att.research.xacml.api.pip.PIPFinder; +import com.att.research.xacml.api.pip.PIPRequest; +import com.att.research.xacml.api.pip.PIPResponse; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdMutableAttribute; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacml.std.pip.StdMutablePIPResponse; +import com.att.research.xacml.std.pip.StdPIPRequest; +import com.att.research.xacml.std.pip.StdPIPResponse; +import com.att.research.xacml.std.pip.engines.StdConfigurableEngine; +import com.att.research.xacml.util.XACMLProperties; + +/** + * PIP Engine for Implementing {@link com.att.research.xacml.std.pip.engines.ConfigurableEngine} interface to provide + * attribute retrieval from Operation History Table. + * + * @version $Revision$ + */ +public class OperationHistoryEngine extends StdConfigurableEngine{ + public static final String DEFAULT_DESCRIPTION = "PIP for retrieving Operations History from DB"; + public static final String DEFAULT_ISSUER = "org:onap:xacml:guard:historydb"; + + private static final Log LOGGER= LogFactory.getLog(OperationHistoryEngine.class); + + private static final PIPRequest PIP_REQUEST_ACTOR = new StdPIPRequest( + XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("actor"), + XACML.ID_DATATYPE_STRING); + + private static final PIPRequest PIP_REQUEST_RECIPE = new StdPIPRequest( + XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("recipe"), + XACML.ID_DATATYPE_STRING); + + private static final PIPRequest PIP_REQUEST_TARGET = new StdPIPRequest( + XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("target"), + XACML.ID_DATATYPE_STRING); + + private void addIntegerAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, int value, PIPRequest pipRequest) { + AttributeValue attributeValue = null; + try { + attributeValue = DataTypes.DT_INTEGER.createAttributeValue(value); + } catch (Exception ex) { + LOGGER.error("Failed to convert " + value + " to an AttributeValue", ex); + } + if (attributeValue != null) { + stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, pipRequest.getIssuer()/*this.getIssuer()*/, false)); + } + } + + public OperationHistoryEngine() { + super(); + } + + @Override + public Collection attributesRequired() { + return new ArrayList<>(); + } + + @Override + public Collection attributesProvided() { + return new ArrayList<>(); + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { + LOGGER.info("Entering FeqLimiter PIP"); + /* + * First check to see if the issuer is set and then match it + */ + String string; + if ((string = pipRequest.getIssuer()) == null) { + LOGGER.info("FeqLimiter PIP - No issuer in the request!"); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } + else{ + //Notice, we are checking here for the base issuer prefix. + if (!string.contains(this.getIssuer())) { + LOGGER.debug("Requested issuer '" + string + "' does not match " + (this.getIssuer() == null ? "null" : "'" + this.getIssuer() + "'")); + LOGGER.info("FeqLimiter PIP - Issuer "+ string +" does not match with: "+this.getIssuer()); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } + } + String[] s1 = string.split("tw:"); + String[] s2 = s1[1].split(":"); + int timeWindowVal = Integer.parseInt(s2[0]);// number [of minutes, hours, days...] + String timeWindowScale = s2[1];//e.g., minute, hour, day, week, month, year + String actor = getActor(pipFinder).iterator().next(); + String operation = getRecipe(pipFinder).iterator().next(); + String target = getTarget(pipFinder).iterator().next(); + String timeWindow = timeWindowVal + " " + timeWindowScale; + LOGGER.info("Going to query DB about: "+actor + " " + operation + " " + target + " " + timeWindow); + int countFromDB = getCountFromDB(actor, operation, target, timeWindowVal, timeWindowScale); + StdMutablePIPResponse stdPIPResponse = new StdMutablePIPResponse(); + this.addIntegerAttribute(stdPIPResponse, + XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, + new IdentifierImpl("count"), + countFromDB, + pipRequest); + return new StdPIPResponse(stdPIPResponse); + } + + @Override + public void configure(String id, Properties properties) throws PIPException { + super.configure(id, properties); + if (this.getDescription() == null) { + this.setDescription(DEFAULT_DESCRIPTION); + } + if (this.getIssuer() == null) { + this.setIssuer(DEFAULT_ISSUER); + } + } + + private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { + PIPResponse pipResponse = null; + try { + pipResponse = pipFinder.getMatchingAttributes(pipRequest, this); + if (pipResponse.getStatus() != null && !pipResponse.getStatus().isOk()) { + LOGGER.info("Error retrieving " + pipRequest.getAttributeId().stringValue() + ": " + pipResponse.getStatus().toString()); + pipResponse = null; + } + if (pipResponse!=null && pipResponse.getAttributes().isEmpty()) { + LOGGER.info("No value for " + pipRequest.getAttributeId().stringValue()); + pipResponse = null; + } + } catch (PIPException ex) { + LOGGER.error("PIPException getting subject-id attribute: " + ex.getMessage(), ex); + } + return pipResponse; + } + + + private Set getActor(PIPFinder pipFinder) { + /* + * Get the AT&T UID from either the subject id or the attuid property + */ + PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_ACTOR, pipFinder); + if (pipResponseATTUID == null) { + return new HashSet<>(); + } + /* + * Iterate over all of the returned results and do the LDAP requests + */ + Collection listATTUIDs = pipResponseATTUID.getAttributes(); + Set setATTUIDs = new HashSet<>(); + for (Attribute attributeATTUID: listATTUIDs) { + Iterator> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); + if (iterAttributeValues != null) { + while (iterAttributeValues.hasNext()) { + String attuid = iterAttributeValues.next().getValue(); + if (attuid != null) { + setATTUIDs.add(attuid); + } + } + } + } + return setATTUIDs; + } + + private Set getRecipe(PIPFinder pipFinder) { + /* + * Get the AT&T UID from either the subject id or the attuid property + */ + PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_RECIPE, pipFinder); + if (pipResponseATTUID == null) { + return new HashSet<>(); + } + /* + * Iterate over all of the returned results and do the LDAP requests + */ + Collection listATTUIDs = pipResponseATTUID.getAttributes(); + Set setATTUIDs = new HashSet<>(); + for (Attribute attributeATTUID: listATTUIDs) { + Iterator> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); + if (iterAttributeValues != null) { + while (iterAttributeValues.hasNext()) { + String attuid = iterAttributeValues.next().getValue(); + if (attuid != null) { + setATTUIDs.add(attuid); + } + } + } + } + return setATTUIDs; + } + + + private Set getTarget(PIPFinder pipFinder) { + /* + * Get the AT&T UID from either the subject id or the attuid property + */ + PIPResponse pipResponseATTUID = this.getAttribute(PIP_REQUEST_TARGET, pipFinder); + if (pipResponseATTUID == null) { + return new HashSet<>(); + } + /* + * Iterate over all of the returned results and do the LDAP requests + */ + Collection listATTUIDs = pipResponseATTUID.getAttributes(); + Set setATTUIDs = new HashSet<>(); + for (Attribute attributeATTUID: listATTUIDs) { + Iterator> iterAttributeValues = attributeATTUID.findValues(DataTypes.DT_STRING); + if (iterAttributeValues != null) { + while (iterAttributeValues.hasNext()) { + String attuid = iterAttributeValues.next().getValue(); + if (attuid != null) { + setATTUIDs.add(attuid); + } + } + } + } + return setATTUIDs; + } + + private static int getCountFromDB(String actor, String operation, String target, int timeWindow, String timeUnits){ + EntityManager em; + try{ + Properties properties = XACMLProperties.getProperties(); + properties.setProperty(PersistenceUnitProperties.ECLIPSELINK_PERSISTENCE_XML, "META-INF/operationHistoryPU.xml"); + em = Persistence.createEntityManagerFactory("OperationsHistoryPU",properties).createEntityManager(); + }catch(Exception e){ + LOGGER.error("Test thread got Exception " + e.getLocalizedMessage() + " Can't connect to Operations History DB.", e); + return -1; + } + // Preventing SQL injection + if(!validTimeUnits(timeUnits)){ + LOGGER.error("given PIP timeUnits is not valid. " + timeUnits); + em.close(); + return -1; + } + String sql = "select count(*) as count from operationshistory10 where outcome<>'Failure_Guard' and actor=?" + + " and operation=?" + + " and target=?" + + " and endtime between date_sub(now(),interval ? "+timeUnits+") and now()"; + Query nq = em.createNativeQuery(sql); + nq.setParameter(1, actor); + nq.setParameter(2, operation); + nq.setParameter(3, target); + nq.setParameter(4, timeWindow); + int ret = ((Number)nq.getSingleResult()).intValue(); + LOGGER.info("###########************** History count: " + ret); + em.close(); + return ret; + } + + // Validating Time Units to prevent SQL Injection. + private static boolean validTimeUnits(String timeUnits) { + return (timeUnits.equalsIgnoreCase("minute") || timeUnits.equalsIgnoreCase("hour") || timeUnits.equalsIgnoreCase("day") + || timeUnits.equalsIgnoreCase("week") || timeUnits.equalsIgnoreCase("month")||timeUnits.equalsIgnoreCase("year"))? + true: false; + } +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/aaf/AAFEngine.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/aaf/AAFEngine.java new file mode 100644 index 000000000..ee75c5f8e --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/std/pip/engines/aaf/AAFEngine.java @@ -0,0 +1,272 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.std.pip.engines.aaf; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.onap.policy.utils.AAFPolicyClient; +import org.onap.policy.utils.AAFPolicyException; + +import com.att.research.xacml.api.Attribute; +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.api.pip.PIPException; +import com.att.research.xacml.api.pip.PIPFinder; +import com.att.research.xacml.api.pip.PIPRequest; +import com.att.research.xacml.api.pip.PIPResponse; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdMutableAttribute; +import com.att.research.xacml.std.datatypes.DataTypes; +import com.att.research.xacml.std.pip.StdMutablePIPResponse; +import com.att.research.xacml.std.pip.StdPIPRequest; +import com.att.research.xacml.std.pip.StdPIPResponse; +import com.att.research.xacml.std.pip.engines.StdConfigurableEngine; +import com.att.research.xacml.util.XACMLProperties; + +/** + * PIP Engine for Implementing {@link com.att.research.xacml.std.pip.engines.ConfigurableEngine} interface to provide + * attribute retrieval from AAF interface. + * + * @version $Revision$ + */ +public class AAFEngine extends StdConfigurableEngine { + + public static final String DEFAULT_DESCRIPTION = "PIP for authenticating aaf attributes using the AAF REST interface"; + public static final String DEFAULT_ISSUER = "aaf"; + + private static final String SUCCESS = "Success"; + + public static final String AAF_RESULT= "AAF_RESULT"; + public static final String AAF_RESPONSE= "AAF_RESPONSE"; + // + public static final Identifier AAF_RESPONSE_ID = new IdentifierImpl(AAF_RESPONSE); + public static final Identifier AAF_RESULT_ID = new IdentifierImpl(AAF_RESULT); + + // + private static final PIPRequest PIP_REQUEST_UID = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("AAF_ID"), XACML3.ID_DATATYPE_STRING); + private static final PIPRequest PIP_REQUEST_PASS = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("AAF_PASS"), XACML3.ID_DATATYPE_STRING); + private static final PIPRequest PIP_REQUEST_TYPE = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("AAF_TYPE"), XACML3.ID_DATATYPE_STRING); + private static final PIPRequest PIP_REQUEST_INSTANCE = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("AAF_INSTANCE"), XACML3.ID_DATATYPE_STRING); + private static final PIPRequest PIP_REQUEST_ACTION = new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, new IdentifierImpl("AAF_ACTION"), XACML3.ID_DATATYPE_STRING); + + private static final List mapRequiredAttributes = new ArrayList<>(); + static{ + mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_UID)); + mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_PASS)); + mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_TYPE)); + mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_INSTANCE)); + mapRequiredAttributes.add(new StdPIPRequest(PIP_REQUEST_ACTION)); + } + + private static final Map mapSupportedAttributes = new HashMap<>(); + static{ + mapSupportedAttributes.put(new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESPONSE_ID, XACML3.ID_DATATYPE_STRING), "response"); + mapSupportedAttributes.put(new StdPIPRequest(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESULT_ID, XACML3.ID_DATATYPE_BOOLEAN), "result"); + } + + protected Log logger = LogFactory.getLog(this.getClass()); + + public AAFEngine(){ + //default constructor + } + + private PIPResponse getAttribute(PIPRequest pipRequest, PIPFinder pipFinder) { + PIPResponse pipResponse = null; + try { + pipResponse = pipFinder.getMatchingAttributes(pipRequest, this); + if (pipResponse.getStatus() != null && !pipResponse.getStatus().isOk()) { + this.logger.warn("Error retrieving " + pipRequest.getAttributeId().stringValue() + ": " + pipResponse.getStatus().toString()); + pipResponse = null; + } + if (pipResponse != null && pipResponse.getAttributes().isEmpty()) { + this.logger.warn("No value for " + pipRequest.getAttributeId().stringValue()); + pipResponse = null; + } + } catch (PIPException ex) { + this.logger.error("PIPException getting subject-id attribute: " + ex.getMessage(), ex); + } + return pipResponse; + } + + private String getValue(PIPResponse pipResponse){ + String result = null; + Collection listAttributes = pipResponse.getAttributes(); + for(Attribute attribute: listAttributes){ + Iterator> iterAttributeValues = attribute.findValues(DataTypes.DT_STRING); + if(iterAttributeValues!=null) { + while(iterAttributeValues.hasNext()){ + result = iterAttributeValues.next().getValue(); + break; + } + } + } + return result; + } + + private synchronized String getResult(PIPFinder pipFinder) { + PIPResponse pipResponseUID = this.getAttribute(PIP_REQUEST_UID, pipFinder); + PIPResponse pipResponsePass = this.getAttribute(PIP_REQUEST_PASS, pipFinder); + PIPResponse pipResponseType = this.getAttribute(PIP_REQUEST_TYPE, pipFinder); + PIPResponse pipResponseAction = this.getAttribute(PIP_REQUEST_ACTION, pipFinder); + PIPResponse pipResponseInstance = this.getAttribute(PIP_REQUEST_INSTANCE, pipFinder); + String response = null; + // Evaluate AAF if we have all the required values. + if(pipResponseUID!=null && pipResponsePass!=null && pipResponseType != null && pipResponseAction!= null && pipResponseInstance!=null){ + String userName = getValue(pipResponseUID); + String pass = getValue(pipResponsePass); + + AAFPolicyClient aafClient = null; + Properties properties; + try { + properties = XACMLProperties.getProperties(); + logger.debug("environment : " + properties.getProperty("ENVIRONMENT")); + } catch (IOException e1) { + logger.error("Exception while getting the properties " + e1); + properties = new Properties(); + properties.setProperty("AAF_LOG_LEVEL", "DEBUG"); + } + if(userName!=null && pass!=null){ + try { + aafClient = AAFPolicyClient.getInstance(properties); + } catch (AAFPolicyException e) { + logger.error("AAF configuration failed. " + e.getMessage() +e); + } + if(aafClient!=null){ + if(aafClient.checkAuth(userName, pass)){ + String type = getValue(pipResponseType); + String instance = getValue(pipResponseInstance); + String action = getValue(pipResponseAction); + if(aafClient.checkPerm(userName, pass, type, instance, action)){ + response = SUCCESS + "Permissions Validated"; + }else{ + response = "No Permissions for "+userName+" to: "+type+", "+instance+", "+action; + } + }else{ + response = "Authentication Failed for the given Values"; + } + } + }else{ + response = "ID and Password are not given"; + } + + }else{ + response = "Insufficient Values to Evaluate AAF"; + } + return response; + } + + private void addStringAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, String value) { + if (value != null) { + AttributeValue attributeValue = null; + try { + attributeValue = DataTypes.DT_STRING.createAttributeValue(value); + } catch (Exception ex) { + this.logger.error("Failed to convert " + value + " to an AttributeValue", ex); + } + if (attributeValue != null) { + stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, this.getIssuer(), false)); + } + } + } + + private void addBooleanAttribute(StdMutablePIPResponse stdPIPResponse, Identifier category, Identifier attributeId, boolean value) { + AttributeValue attributeValue = null; + try { + attributeValue = DataTypes.DT_BOOLEAN.createAttributeValue(value); + } catch (Exception ex) { + this.logger.error("Failed to convert " + value + " to an AttributeValue", ex); + } + if (attributeValue != null) { + stdPIPResponse.addAttribute(new StdMutableAttribute(category, attributeId, attributeValue, this.getIssuer(), false)); + } + } + + @Override + public PIPResponse getAttributes(PIPRequest pipRequest, PIPFinder pipFinder) throws PIPException { + /* + * First check to see if the issuer is set and then match it + */ + String string; + + if((string = pipRequest.getIssuer()) != null && !string.equals(this.getIssuer())) { + this.logger.debug("Requested issuer '" + string + "' does not match " + (this.getIssuer() == null ? "null" : "'" + this.getIssuer() + "'")); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } + + + /* + * Drop the issuer and see if the request matches any of our supported queries + */ + PIPRequest pipRequestSupported = (pipRequest.getIssuer() == null ? pipRequest : new StdPIPRequest(pipRequest.getCategory(), pipRequest.getAttributeId(), pipRequest.getDataTypeId())); + if (!mapSupportedAttributes.containsKey(pipRequestSupported)) { + this.logger.debug("Requested attribute '" + pipRequest.toString() + "' is not supported"); + return StdPIPResponse.PIP_RESPONSE_EMPTY; + } + StdMutablePIPResponse stdPIPResponse = new StdMutablePIPResponse(); + String response = this.getResult(pipFinder); + boolean result = false; + if(response != null && response.contains(SUCCESS)){ + result = true; + } + this.addBooleanAttribute(stdPIPResponse, XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESULT_ID, result); + this.addStringAttribute(stdPIPResponse, XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE, AAF_RESPONSE_ID, response); + return new StdPIPResponse(stdPIPResponse); + } + + @Override + public void configure(String id, Properties properties) throws PIPException { + super.configure(id, properties); + if (this.getDescription() == null) { + this.setDescription(DEFAULT_DESCRIPTION); + } + if (this.getIssuer() == null) { + this.setIssuer(DEFAULT_ISSUER); + } + } + + @Override + public Collection attributesRequired() { + List attributes = new ArrayList<>(); + for (PIPRequest attribute: mapRequiredAttributes) { + attributes.add(new StdPIPRequest(attribute)); + } + return attributes; + } + + @Override + public Collection attributesProvided() { + List attributes = new ArrayList<>(); + for (PIPRequest attribute : mapSupportedAttributes.keySet()) { + attributes.add(new StdPIPRequest(attribute)); + } + return attributes; + } + +} \ No newline at end of file diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/MetricsUtil.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/MetricsUtil.java new file mode 100644 index 000000000..91e99b88b --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/MetricsUtil.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.util; + +public class MetricsUtil { + + public static class AvgLatency { + private long cumLatency = 0; + private long count = 0; + + public void compute(long latency) { + cumLatency += latency; + count++; + } + + public long avg() { + if (count == 0) + return 0; + + return (cumLatency / count); + } + + public void reset() { + cumLatency = 0; + count = 0; + } + } + + public static class MinLatency { + private long min = Long.MAX_VALUE; + + public synchronized void compute(long ts) { + if (ts < min) + min = ts; + } + + public long min() { + return min; + } + + public void reset() { + min = Long.MAX_VALUE; + } + } + + public static class MaxLatency { + private long max = Long.MIN_VALUE; + + public synchronized void compute(long ts) { + if (ts > max) + max = ts; + } + + public long max() { + return max; + } + + public void reset() { + max = Long.MIN_VALUE; + } + } + +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyScanner.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyScanner.java new file mode 100644 index 000000000..b43299e4e --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyScanner.java @@ -0,0 +1,722 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.util; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.Unmarshaller; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + +import com.att.research.xacml.api.AttributeAssignment; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdAttribute; +import com.att.research.xacml.std.StdAttributeAssignment; +import com.att.research.xacml.std.StdAttributeValue; +import com.att.research.xacml.std.StdMutableAdvice; +import com.att.research.xacml.std.StdMutableObligation; +import com.att.research.xacml.util.XACMLPolicyScanner.Callback; +import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult; + +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.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.IdReferenceType; +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.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; + +/** + * class XACMLPolicyScanner + * + * This class traverses the hierarchy of a XACML 3.0 policy. You can optionally pass a Callback class + * and override any desired methods to retrieve information from a policy. + * + * + */ +public class XACMLPolicyScanner { + + private static final Log logger = LogFactory.getLog(XACMLPolicyScanner.class); + private Object policyObject = null; + private Callback callback = null; + + public XACMLPolicyScanner(Path filename, Callback callback) { + try (InputStream is = Files.newInputStream(filename)) { + this.policyObject = XACMLPolicyScanner.readPolicy(is); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy"); + } + this.callback = callback; + } + + public XACMLPolicyScanner(InputStream filename, Callback callback) { + try (InputStream is = filename) { + this.policyObject = XACMLPolicyScanner.readPolicy(is); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy"); + } + this.callback = callback; + } + + public XACMLPolicyScanner(PolicySetType policySet, Callback callback) { + this.policyObject = policySet; + this.callback = callback; + } + + public XACMLPolicyScanner(PolicySetType policySet) { + this(policySet, null); + } + + public XACMLPolicyScanner(PolicyType policy, Callback callback) { + this.policyObject = policy; + this.callback = callback; + } + + public XACMLPolicyScanner(PolicyType policy) { + this(policy, null); + } + + /** + * Sets the callback interface to be used. + * + * @param cb + */ + public void setCallback(Callback cb) { + this.callback = cb; + } + + /** + * Saves the given callback object then calls the scan() method. + * + * @param cb + * @return + */ + public Object scan(Callback cb) { + this.callback = cb; + return this.scan(); + } + + /** + * + * This begins the scanning of the contained object. + * + * @return - The PolicySet/Policy that was scanned. + */ + public Object scan() { + if (this.policyObject == null) { + return null; + } + if (this.callback != null) { + if (this.callback.onBeginScan(this.policyObject) == CallbackResult.STOP) { + return this.policyObject; + } + } + if (this.policyObject instanceof PolicyType) { + this.scanPolicy(null, (PolicyType) this.policyObject); + } else if (this.policyObject instanceof PolicySetType) { + this.scanPolicySet(null, (PolicySetType) this.policyObject); + } else { + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + "Unknown class type: " + this.policyObject.getClass().getCanonicalName()); + } + if (this.callback != null) { + this.callback.onFinishScan(this.policyObject); + } + return this.policyObject; + } + + /** + * This performs the scan of a PolicySet + * + * @param parent - Its parent PolicySet. Can be null if this is the root. + * @param policySet - The PolicySet object. + * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. + */ + /** + * @param parent + * @param policySet + * @return + */ + protected CallbackResult scanPolicySet(PolicySetType parent, PolicySetType policySet) { + if (logger.isTraceEnabled()) { + logger.trace("scanning policy set: " + policySet.getPolicySetId() + " " + policySet.getDescription()); + } + if (this.callback != null) { + if (this.callback.onPreVisitPolicySet(parent, policySet) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + // + // Scan its info + // + if (this.scanTarget(policySet, policySet.getTarget()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanObligations(policySet, policySet.getObligationExpressions()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanAdvice(policySet, policySet.getAdviceExpressions()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + // + // Iterate the policy sets and/or policies + // + List> list = policySet.getPolicySetOrPolicyOrPolicySetIdReference(); + for (JAXBElement element: list) { + if (element.getName().getLocalPart().equals("PolicySet")) { + if (this.scanPolicySet(policySet, (PolicySetType)element.getValue()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } else if (element.getName().getLocalPart().equals("Policy")) { + if (this.scanPolicy(policySet, (PolicyType)element.getValue()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } else if (element.getValue() instanceof IdReferenceType) { + if (element.getName().getLocalPart().equals("PolicySetIdReference")) { + + } else if (element.getName().getLocalPart().equals("PolicyIdReference")) { + + } + } else { + logger.warn("generating policy sets found unsupported element: " + element.getName().getNamespaceURI()); + } + } + if (this.callback != null) { + if (this.callback.onPostVisitPolicySet(parent, policySet) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + return CallbackResult.CONTINUE; + } + + /** + * + * This performs scanning of the Policy object. + * + * @param parent - The parent PolicySet of the policy. This can be null if this is a root Policy. + * @param policy - The policy being scanned. + * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. + */ + protected CallbackResult scanPolicy(PolicySetType parent, PolicyType policy) { + if (logger.isTraceEnabled()) { + logger.trace("scanning policy: " + policy.getPolicyId() + " " + policy.getDescription()); + } + if (this.callback != null) { + if (this.callback.onPreVisitPolicy(parent, policy) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + // + // Scan its info + // + if (this.scanTarget(policy, policy.getTarget()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanVariables(policy, policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanObligations(policy, policy.getObligationExpressions()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanAdvice(policy, policy.getAdviceExpressions()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + // + // Iterate the rules + // + List list = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + for (Object o: list) { + if (o instanceof RuleType) { + RuleType rule = (RuleType) o; + if (logger.isTraceEnabled()) { + logger.trace("scanning rule: " + rule.getRuleId() + " " + rule.getDescription()); + } + if (this.callback != null) { + if (this.callback.onPreVisitRule(policy, rule) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + if (this.scanTarget(rule, rule.getTarget()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanConditions(rule, rule.getCondition()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanObligations(rule, rule.getObligationExpressions()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.scanAdvice(rule, rule.getAdviceExpressions()) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + if (this.callback != null) { + if (this.callback.onPostVisitRule(policy, rule) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + } else if (o instanceof VariableDefinitionType) { + if (this.callback != null) { + if (this.callback.onVariable(policy, (VariableDefinitionType) o) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + } else { + if (logger.isDebugEnabled()) { + logger.debug("scanning policy rules found unsupported object:" + o.toString()); + } + } + } + if (this.callback != null) { + if (this.callback.onPostVisitPolicy(parent, policy) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + return CallbackResult.CONTINUE; + } + + /** + * Scans the given target for attributes. Its sole purpose is to return attributes found. + * + * @param parent - The parent PolicySet/Policy/Rule for the target. + * @param target - The target. + * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. + */ + protected CallbackResult scanTarget(Object parent, TargetType target) { + if (target == null) { + return CallbackResult.CONTINUE; + } + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + 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(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Finally down to the actual attribute + // + StdAttribute attribute = null; + AttributeValueType value = match.getAttributeValue(); + if (match.getAttributeDesignator() != null && value != null) { + AttributeDesignatorType designator = match.getAttributeDesignator(); + // + // The content may be tricky + // + attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()), + new IdentifierImpl(designator.getAttributeId()), + new StdAttributeValue>(new IdentifierImpl(value.getDataType()), value.getContent()), + designator.getIssuer(), + false); + } 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); + } else { + logger.warn("NULL designator/selector or value for match."); + } + if (attribute != null && this.callback != null) { + if (this.callback.onAttribute(parent, target, attribute) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + } + } + } + } + } + } + return CallbackResult.CONTINUE; + } + + /** + * Scan the list of obligations. + * + * @param parent - The parent PolicySet/Policy/Rule for the obligation. + * @param obligationExpressionsType - All the obligation expressions. + * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. + */ + protected CallbackResult scanObligations(Object parent, ObligationExpressionsType obligationExpressionsType) { + if (obligationExpressionsType == null) { + return CallbackResult.CONTINUE; + } + List expressions = obligationExpressionsType.getObligationExpression(); + if (expressions == null || expressions.size() == 0) { + return CallbackResult.CONTINUE; + } + for (ObligationExpressionType expression : expressions) { + StdMutableObligation ob = new StdMutableObligation(new IdentifierImpl(expression.getObligationId())); + List assignments = expression.getAttributeAssignmentExpression(); + if (assignments != null) { + for (AttributeAssignmentExpressionType assignment : assignments) { + // category is optional and may be null + IdentifierImpl categoryId = null; + if (assignment.getCategory() != null) { + categoryId = new IdentifierImpl(assignment.getCategory()); + } + AttributeAssignment attribute = new StdAttributeAssignment( + categoryId, + new IdentifierImpl(assignment.getAttributeId()), + assignment.getIssuer(), + new StdAttributeValue(null, null) + ); + ob.addAttributeAssignment(attribute); + } + } + if (this.callback != null) { + if (this.callback.onObligation(parent, expression, ob) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + } + return CallbackResult.CONTINUE; + } + + /** + * + * Scans the list of advice expressions returning each individually. + * + * @param parent - The parent PolicySet/Policy/Rule for the advice. + * @param adviceExpressionstype - The list of advice expressions. + * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. + */ + protected CallbackResult scanAdvice(Object parent, AdviceExpressionsType adviceExpressionstype) { + if (adviceExpressionstype == null) { + return CallbackResult.CONTINUE; + } + List expressions = adviceExpressionstype.getAdviceExpression(); + if (expressions == null || expressions.size() == 0) { + return CallbackResult.CONTINUE; + } + for (AdviceExpressionType expression : expressions) { + StdMutableAdvice ob = new StdMutableAdvice(new IdentifierImpl(expression.getAdviceId())); + List assignments = expression.getAttributeAssignmentExpression(); + if (assignments != null) { + for (AttributeAssignmentExpressionType assignment : assignments) { + IdentifierImpl categoryId = null; + if (assignment.getCategory() != null) { + categoryId = new IdentifierImpl(assignment.getCategory()); + } + AttributeAssignment attribute = new StdAttributeAssignment( + categoryId, + new IdentifierImpl(assignment.getAttributeId()), + assignment.getIssuer(), + new StdAttributeValue(null, null) + ); + ob.addAttributeAssignment(attribute); + } + } + if (this.callback != null) { + if (this.callback.onAdvice(parent, expression, ob) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + } + return CallbackResult.CONTINUE; + } + + /** + * Scans the list of variable definitions. + * + * @param policy - Policy object containing the variable definition. + * @param list - List of variable definitions. + * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. + */ + protected CallbackResult scanVariables(PolicyType policy, List list) { + if (list == null) { + return CallbackResult.CONTINUE; + } + for (Object o : list) { + if (o instanceof VariableDefinitionType) { + if (this.callback != null) { + if (this.callback.onVariable(policy, (VariableDefinitionType) o) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + } + } + + return CallbackResult.CONTINUE; + } + + /** + * Scans the list of conditions. + * + * @param rule + * @param condition + * @return + */ + protected CallbackResult scanConditions(RuleType rule, ConditionType condition) { + if (condition != null) { + if (this.callback != null) { + if (this.callback.onCondition(rule, condition) == CallbackResult.STOP) { + return CallbackResult.STOP; + } + } + } + return CallbackResult.CONTINUE; + } + + /** + * Reads the XACML XML policy file in and returns the version contained in the root Policy/PolicySet element. + * + * @param policy - The policy file. + * @return - The version string from the file (uninterpreted) + * @throws IOException + */ + public static String getVersion(Path policy) throws IOException { + Object data = null; + try (InputStream is = Files.newInputStream(policy)) { + data = XACMLPolicyScanner.readPolicy(is); + } catch (IOException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy"); + throw e; + } + if (data == null) { + logger.warn("Version is null."); + return null; + } + return getVersion(data); + } + + /** + * Reads the Policy/PolicySet element object and returns its current version. + * + * @param data - Either a PolicySet or Policy XACML type object. + * @return - The integer version value. -1 if it doesn't exist or was un-parsable. + */ + public static String getVersion(Object data) { + String version = null; + try { + if (data instanceof PolicySetType) { + version = ((PolicySetType)data).getVersion(); + } else if (data instanceof PolicyType) { + version = ((PolicyType)data).getVersion(); + } else { + if (data != null) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + data.getClass().getCanonicalName()); + } + return null; + } + if (version != null && version.length() > 0) { + return version; + } else { + logger.warn("No version set in policy"); + } + } catch (NumberFormatException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Invalid version contained in policy: " + version); + return null; + } + return null; + } + + /** + * Returns the Policy or PolicySet ID. + * + * @param data - A XACML 3.0 Policy or PolicySet element object. + * @return The policy/policyset's policy ID + */ + public static String getID(Object data) { + if (data instanceof PolicySetType) { + return ((PolicySetType)data).getPolicySetId(); + } else if (data instanceof PolicyType) { + return ((PolicyType)data).getPolicyId(); + } else { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + data.getClass().getCanonicalName()); + return null; + } + } + + public static List getCreatedByModifiedBy(Path policyPath) throws IOException{ + String createdBy = ""; + String modifiedBy= ""; + String cValue = "@CreatedBy:"; + String mValue = "@ModifiedBy:"; + for(String line: Files.readAllLines(policyPath)){ + line = line.replaceAll("\\s+", ""); + if(line.isEmpty()){ + continue; + } + if(line.contains("") && line.contains(cValue) && line.contains(mValue)){ + createdBy = line.substring(line.indexOf(cValue) + cValue.length(), line.lastIndexOf(cValue)); + modifiedBy = line.substring(line.indexOf(mValue) + mValue.length(), line.lastIndexOf(mValue)); + break; + } + } + return Arrays.asList(createdBy, modifiedBy); + } + + //get the Created Name of the User on reading the Xml file + public static String getCreatedBy(Path policyPath) throws IOException{ + String userId = ""; + String value = "@CreatedBy:"; + for(String line: Files.readAllLines(policyPath)){ + line = line.replaceAll("\\s+", ""); + if(line.isEmpty()){ + continue; + } + if(line.contains("") && line.contains(value)){ + userId = line.substring(line.indexOf(value) + value.length(), line.lastIndexOf(value)); + break; + } + } + return userId; + } + + //get the Modified Name of the User on reading the Xml file + public static String getModifiedBy(Path policyPath) throws IOException{ + String modifiedBy = ""; + String value = "@ModifiedBy:"; + for(String line: Files.readAllLines(policyPath)){ + line = line.replaceAll("\\s+", ""); + if(line.isEmpty()){ + continue; + } + if(line.contains("") && line.contains(value)){ + modifiedBy = line.substring(line.indexOf(value) + value.length(), line.lastIndexOf(value)); + break; + } + } + return modifiedBy; + } + + /** + * readPolicy - does the work to read in policy data from a file. + * + * @param policy - The path to the policy file. + * @return - The policy data object. This *should* be either a PolicySet or a Policy. + */ + public static Object readPolicy(InputStream is) { + try { + // + // Create a DOM parser + // + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + DocumentBuilder db = dbf.newDocumentBuilder(); + // + // Parse the policy file + // + Document doc = db.parse(is); + // + // Because there is no root defined in xacml, + // find the first element + // + NodeList nodes = doc.getChildNodes(); + Node node = nodes.item(0); + Element e = null; + if (node.getNodeType() == Node.ELEMENT_NODE) { + e = (Element) node; + // + // Is it a 3.0 policy? + // + if (e.getNamespaceURI().equals("urn:oasis:names:tc:xacml:3.0:core:schema:wd-17")) { + // + // A policyset or policy could be the root + // + if (e.getNodeName().endsWith("Policy")) { + // + // Now we can create the context for the policy set + // and unmarshall the policy into a class. + // + JAXBContext context = JAXBContext.newInstance(PolicyType.class); + Unmarshaller um = context.createUnmarshaller(); + JAXBElement root = um.unmarshal(e, PolicyType.class); + // + // Here is our policy set class + // + return root.getValue(); + } else if (e.getNodeName().endsWith("PolicySet")) { + // + // Now we can create the context for the policy set + // and unmarshall the policy into a class. + // + JAXBContext context = JAXBContext.newInstance(PolicySetType.class); + Unmarshaller um = context.createUnmarshaller(); + JAXBElement root = um.unmarshal(e, PolicySetType.class); + // + // Here is our policy set class + // + return root.getValue(); + } else { + if (logger.isDebugEnabled()) { + logger.debug("Not supported yet: " + e.getNodeName()); + } + } + } else { + logger.warn("unsupported namespace: " + e.getNamespaceURI()); + } + } else { + if (logger.isDebugEnabled()) { + logger.debug("No root element contained in policy " + + " Name: " + node.getNodeName() + " type: " + node.getNodeType() + + " Value: " + node.getNodeValue()); + } + } + } catch (Exception e) { + PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPolicyScanner", "Exception in readPolicy"); + } + return null; + } + + /** + * @return the policyObject + */ + public Object getPolicyObject() { + return policyObject; + } +} diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyWriter.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyWriter.java new file mode 100644 index 000000000..14c8ffde0 --- /dev/null +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyWriter.java @@ -0,0 +1,344 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.util; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Iterator; +import java.util.List; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; + +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; + + +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.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +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.TargetType; + +/** + * Helper static class for policy writing. + * + * + */ +public class XACMLPolicyWriter { + + /** + * Helper static class that does the work to write a policy set to a file on disk. + * + * + */ + public static Path writePolicyFile(Path filename, PolicySetType policySet) { + JAXBElement policySetElement = new ObjectFactory().createPolicySet(policySet); + try { + JAXBContext context = JAXBContext.newInstance(PolicySetType.class); + Marshaller m = context.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + m.marshal(policySetElement, filename.toFile()); + + if (Files.exists(filename)) { + return filename; + } else { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "File does not exist after marshalling."); + return null; + } + + } catch (JAXBException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed"); + return null; + } + } + + /** + * Helper static class that does the work to write a policy set to an output stream. + * + * + */ + public static void writePolicyFile(OutputStream os, PolicySetType policySet) { + JAXBElement policySetElement = new ObjectFactory().createPolicySet(policySet); + try { + JAXBContext context = JAXBContext.newInstance(PolicySetType.class); + Marshaller m = context.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + m.marshal(policySetElement, os); + } catch (JAXBException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed"); + } + } + + /** + * Helper static class that does the work to write a policy to a file on disk. + * + * + */ + public static Path writePolicyFile(Path filename, PolicyType policy) { + JAXBElement policyElement = new ObjectFactory().createPolicy(policy); + try { + JAXBContext context = JAXBContext.newInstance(PolicyType.class); + Marshaller m = context.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + m.marshal(policyElement, filename.toFile()); + + if (Files.exists(filename)) { + return filename; + } else { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "File does not exist after marshalling."); + return null; + } + + } catch (JAXBException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed"); + return null; + } + } + + + /** + * Helper static class that does the work to write a policy to a file on disk. + * + * + */ + public static InputStream getXmlAsInputStream(PolicyType policy) { + JAXBElement policyElement = new ObjectFactory().createPolicy(policy); + try { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + JAXBContext context = JAXBContext.newInstance(PolicyType.class); + Marshaller m = context.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + m.marshal(policyElement, byteArrayOutputStream); + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); + + return byteArrayInputStream; + + } catch (JAXBException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed"); + return null; + } + } + /** + * Helper static class that does the work to write a policy set to an output stream. + * + * + */ + public static void writePolicyFile(OutputStream os, PolicyType policy) { + JAXBElement policySetElement = new ObjectFactory().createPolicy(policy); + try { + JAXBContext context = JAXBContext.newInstance(PolicyType.class); + Marshaller m = context.createMarshaller(); + m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + m.marshal(policySetElement, os); + } catch (JAXBException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed"); + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static String changeFileNameInXmlWhenRenamePolicy(Path filename) { + + PolicyType policyType = null; + String extension = ""; + String domain = null; + String repository = "repository"; + if(filename.toString().contains("Config_")){ + domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.toString().length()+1), filename.toString().indexOf("Config_")); + }else if(filename.toString().contains("Action_")){ + domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.toString().length()+1), filename.toString().indexOf("Action_")); + }else if(filename.toString().contains("Decision_")){ + domain = filename.toString().substring(filename.toString().indexOf(repository) + (repository.toString().length()+1), filename.toString().indexOf("Decision_")); + } + if(domain.contains(File.separator)){ + domain = domain.replace(File.separator, "."); + } + try { + JAXBContext context = JAXBContext.newInstance(PolicyType.class); + Unmarshaller m = context.createUnmarshaller(); + JAXBElement policyElement = (JAXBElement) m.unmarshal(filename.toFile()); + policyType = policyElement.getValue(); + if (policyType != null) { + TargetType targetType = policyType.getTarget(); + List anyOfTypes = targetType.getAnyOf(); + for( Iterator anyOfIte = anyOfTypes.iterator(); anyOfIte.hasNext(); ){ + AnyOfType anyOfType = (AnyOfType) anyOfIte.next(); + List allOf = anyOfType.getAllOf(); + for( Iterator allOfIte = allOf.iterator(); allOfIte.hasNext(); ){ + AllOfType allOfType = (AllOfType) allOfIte.next(); + List match = allOfType.getMatch(); + for( Iterator matchIte = match.iterator(); matchIte.hasNext();) { + MatchType matchType = (MatchType) matchIte.next(); + if(matchType.getAttributeDesignator().getAttributeId().equals("PolicyName")){ + AttributeValueType attributeValueType = matchType.getAttributeValue(); + List contents = attributeValueType.getContent(); + if (contents != null && contents.size() > 0) { + String value = (String) contents.get(0); + String version = value; + version = version.substring(0, version.lastIndexOf(".")); + version = version.substring(version.lastIndexOf(".")); + if(filename.toString().contains("Config_")){ + value = value.substring(0, value.indexOf("Config_")); + }else{ + value = value.substring(0, value.indexOf("Decision_")); + } + String tmp = filename.getFileName()+""; + String newName = tmp.substring(0, tmp.lastIndexOf(".")); + attributeValueType.getContent().clear(); + attributeValueType.getContent().add(domain + newName + "." + "xml"); + } + } + } + } + } + if(filename.toString().contains("Config_") || filename.toString().contains("Action_")){ + List objects = policyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + if (objects != null && objects.size() > 0) { + for (Iterator ite = objects.iterator(); ite.hasNext();) { + + RuleType ruleType = (RuleType ) ite.next(); + AdviceExpressionsType adviceExpressionsType = ruleType.getAdviceExpressions(); + if (adviceExpressionsType != null) { + List adviceExpressionTypes = adviceExpressionsType.getAdviceExpression(); + if (adviceExpressionTypes != null && adviceExpressionTypes.size() > 0) { + for (Iterator iterator = adviceExpressionTypes + .iterator(); iterator.hasNext();) { + AdviceExpressionType adviceExpressionType = (AdviceExpressionType) iterator + .next(); + if (adviceExpressionType.getAdviceId() != null && !adviceExpressionType.getAdviceId().equals("") && (adviceExpressionType.getAdviceId().equals("configID") + || adviceExpressionType.getAdviceId().equals("faultID") || adviceExpressionType.getAdviceId().equals("PMID")||adviceExpressionType.getAdviceId().equals("firewallConfigID") + || adviceExpressionType.getAdviceId().equals("MSID")) || adviceExpressionType.getAdviceId().equals("GocID")||adviceExpressionType.getAdviceId().equals("GocHPID")||adviceExpressionType.getAdviceId().equals("BRMSRAWID") + ||adviceExpressionType.getAdviceId().equals("BRMSPARAMID")|| adviceExpressionType.getAdviceId().equals("HPSuppID") || adviceExpressionType.getAdviceId().equals("HPFlapID") || adviceExpressionType.getAdviceId().equals("HPOverID")) + { + List attributeAssignmentExpressionTypes = adviceExpressionType.getAttributeAssignmentExpression(); + if (attributeAssignmentExpressionTypes != null && attributeAssignmentExpressionTypes.size() > 0) { + for (Iterator iterator2 = attributeAssignmentExpressionTypes + .iterator(); iterator2.hasNext();) { + AttributeAssignmentExpressionType attributeAssignmentExpressionType = (AttributeAssignmentExpressionType) iterator2 + .next(); + if (attributeAssignmentExpressionType.getAttributeId().equals("URLID")) { + JAXBElement attributeValueType = (JAXBElement) attributeAssignmentExpressionType.getExpression(); + AttributeValueType attributeValueType1 = attributeValueType.getValue(); + String configUrl = "$URL"; + String urlVal = (String) attributeValueType1.getContent().get(0); + String origExtension = urlVal.substring(urlVal.lastIndexOf('.')+1).trim(); + extension = origExtension; + attributeValueType1.getContent().clear(); + String txtFileName = filename.getFileName().toString(); + txtFileName = txtFileName.substring(0, txtFileName.lastIndexOf(".")+1) + origExtension; + txtFileName = configUrl+ File.separator + "Config" + File.separator + domain + txtFileName; + attributeValueType1.getContent().add(txtFileName); + } else if (attributeAssignmentExpressionType.getAttributeId().equals("PolicyName")) { + JAXBElement attributeValueType = (JAXBElement) attributeAssignmentExpressionType.getExpression(); + AttributeValueType attributeValueType1 = attributeValueType.getValue(); + List contents = attributeValueType1.getContent(); + if (contents != null && contents.size() > 0) { + String value = (String) contents.get(0); + String version = value; + version = version.substring(0, version.lastIndexOf(".")); + version = version.substring(version.lastIndexOf(".")); + value = value.substring(0, value.indexOf("Config_")); + String tmp = filename.getFileName()+""; + String newName = tmp.substring(0, tmp.lastIndexOf(".")); + attributeValueType1.getContent().clear(); + attributeValueType1.getContent().add(domain + newName + "." + "xml"); + } + + } + + } + } + } + } + } + } + } + if (objects != null && objects.size() > 0) { + for (Iterator ite1 = objects.iterator(); ite1.hasNext();) { + + RuleType ruleType1 = (RuleType ) ite1.next(); + ObligationExpressionsType obligationExpressionsType = ruleType1.getObligationExpressions(); + if (obligationExpressionsType != null) { + List obligationExpressionType = obligationExpressionsType.getObligationExpression(); + if (obligationExpressionType != null && obligationExpressionType.size() > 0) { + for (Iterator iterator = obligationExpressionType + .iterator(); iterator.hasNext();) { + ObligationExpressionType obligationExpressionTypes = (ObligationExpressionType) iterator + .next(); + if (obligationExpressionTypes.getObligationId() != null && !obligationExpressionTypes.getObligationId().equals("")) { + List attributeAssignmentExpressionTypes = obligationExpressionTypes.getAttributeAssignmentExpression(); + if (attributeAssignmentExpressionTypes != null && attributeAssignmentExpressionTypes.size() > 0) { + for (Iterator iterator2 = attributeAssignmentExpressionTypes + .iterator(); iterator2.hasNext();) { + AttributeAssignmentExpressionType attributeAssignmentExpressionType = (AttributeAssignmentExpressionType) iterator2 + .next(); + if (attributeAssignmentExpressionType.getAttributeId().equals("body")) { + JAXBElement attributeValueType = (JAXBElement) attributeAssignmentExpressionType.getExpression(); + AttributeValueType attributeValueType1 = attributeValueType.getValue(); + String configUrl = "$URL"; + String urlVal = (String) attributeValueType1.getContent().get(0); + String origExtension = urlVal.substring(urlVal.lastIndexOf('.')+1).trim(); + extension = "json"; + attributeValueType1.getContent().clear(); + String txtFileName = filename.getFileName().toString(); + txtFileName = txtFileName.substring(0, txtFileName.lastIndexOf(".")+1) + origExtension; + txtFileName = configUrl+ File.separator + "Action" + File.separator + domain + txtFileName; + attributeValueType1.getContent().add(txtFileName); + } + + } + } + + } + + } + } + } + } + } + } + } + writePolicyFile(filename, policyType); + } + }catch (JAXBException e) { + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyWriter", "writePolicyFile failed"); + } + + return extension; + } + +} diff --git a/ECOMP-XACML/src/main/resources/META-INF/operationHistoryPU.xml b/ONAP-XACML/src/main/resources/META-INF/operationHistoryPU.xml similarity index 100% rename from ECOMP-XACML/src/main/resources/META-INF/operationHistoryPU.xml rename to ONAP-XACML/src/main/resources/META-INF/operationHistoryPU.xml diff --git a/ONAP-XACML/src/main/resources/xacml.properties b/ONAP-XACML/src/main/resources/xacml.properties new file mode 100644 index 000000000..5be3939cb --- /dev/null +++ b/ONAP-XACML/src/main/resources/xacml.properties @@ -0,0 +1,46 @@ +### +# ============LICENSE_START======================================================= +# ONAP-XACML +# ================================================================================ +# 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========================================================= +### + +# Default XACML Properties File +# Standard API Factories +# +xacml.dataTypeFactory=org.onap.policy.xacml.std.StdDataTypeFactory +xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory +xacml.pepEngineFactory=org.onap.policy.xacml.std.pep.StdEngineFactory +xacml.pipFinderFactory=org.onap.policy.xacml.std.pip.StdPIPFinderFactory + +# If there is a standard set of PIPEngines: +# xacml.pip.engines=engine1,engine2,...,engineN +# engine1.classname=com.att.research.xacmlpip.OraclePIP +# engine1.prop1=foo +# engine1.prop2=bar +# ... +# engine2.classname=com.att.research.xacmlpip.ActiveDirectoryPIP +# ... + +# AT&T PDP Implementation Factories +# +xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory +xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory +xacml.att.functionDefinitionFactory=com.att.research.xacmlatt.pdp.std.StdFunctionDefinitionFactory +xacml.att.policyFinderFactory=com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory + +# If there is a standard policy for the engine: +# xacml.att.stdPolicyFinderFactory.rootPolicyFile=/etc/stdpolicyset.xml diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdEngineFactoryTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdEngineFactoryTest.java new file mode 100644 index 000000000..3fa49551b --- /dev/null +++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/std/pap/StdEngineFactoryTest.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.test.std.pap; + +import static org.junit.Assert.assertTrue; + +import java.io.IOException; +import java.util.Properties; + +import org.junit.Test; +import org.onap.policy.xacml.std.pap.StdEngineFactory; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.util.FactoryException; + +public class StdEngineFactoryTest { + + + @Test + public void testStdEngineFactory() throws FactoryException, PAPException, IOException{ + + StdEngineFactory stdFactory = new StdEngineFactory(); + System.setProperty("xacml.pap.pdps", "src/test/resources/pdps"); + assertTrue(stdFactory.newEngine() != null); + Properties properties = new Properties(); + properties.setProperty("xacml.pap.pdps", "src/test/resources/pdps"); + assertTrue(stdFactory.newEngine(properties) != null); + + StdEngineFactory stdFactoryNew = new StdEngineFactory(); + System.setProperty("xacml.pap.pdps", "src/test/resources/pdpstest"); + assertTrue(stdFactoryNew.newEngine() != null); + + } +} diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/AAFEngineTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/AAFEngineTest.java new file mode 100644 index 000000000..65646e1e6 --- /dev/null +++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/AAFEngineTest.java @@ -0,0 +1,24 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.test.util; + +public class AAFEngineTest { + +} diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/MetricsUtilTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/MetricsUtilTest.java new file mode 100644 index 000000000..041acdee6 --- /dev/null +++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/MetricsUtilTest.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.test.util; + +import static org.junit.Assert.*; + +import org.junit.Test; +import org.onap.policy.xacml.util.MetricsUtil; + +public class MetricsUtilTest { + + @Test + public void metricsUtilTest(){ + MetricsUtil.AvgLatency avgLatency = new MetricsUtil.AvgLatency(); + avgLatency.compute(0); + assertTrue(avgLatency.avg() == 0); + avgLatency.compute(2); + assertTrue(avgLatency.avg() == 1); + avgLatency.reset(); + assertTrue(avgLatency.avg() == 0); + + MetricsUtil.MaxLatency maxLatency = new MetricsUtil.MaxLatency(); + maxLatency.compute(2); + assertTrue(maxLatency.max() == 2); + maxLatency.reset(); + assertTrue(maxLatency.max() < 0); + + MetricsUtil.MinLatency minLatency = new MetricsUtil.MinLatency(); + minLatency.compute(2); + assertTrue(minLatency.min() == 2); + minLatency.reset(); + assertTrue(minLatency.min() > 0); + } + +} diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/XACMLPolicyScannerTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/XACMLPolicyScannerTest.java new file mode 100644 index 000000000..09dcf837f --- /dev/null +++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/XACMLPolicyScannerTest.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.test.util; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.xacml.util.XACMLPolicyScanner; + +import com.att.research.xacml.util.XACMLPolicyScanner.Callback; + +public class XACMLPolicyScannerTest { + + private static final Log logger = LogFactory.getLog(XACMLPolicyScannerTest.class); + private static Path configPolicyPathValue; + private static Path actionPolicyPathValue; + + @Before + public void setUp() { + File templateFile; + ClassLoader classLoader = getClass().getClassLoader(); + try { + templateFile = new File(classLoader.getResource("Config_SampleTest1206.1.xml").getFile()); + configPolicyPathValue = templateFile.toPath(); + templateFile = new File(classLoader.getResource("Action_TestActionPolicy.1.xml").getFile()); + actionPolicyPathValue = templateFile.toPath(); + } catch (Exception e1) { + logger.error("Exception Occured"+e1); + } + } + + @Test + public void xacmlPolicyScannerTest() throws IOException{ + Callback callback = null; + try{ + XACMLPolicyScanner actionScanner = new XACMLPolicyScanner(actionPolicyPathValue, callback); + assertTrue(actionScanner.getPolicyObject() != null); + Object actionObject = actionScanner.scan(); + assertTrue(actionObject != null); + + XACMLPolicyScanner scanner = new XACMLPolicyScanner(configPolicyPathValue, callback); + assertTrue(scanner.getPolicyObject() != null); + Object object = scanner.scan(); + assertTrue(object != null); + String id = XACMLPolicyScanner.getID(scanner.getPolicyObject()); + assertTrue(id.equals("urn:com:xacml:policy:id:0b67998b-57e2-4e25-9ea9-f9154bf18df1")); + String version = XACMLPolicyScanner.getVersion(scanner.getPolicyObject()); + assertTrue(version.equals("1")); + String versionFromPath = XACMLPolicyScanner.getVersion(configPolicyPathValue); + assertTrue(versionFromPath.equals("1")); + List returnValue = XACMLPolicyScanner.getCreatedByModifiedBy(configPolicyPathValue); + assertTrue(returnValue.get(0).equals("test")); + String createdBy = XACMLPolicyScanner.getCreatedBy(configPolicyPathValue); + assertTrue(createdBy.equals("test")); + String modifiedBy = XACMLPolicyScanner.getModifiedBy(configPolicyPathValue); + assertTrue(modifiedBy.equals("test")); + }catch(Exception e){ + fail(); + logger.error("Exception Occured"+e); + } + } +} diff --git a/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/XACMLPolicyWriterTest.java b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/XACMLPolicyWriterTest.java new file mode 100644 index 000000000..c948716dc --- /dev/null +++ b/ONAP-XACML/src/test/java/org/onap/policy/xacml/test/util/XACMLPolicyWriterTest.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP-XACML + * ================================================================================ + * 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.xacml.test.util; + +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.xacml.util.XACMLPolicyWriter; + +public class XACMLPolicyWriterTest { + private static final Log logger = LogFactory.getLog(XACMLPolicyWriterTest.class); + private static Path configPolicyPathValue; + private static Path actionPolicyPathValue; + + @Before + public void setUp() { + File templateFile; + ClassLoader classLoader = getClass().getClassLoader(); + try { + templateFile = new File(classLoader.getResource("Config_SampleTest1206.1.xml").getFile()); + configPolicyPathValue = templateFile.toPath(); + templateFile = new File(classLoader.getResource("Action_TestActionPolicy.1.xml").getFile()); + actionPolicyPathValue = templateFile.toPath(); + } catch (Exception e1) { + logger.error("Exception Occured"+e1); + } + } + + @SuppressWarnings("static-access") + @Test + public void xacmlPolicyWriterTest() throws IOException{ + XACMLPolicyWriter writer = new XACMLPolicyWriter(); + String configResponseValue = writer.changeFileNameInXmlWhenRenamePolicy(configPolicyPathValue); + assertTrue(configResponseValue.equals("txt")); + String actionResponseValue = writer.changeFileNameInXmlWhenRenamePolicy(actionPolicyPathValue); + assertTrue(actionResponseValue.equals("json")); + } +} diff --git a/ONAP-XACML/src/test/resources/Action_TestActionPolicy.1.xml b/ONAP-XACML/src/test/resources/Action_TestActionPolicy.1.xml new file mode 100644 index 000000000..a3b483f74 --- /dev/null +++ b/ONAP-XACML/src/test/resources/Action_TestActionPolicy.1.xml @@ -0,0 +1,52 @@ + + + TestActionPolicy@CreatedBy:test@CreatedBy:@ModifiedBy:test@ModifiedBy: + + + + + 12 + + + + + + + + + + + + + + test + + + + + + Sample + + + + + + + PEPAction + + + REST + + + http://localhost.com + + + GET + + + $URL/Action/com.Action_TestActionPolicy.1.xml.json + + + + + \ No newline at end of file diff --git a/ONAP-XACML/src/test/resources/CSVPolicy.xml b/ONAP-XACML/src/test/resources/CSVPolicy.xml new file mode 100644 index 000000000..6396e66a1 --- /dev/null +++ b/ONAP-XACML/src/test/resources/CSVPolicy.xml @@ -0,0 +1,205 @@ + + + + + This Policy handles the Take action and Advice action operations. + + + + + Check the CPU Utilization or Network Load + + Load + + + + 95 + + + + CPU + + + + 95 + + + + + + Permit to create a new VM with Obligation + + + + + If the Requirement has met create the VM + + true + + + + + + Action_Info + + + + + Create_NEW_VM + + + + + + Permit to create a new VM with Advice + + + + + create_adviceAction + + + + + + + + If the Requirement has met create the VM + + true + + + + + + Action_Info + + + + + Created New VM + + + http://localhost:8080/pdp/?type=hb + + + + + + + + + + + + + + + + Permit to remove a VM with Obligation + + + + + remove_Action + + + + + + + + If the resource usage is low then remove the VM + + true + + + + + + Action_Info + + + + + Remove_VM + + + + + + Permit to remove a VM with Advice + + + + + remove_adviceAction + + + + + + + + If the resource usage is low then remove the VM + + true + + + + + + Action_Info + + + + + Removed VM + + + http://localhost:8080/pdp/?type=hb + + + + + diff --git a/ONAP-XACML/src/test/resources/Config_SampleTest1206.1.xml b/ONAP-XACML/src/test/resources/Config_SampleTest1206.1.xml new file mode 100644 index 000000000..dcfd0c5eb --- /dev/null +++ b/ONAP-XACML/src/test/resources/Config_SampleTest1206.1.xml @@ -0,0 +1,90 @@ + + + SampleTest1206@CreatedBy:test@CreatedBy:@ModifiedBy:test@ModifiedBy: + + + + + com.Config_SampleTest1206.1.xml + + + + + + success + + + + PROD + + + + 1 + + + + True + + + + 08-06-2017 + + + + SampleTest1206 + + + + + + + + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + $URL/Config/com.Config_SampleTest1206.1.txt + + + com.Config_SampleTest1206.1.xml + + + 1 + + + success + + + SampleTest1206 + + + PROD + + + 1 + + + True + + + 08-06-2017 + + + + + diff --git a/ONAP-XACML/src/test/resources/log4j.properties b/ONAP-XACML/src/test/resources/log4j.properties new file mode 100644 index 000000000..ee9cfa39b --- /dev/null +++ b/ONAP-XACML/src/test/resources/log4j.properties @@ -0,0 +1,42 @@ +### +# ============LICENSE_START======================================================= +# ONAP-XACML +# ================================================================================ +# 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========================================================= +### + +# +# Use this properties for debugging and development. +# +# +# Set root logger level to DEBUG and its only appender to A1. +log4j.rootLogger=INFO, MAIN_LOG + +# A1 is set to be a ConsoleAppender. +log4j.appender.MAIN_LOG=org.apache.log4j.ConsoleAppender + +# A1 uses PatternLayout. +log4j.appender.MAIN_LOG.layout=org.apache.log4j.PatternLayout +log4j.appender.MAIN_LOG.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} [%t] %-5p %l- %m%n + +# +# This is specifically for Xacml request/response logging +# +log4j.logger.xacml.request=INFO, REQUEST_LOG + +log4j.appender.REQUEST_LOG=org.apache.log4j.ConsoleAppender +log4j.appender.REQUEST_LOG.layout=org.apache.log4j.PatternLayout +log4j.appender.REQUEST_LOG.layout.ConversionPattern=%d{yyyy_MM_dd_HH_mm_ss_SSS} %m%n diff --git a/ONAP-XACML/src/test/resources/logback.xml b/ONAP-XACML/src/test/resources/logback.xml new file mode 100644 index 000000000..cd8e69414 --- /dev/null +++ b/ONAP-XACML/src/test/resources/logback.xml @@ -0,0 +1,253 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + --> + + + + + + + + + + + + + + + + + + + + ${defaultPattern} + + + + + + + + + + + + + ${logDirectory}/${auditLogName}.log + + ${logDirectory}/${auditLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + ${defaultAuditPattern} + + + + + 256 + + + + + + + + ${logDirectory}/${metricsLogName}.log + + ${logDirectory}/${metricsLogName}.%i.log.zip + + 1 + 9 + + + 5MB + + + + ${defaultMetricPattern} + + + + + 256 + + + + + + + + ${logDirectory}/${errorLogName}.log + + ${logDirectory}/${errorLogName}.%i.log.zip + + 1 + 9 + + + ERROR + + + 5MB + + + ${defaultErrorPattern} + + + + + 256 + + + + + + + ${debugLogDirectory}/${debugLogName}.log + + ${debugLogDirectory}/${debugLogName}.%i.log.zip + + 1 + 9 + + + INFO + + + 5MB + + + ${debugLoggerPattern} + + + + + 256 + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ONAP-XACML/src/test/resources/logging.properties b/ONAP-XACML/src/test/resources/logging.properties new file mode 100644 index 000000000..ff9840ff7 --- /dev/null +++ b/ONAP-XACML/src/test/resources/logging.properties @@ -0,0 +1,32 @@ +### +# ============LICENSE_START======================================================= +# ONAP-XACML +# ================================================================================ +# 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========================================================= +### + +handlers = java.util.logging.ConsoleHandler, java.util.logging.FileHandler + +.level = FINE + +java.util.logging.SimpleFormatter.format=%4$s: %5$s %n + +java.util.logging.ConsoleHandler.level = FINEST +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter + +java.util.logging.FileHandler.level = SEVERE +java.util.logging.FileHandler.pattern=%h/xacml_log%u.log +java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter diff --git a/ONAP-XACML/src/test/resources/pdps/default/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml b/ONAP-XACML/src/test/resources/pdps/default/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml new file mode 100644 index 000000000..e27f163b6 --- /dev/null +++ b/ONAP-XACML/src/test/resources/pdps/default/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml @@ -0,0 +1,93 @@ + + + vFW Demo Policy@CreatedBy:@CreatedBy:@ModifiedBy:@ModifiedBy: + + + + + com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml + + + + + + DROOLS + + + + BRMS_PARAM_RULE + + + + SampleRiskType + + + + 1 + + + + False + + + + NA + + + + + + + + + + + ACCESS + + + + Config + + + + + + + + + Configuration + + + $URL/Config/com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.txt + + + com.Config_BRMS_Param_BRMSParamvFWDemoPolicy.1.xml + + + 1 + + + DROOLS + + + BRMS_PARAM_RULE + + + vFW + + + SampleRiskType + + + 1 + + + False + + + NA + + + + + \ No newline at end of file diff --git a/ONAP-XACML/src/test/resources/pdps/default/xacml.pip.properties b/ONAP-XACML/src/test/resources/pdps/default/xacml.pip.properties new file mode 100644 index 000000000..846848f28 --- /dev/null +++ b/ONAP-XACML/src/test/resources/pdps/default/xacml.pip.properties @@ -0,0 +1,6 @@ +# +#Tue Feb 07 10:35:08 EST 2017 +AAF.description=AAFEngine to communicate with AAF to take decisions +AAF.classname=org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine +AAF.name=AAFEngine +xacml.pip.engines=AAF \ No newline at end of file diff --git a/ECOMP-XACML/src/test/resources/pdps/default/xacml.policy.properties b/ONAP-XACML/src/test/resources/pdps/default/xacml.policy.properties similarity index 100% rename from ECOMP-XACML/src/test/resources/pdps/default/xacml.policy.properties rename to ONAP-XACML/src/test/resources/pdps/default/xacml.policy.properties diff --git a/ECOMP-XACML/src/test/resources/pdps/xacml.properties b/ONAP-XACML/src/test/resources/pdps/xacml.properties similarity index 100% rename from ECOMP-XACML/src/test/resources/pdps/xacml.properties rename to ONAP-XACML/src/test/resources/pdps/xacml.properties diff --git a/ONAP-XACML/src/test/resources/xacml.pip.properties b/ONAP-XACML/src/test/resources/xacml.pip.properties new file mode 100644 index 000000000..ac1747728 --- /dev/null +++ b/ONAP-XACML/src/test/resources/xacml.pip.properties @@ -0,0 +1,23 @@ +### +# ============LICENSE_START======================================================= +# ONAP-XACML +# ================================================================================ +# 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========================================================= +### + +# +#Fri Mar 06 12:06:30 EST 2015 +xacml.pip.engines= diff --git a/ONAP-XACML/src/test/resources/xacml.policy.properties b/ONAP-XACML/src/test/resources/xacml.policy.properties new file mode 100644 index 000000000..8538b2331 --- /dev/null +++ b/ONAP-XACML/src/test/resources/xacml.policy.properties @@ -0,0 +1,25 @@ +### +# ============LICENSE_START======================================================= +# ONAP-XACML +# ================================================================================ +# 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========================================================= +### + +# +#Fri Mar 06 12:06:30 EST 2015 +xacml.referencedPolicies= +xacml.rootPolicies= + diff --git a/ONAP-XACML/testclient.properties b/ONAP-XACML/testclient.properties new file mode 100644 index 000000000..85d679e34 --- /dev/null +++ b/ONAP-XACML/testclient.properties @@ -0,0 +1,21 @@ +### +# ============LICENSE_START======================================================= +# ONAP-XACML +# ================================================================================ +# 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========================================================= +### + +test=test,MASTER diff --git a/ONAP-XACML/testpdp.properties b/ONAP-XACML/testpdp.properties new file mode 100644 index 000000000..23f02243a --- /dev/null +++ b/ONAP-XACML/testpdp.properties @@ -0,0 +1,21 @@ +### +# ============LICENSE_START======================================================= +# ONAP-XACML +# ================================================================================ +# 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========================================================= +### + +PDP_URL= , test, test diff --git a/ECOMP-XACML/testsets/conformance/xacml3.0-ct-v.0.4/IIA001Response.xml b/ONAP-XACML/testsets/conformance/xacml3.0-ct-v.0.4/IIA001Response.xml similarity index 100% rename from ECOMP-XACML/testsets/conformance/xacml3.0-ct-v.0.4/IIA001Response.xml rename to ONAP-XACML/testsets/conformance/xacml3.0-ct-v.0.4/IIA001Response.xml diff --git a/ONAP-XACML/xacml.pap.properties b/ONAP-XACML/xacml.pap.properties new file mode 100644 index 000000000..608ca232d --- /dev/null +++ b/ONAP-XACML/xacml.pap.properties @@ -0,0 +1,107 @@ +### +# ============LICENSE_START======================================================= +# ONAP-XACML +# ================================================================================ +# 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========================================================= +### + +# +# This is our factory that will create our engine +# +xacml.PAP.papEngineFactory=org.onap.policy.xacml.std.pap.StdEngineFactory + +# +# Where we store our PAP PDP Group/Node information +# +xacml.pap.pdps=pdps +# +# Need the PAP's url (how PDPs will reach it) configured here +# because we need it to generate the URLs of the Policy Files +# sent to the PDPs in the configuration when the PAP is first brought up. +# (In other cases, such as the PDP calling the PAP, we could generate this URL, +# but for startup there is no other way to get it.) +# +# + +xacml.rest.pap.url=http://localhost:8070/pap/ + +# +# Upon startup, have the PAP servlet send latest configuration information to all +# the PDP nodes it knows about. +# +xacml.rest.pap.initiate.pdp=true +# +# Heartbeat from PAP to PDPs +# +# How much time (in milliseconds) between heartbeats +# (i.e. the time between completing the heartbeat with all PDPs and starting the next cycle) +# +xacml.rest.pap.heartbeat.interval=10000 +# +# Heartbeat connection timeout (in milliseconds) +# +xacml.rest.pap.heartbeat.timeout=10000 + +################################################################################################ +# Adding properties for getting properties previously used by PAP-ADMIN for creating Policies +# THis is part of the Policy Creation API project +################################################################################################ + +# Set your domain here: +xacml.rest.pap.domain=com + +# Location where all the user workspaces are located. +xacml.rest.pap.workspace=workspace + +# Location where the GIT repository is located +xacml.rest.pap.repository=repository + +# new Property Please mention your PAP-REST webapps Location here. +xacml.rest.config.webapps=C:\\Second Tomcat\\apache-tomcat-8.0.23\\webapps\\ConfigPAP\\ + +#Turn the audit on to synchronize the DB/file system +#xacml.rest.pap.run.audit.flag=true +#Turn the audit off to not synchronize the DB/file system +#xacml.rest.pap.run.audit.flag=false +xacml.rest.pap.run.audit.flag=false + +#Audit will synchronize the file system to match the contents of the DB +#xacml.rest.pap.filesystem.audit=true +#Audit will synchronize the DB to match the contents of the file system +#xacml.rest.pap.filesystem.audit=false +xacml.rest.pap.filesystem.audit=false + +# id +xacml.rest.pap.userid=testpap +# pass +xacml.rest.pap.password=alpha123 +# pdps file +xacml.rest.pdp.idfile=test.properties + +#Properties for db access +javax.persistence.jdbc.driver=org.h2.Driver +javax.persistence.jdbc.url=jdbc:h2:file:./sql/xacmlTest +javax.persistence.jdbc.user=sa +javax.persistence.jdbc.password= + +#Time in ms which a Policy DB transaction will wait to get the transaction lock object +xacml.rest.pap.transaction.waitms=1000 + +#Policy DB transaction timeout in ms after it has obtained the transaction lock object +xacml.rest.pap.transaction.timeoutms=500 + +#Policy Audit timeout in ms after it has obtained the transaction lock object +xacml.rest.pap.audit.timeoutms=5000 diff --git a/ONAP-XACML/xacml.pdp.properties b/ONAP-XACML/xacml.pdp.properties new file mode 100644 index 000000000..b2687848b --- /dev/null +++ b/ONAP-XACML/xacml.pdp.properties @@ -0,0 +1,86 @@ +### +# ============LICENSE_START======================================================= +# ONAP-XACML +# ================================================================================ +# 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========================================================= +### + +# Default XACML Properties File for PDP RESTful servlet +# +# Standard API Factories +# +xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory +xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory +xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory +# NOT USED SEE BELOW xacml.pipFinderFactory=org.onap.policy.xacml.std.pip.StdPIPFinderFactory +xacml.traceEngineFactory=com.att.research.xacml.std.trace.LoggingTraceEngineFactory +# +# AT&T PDP Implementation Factories +# +xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory +xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory +xacml.att.functionDefinitionFactory=com.att.research.xacmlatt.pdp.std.StdFunctionDefinitionFactory +# NOT USED SEE BELOW xacml.att.policyFinderFactory=com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory + +# +# AT&T RESTful PDP Implementation Factories +# +xacml.pipFinderFactory=org.onap.policy.pdp.rest.impl.XACMLPdpPIPFinderFactory +xacml.att.policyFinderFactory=org.onap.policy.pdp.rest.impl.XACMLPdpPolicyFinderFactory +# +# When set to true, this flag tells the StdPolicyFinderFactory to combined all the root policy files into +# into one PolicySet and use the given Policy Algorithm. +# +xacml.att.policyFinderFactory.combineRootPolicies=urn:com:att:xacml:3.0:policy-combining-algorithm:combined-deny-overrides +# +# PDP RESTful API properties +# +# Set this to the address where the XACML-PAP-REST servlet is running +# http://localhost:9090/pap/ +xacml.rest.pap.url=http://localhost:8070/pap/ +# +# Give the running PDP an ID for the PAP. The url that its running as is a good choice. +# The PAP identifies PDP's using the URL of the PDP. +# +xacml.rest.pdp.id=http://localhost:8082/pdp/ +# +# Set the directory where the PDP holds its Policy Cache and PIP Configuration +# +xacml.rest.pdp.config=config_testing + +xacml.rest.pdp.webapps=/webapps + +xacml.rest.pdp.configparams=../webapps/configparams +# +# Initialize register with PAP servlet +# +xacml.rest.pdp.register=true +# +# Sleep period in seconds between register attempts +# +xacml.rest.pdp.register.sleep=15 +# +# number of attempts to register. -1 means keep trying forever. +# +xacml.rest.pdp.register.retries=-1 +# +# max number of bytes in a POST of a XML/JSON request +# +xacml.rest.pdp.maxcontent=32767 +# +# testClient file +# +xacml.rest.pep.idfile = testclient.properties diff --git a/ONAP-XACML/xacml.properties b/ONAP-XACML/xacml.properties new file mode 100644 index 000000000..69f5a4fd6 --- /dev/null +++ b/ONAP-XACML/xacml.properties @@ -0,0 +1,46 @@ +### +# ============LICENSE_START======================================================= +# ONAP-XACML +# ================================================================================ +# 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========================================================= +### + +# Default XACML Properties File +# Standard API Factories +# +xacml.dataTypeFactory=com.att.research.xacml.std.StdDataTypeFactory +xacml.pdpEngineFactory=com.att.research.xacmlatt.pdp.ATTPDPEngineFactory +xacml.pepEngineFactory=com.att.research.xacml.std.pep.StdEngineFactory +xacml.pipFinderFactory=com.att.research.xacml.std.pip.StdPIPFinderFactory + +# If there is a standard set of PIPEngines: +# xacml.pip.engines=engine1,engine2,...,engineN +# engine1.classname=com.att.research.xacmlpip.OraclePIP +# engine1.prop1=foo +# engine1.prop2=bar +# ... +# engine2.classname=com.att.research.xacmlpip.ActiveDirectoryPIP +# ... + +# AT&T PDP Implementation Factories +# +xacml.att.evaluationContextFactory=com.att.research.xacmlatt.pdp.std.StdEvaluationContextFactory +xacml.att.combiningAlgorithmFactory=com.att.research.xacmlatt.pdp.std.StdCombiningAlgorithmFactory +xacml.att.functionDefinitionFactory=com.att.research.xacmlatt.pdp.std.StdFunctionDefinitionFactory +xacml.att.policyFinderFactory=com.att.research.xacmlatt.pdp.std.StdPolicyFinderFactory + +# If there is a standard policy for the engine: +# xacml.att.stdPolicyFinderFactory.rootPolicyFile=/etc/stdpolicyset.xml diff --git a/POLICY-SDK-APP/pom.xml b/POLICY-SDK-APP/pom.xml index ae58bc182..b8ac94bd2 100644 --- a/POLICY-SDK-APP/pom.xml +++ b/POLICY-SDK-APP/pom.xml @@ -2,7 +2,7 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - org.openecomp.policy.engine + org.onap.policy.engine PolicyEngineSuite 1.1.0-SNAPSHOT @@ -171,8 +171,8 @@ - org.openecomp.policy.engine - ECOMP-PDP + org.onap.policy.engine + ONAP-PDP ${project.version} 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 - +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    - +
    diff --git a/PolicyEngineAPI/Test/PDP_settings/test_PolicyEngine.xml b/PolicyEngineAPI/Test/PDP_settings/test_PolicyEngine.xml index 343ec7c55..4eebf154f 100644 --- a/PolicyEngineAPI/Test/PDP_settings/test_PolicyEngine.xml +++ b/PolicyEngineAPI/Test/PDP_settings/test_PolicyEngine.xml @@ -28,14 +28,14 @@ CPU - + 95 Memory - + 95 @@ -47,14 +47,14 @@ CPU - + 90 Memory - + 90 @@ -81,11 +81,11 @@ - - + + Configuration - + http://localhost:5443/config/test_json.json @@ -116,11 +116,11 @@ - - + + Configuration - + http://localhost:5443/config/test_json.json @@ -147,11 +147,11 @@ - - + + Configuration - + http://localhost:5443/config/test_xml.xml @@ -182,11 +182,11 @@ - - + + Configuration - + http://localhost:5443/config/test_xml.xml @@ -213,11 +213,11 @@ - - + + Configuration - + http://localhost:5443/config/test_prop.properties @@ -248,11 +248,11 @@ - - + + Configuration - + http://localhost:5443/config/test_prop.properties @@ -279,11 +279,11 @@ - - + + Configuration - + http://localhost:5443/config/test_other.txt @@ -314,11 +314,11 @@ - - + + Configuration - + http://localhost:5443/config/test_other.txt @@ -361,11 +361,11 @@ - - + + Configuration - + http://localhost:5443/config/test_json.json @@ -408,11 +408,11 @@ - - + + Configuration - + http://localhost:5443/config/test_xml.xml @@ -455,11 +455,11 @@ - - + + Configuration - + http://localhost:5443/config/test_prop.properties @@ -502,11 +502,11 @@ - - + + Configuration - + http://localhost:5443/config/test_other.txt @@ -536,12 +536,12 @@ - - + + Restart - - + + @@ -566,8 +566,8 @@ - - + + SpinOff @@ -576,14 +576,14 @@ REST - - + + GET - http://localhost:8635/RESTjson/PDP/VM/$com.att.labs.ecomp.obligation.spinoff/$com.att.labs.ecomp.obligation.server + http://localhost:8635/RESTjson/PDP/VM/$com.att.labs.onap.obligation.spinoff/$com.att.labs.onap.obligation.server diff --git a/PolicyEngineAPI/Test/test_PolicyEngine.xml b/PolicyEngineAPI/Test/test_PolicyEngine.xml index d83c12a4c..1c1abf19e 100644 --- a/PolicyEngineAPI/Test/test_PolicyEngine.xml +++ b/PolicyEngineAPI/Test/test_PolicyEngine.xml @@ -28,14 +28,14 @@ CPU - + 95 Memory - + 95 @@ -47,14 +47,14 @@ CPU - + 90 Memory - + 90 @@ -81,11 +81,11 @@ - - + + Configuration - + http://10.01.10.01:5443/config/test_json.json @@ -116,11 +116,11 @@ - - + + Configuration - + http://10.01.10.01:5443/config/test_json.json @@ -147,11 +147,11 @@ - - + + Configuration - + http://10.01.10.01:5443/config/test_xml.xml @@ -182,11 +182,11 @@ - - + + Configuration - + http://10.01.10.01:5443/config/test_xml.xml @@ -213,11 +213,11 @@ - - + + Configuration - + http://10.01.10.01:5443/config/test_prop.properties @@ -248,11 +248,11 @@ - - + + Configuration - + http://10.01.10.01:5443/config/test_prop.properties @@ -279,11 +279,11 @@ - - + + Configuration - + http://10.01.10.01:5443/config/test_other.txt @@ -314,11 +314,11 @@ - - + + Configuration - + http://10.01.10.01:5443/config/test_other.txt @@ -361,11 +361,11 @@ - - + + Configuration - + http://10.01.10.01:5443/config/test_json.json @@ -408,11 +408,11 @@ - - + + Configuration - + http://10.01.10.01:5443/config/test_xml.xml @@ -455,11 +455,11 @@ - - + + Configuration - + http://10.01.10.01:5443/config/test_prop.properties @@ -502,11 +502,11 @@ - - + + Configuration - + http://10.01.10.01:5443/config/test_other.txt @@ -536,12 +536,12 @@ - - + + Restart - - + + @@ -566,8 +566,8 @@ - - + + SpinOff @@ -576,14 +576,14 @@ REST - - + + GET - http://localhost:8635/RESTjson/PDP/VM/$org.ecomp.obligation.spinoff/$org.ecomp.obligation.server + http://localhost:8635/RESTjson/PDP/VM/$org.onap.obligation.spinoff/$org.onap.obligation.server diff --git a/PolicyEngineAPI/pom.xml b/PolicyEngineAPI/pom.xml index 60e603bf4..e5af8d7d3 100644 --- a/PolicyEngineAPI/pom.xml +++ b/PolicyEngineAPI/pom.xml @@ -1,7 +1,7 @@ + ::= "MSO" | "DCAE" | "ASDC " | "AAI" |"Policy" | "SDNC" | "AC" --> diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientEndTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientEndTest.java new file mode 100644 index 000000000..203b9f54f --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientEndTest.java @@ -0,0 +1,228 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import static org.junit.Assert.assertNotNull; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.api.NotificationHandler; +import org.onap.policy.api.NotificationScheme; +import org.onap.policy.std.AutoClientEnd; +import org.onap.policy.std.StdPolicyEngine; + +/** + * The class AutoClientEndTest contains tests for the class {@link AutoClientEnd}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class AutoClientEndTest { + /** + * Run the AutoClientEnd() constructor test. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testAutoClientEnd_1() + throws Exception { + AutoClientEnd result = new AutoClientEnd(); + assertNotNull(result); + // add additional test code here + } + + /** + * Run the boolean getStatus() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetStatus_1() + throws Exception { + + boolean result = AutoClientEnd.getStatus(); + + assertNotNull(result); + } + + /** + * Run the String getURL() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetURL_1() + throws Exception { + + String result = AutoClientEnd.getURL(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientEnd + assertNotNull(result); + } + + + /** + * Run the void setAuto(NotificationScheme,NotificationHandler) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetAuto() + throws Exception { + NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; + NotificationHandler handler = null; + + AutoClientEnd.setAuto(scheme, handler); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.ExceptionInInitializerError + // at org.apache.log4j.Logger.getLogger(Logger.java:104) + // at org.onap.policy.std.AutoClientEnd.(AutoClientEnd.java:39) + } + + /** + * Run the void setScheme(NotificationScheme) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetScheme() + throws Exception { + + NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; + AutoClientEnd.setScheme(scheme); + + } + + /** + * Run the void start(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testStart() + throws Exception { + String url = "http://test.com"; + + AutoClientEnd.start(url); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientEnd + } + + + /** + * Run the void start(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testStart_2() + throws Exception { + String url = null; + + AutoClientEnd.start(url); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientEnd + } + + /** + * Run the void stop() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testStop_1() + throws Exception { + + AutoClientEnd.stop(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientEnd + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add set up code here + StdPolicyEngine policyEngine = new StdPolicyEngine("Test/config_pass.properties", (String) null); + + NotificationHandler handler = policyEngine.getNotificationHandler(); + AutoClientEnd.setAuto(NotificationScheme.AUTO_ALL_NOTIFICATIONS, handler); + AutoClientEnd.start("http://testurl.com"); + + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(AutoClientEndTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientUEBTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientUEBTest.java new file mode 100644 index 000000000..94c2ac781 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/AutoClientUEBTest.java @@ -0,0 +1,567 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import java.util.LinkedList; +import java.util.List; + +import org.junit.*; +import org.onap.policy.api.NotificationHandler; +import org.onap.policy.api.NotificationScheme; +import org.onap.policy.std.AutoClientUEB; + +import static org.junit.Assert.*; + +/** + * The class AutoClientUEBTest contains tests for the class {@link AutoClientUEB}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class AutoClientUEBTest { + /** + * Run the AutoClientUEB(String,List) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testAutoClientUEB_1() + throws Exception { + String url = ""; + String apiKey = ""; + String apiSecret = ""; + List uebURLList = new LinkedList(); + + AutoClientUEB result = new AutoClientUEB(url, uebURLList, apiKey, apiSecret); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.ExceptionInInitializerError + // at org.apache.log4j.Logger.getLogger(Logger.java:104) + // at org.onap.policy.std.AutoClientUEB.(AutoClientUEB.java:39) + assertNotNull(result); + } + + /** + * Run the String getNotficationType() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetNotficationType_1() + throws Exception { + + String result = AutoClientUEB.getNotficationType(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + assertNull(result); + } + + /** + * Run the boolean getStatus() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetStatus_1() + throws Exception { + + boolean result = AutoClientUEB.getStatus(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + assertFalse(result); + } + + /** + * Run the String getURL() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetURL_1() + throws Exception { + + String result = AutoClientUEB.getURL(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + assertNotNull(result); + } + + /** + * Run the boolean isRunning() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testIsRunning_1() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(), "", ""); + fixture.isRunning = true; + + boolean result = fixture.isRunning(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + assertTrue(result); + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_1() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(), "", ""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_2() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(), "", ""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_3() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(), "", ""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_4() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(), "", ""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_5() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_6() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_7() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_8() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_9() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_10() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_11() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_12() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_13() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_14() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_15() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void run() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRun_16() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); + fixture.isRunning = true; + + fixture.run(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void setAuto(NotificationScheme,NotificationHandler) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetAuto_1() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); + fixture.isRunning = true; + NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; + NotificationHandler handler = null; + + fixture.setAuto(scheme, handler); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void setScheme(NotificationScheme) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetScheme_1() + throws Exception { + NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; + + AutoClientUEB.setScheme(scheme); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Run the void terminate() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testTerminate_1() + throws Exception { + AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); + fixture.isRunning = true; + + fixture.terminate(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.AutoClientUEB + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add set up code here + List urlList = new LinkedList(); + urlList.add("test2.com"); + AutoClientUEB client = new AutoClientUEB("test.com", urlList, "testKey", "testSecret"); + NotificationHandler handler = null; + client.setAuto(NotificationScheme.AUTO_ALL_NOTIFICATIONS, handler); + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(AutoClientUEBTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/Handler.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/Handler.java new file mode 100644 index 000000000..388ca078d --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/Handler.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import java.util.Collection; + +import org.onap.policy.api.LoadedPolicy; +import org.onap.policy.api.NotificationHandler; +import org.onap.policy.api.NotificationType; +import org.onap.policy.api.PDPNotification; +import org.onap.policy.api.PolicyConfig; +import org.onap.policy.api.PolicyConfigException; +import org.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.api.RemovedPolicy; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +public class Handler implements NotificationHandler{ + + private static final Logger LOGGER = FlexLogger.getLogger(Handler.class); + + @Override + public void notificationReceived(PDPNotification notification) { + System.out.println("Notification Received..."); + System.out.println(notification.getNotificationType()); + if(notification.getNotificationType().equals(NotificationType.REMOVE)){ + System.out.println("Removed Policies: \n"); + for(RemovedPolicy removedPolicy: notification.getRemovedPolicies()){ + System.out.println(removedPolicy.getPolicyName()); + System.out.println(removedPolicy.getVersionNo()); + } + }else if(notification.getNotificationType().equals(NotificationType.UPDATE)){ + System.out.println("Updated Policies: \n"); + for(LoadedPolicy updatedPolicy: notification.getLoadedPolicies()){ + System.out.println("policyName : " + updatedPolicy.getPolicyName()); + System.out.println("policyVersion :" + updatedPolicy.getVersionNo()); + if(updatedPolicy.getPolicyName().contains(".Config_")){ + System.out.println("Matches: " + updatedPolicy.getMatches()); + System.out.println("UpdateType: "+ updatedPolicy.getUpdateType()); + // Checking the Name is correct or not. + try { + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + @SuppressWarnings("deprecation") + Collection policyConfigs = policyEngine.getConfigByPolicyName(updatedPolicy.getPolicyName()); + for(PolicyConfig policyConfig: policyConfigs){ + if(policyConfig.getPolicyConfigStatus().equals(PolicyConfigStatus.CONFIG_RETRIEVED)){ + System.out.println("Policy Retrieved with this Name notified. "); + }else{ + System.err.println("\n\n Fail to retrieve policy !!!!\n\n"); + } + // Also Test this case. + if(policyConfig.getPolicyName().equals(updatedPolicy.getPolicyName())){ + System.out.println("Policy Name is good. "); + }else{ + System.err.println("\n\n Fail to check Name \n\n"); + } + } + } catch (PolicyEngineException e) { + LOGGER.error("Exception Occured"+e); + } catch (PolicyConfigException e) { + LOGGER.error("Exception Occured"+e); + } + } + } + }else if(notification.getNotificationType().equals(NotificationType.BOTH)){ + System.out.println("Both updated and Removed Notification: \n"); + System.out.println("Removed Policies: \n"); + for(RemovedPolicy removedPolicy: notification.getRemovedPolicies()){ + System.out.println(removedPolicy.getPolicyName()); + System.out.println(removedPolicy.getVersionNo()); + } + System.out.println("Updated Policies: \n"); + for(LoadedPolicy updatedPolicy: notification.getLoadedPolicies()){ + System.out.println("policyName : " + updatedPolicy.getPolicyName()); + System.out.println("policyVersion :" + updatedPolicy.getVersionNo()); + System.out.println("Matches: " + updatedPolicy.getMatches()); + System.out.println("UpdateType: "+ updatedPolicy.getUpdateType()); + // Checking the Name is correct or not. + try { + PolicyEngine policyEngine = new PolicyEngine("config.properties"); + @SuppressWarnings("deprecation") + Collection policyConfigs = policyEngine.getConfigByPolicyName(updatedPolicy.getPolicyName()); + for(PolicyConfig policyConfig: policyConfigs){ + if(policyConfig.getPolicyConfigStatus().equals(PolicyConfigStatus.CONFIG_RETRIEVED)){ + System.out.println("Policy Retrieved with this Name notified. "); + }else{ + System.err.println("\n\n Fail to retrieve policy !!!!\n\n"); + } + // Also Test this case. + if(policyConfig.getPolicyName().equals(updatedPolicy.getPolicyName())){ + System.out.println("Policy Name is good. "); + }else{ + System.err.println("\n\n Fail to check Name \n\n"); + } + } + } catch (PolicyEngineException e) { + LOGGER.error("Exception Occured"+e); + } catch (PolicyConfigException e) { + LOGGER.error("Exception Occured"+e); + } + } + } + } + + +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndTest.java new file mode 100644 index 000000000..2ae522c1d --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndTest.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.api.NotificationScheme; +import org.onap.policy.api.PDPNotification; +import org.onap.policy.std.ManualClientEnd; + +/** + * The class ManualClientEndTest contains tests for the class {@link ManualClientEnd}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class ManualClientEndTest { + /** + * Run the ManualClientEnd() constructor test. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testManualClientEnd_1() + throws Exception { + ManualClientEnd result = new ManualClientEnd(); + assertNotNull(result); + // add additional test code here + } + + + /** + * Run the PDPNotification result(NotificationScheme) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testResult_1() + throws Exception { + NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; + + PDPNotification result = ManualClientEnd.result(scheme); + + assertNull(result); + } + + + /** + * Run the void start(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStart_1() + throws Exception { + String url = ""; + + ManualClientEnd.start(url); + + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(ManualClientEndTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndUEBTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndUEBTest.java new file mode 100644 index 000000000..77b0c6f49 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndUEBTest.java @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.LinkedList; +import java.util.List; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.api.NotificationScheme; +import org.onap.policy.api.PDPNotification; +import org.onap.policy.std.ManualClientEndUEB; +import org.onap.policy.std.StdPDPNotification; + +/** + * The class ManualClientEndUEBTest contains tests for the class {@link ManualClientEndUEB}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class ManualClientEndUEBTest { + + String resultJson = "{'test':'testing'}"; + String json = "{\"test\":\"testing\"}"; + StdPDPNotification notification = new StdPDPNotification(); + ManualClientEndUEB mockManualClient = null; + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + String url = "http://test.com"; + List uebURLList = new LinkedList(); + uebURLList.add(url); + + } + /** + * Run the ManualClientEndUEB() constructor test. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testManualClientEndUEB_1() + throws Exception { + ManualClientEndUEB result = new ManualClientEndUEB(); + assertNotNull(result); + // add additional test code here + } + + /** + * Run the PDPNotification result(NotificationScheme) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testResult_1() + throws Exception { + NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; + + PDPNotification result = ManualClientEndUEB.result(scheme); + + assertNull(result); + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(ManualClientEndUEBTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/MatchStoreTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/MatchStoreTest.java new file mode 100644 index 000000000..856474dd8 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/MatchStoreTest.java @@ -0,0 +1,776 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.HashSet; +import java.util.Hashtable; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.api.PDPNotification; +import org.onap.policy.std.MatchStore; +import org.onap.policy.std.Matches; +import org.onap.policy.std.StdPDPNotification; + +/** + * The class MatchStoreTest contains tests for the class {@link MatchStore}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class MatchStoreTest { + /** + * Run the MatchStore() constructor test. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testMatchStore_1() + throws Exception { + MatchStore result = new MatchStore(); + assertNotNull(result); + // add additional test code here + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_1() + throws Exception { + PDPNotification oldNotification = null; + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNull(result); + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_2() + throws Exception { + PDPNotification oldNotification = new StdPDPNotification(); + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNotNull(result); + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_3() + throws Exception { + PDPNotification oldNotification = new StdPDPNotification(); + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNotNull(result); + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_4() + throws Exception { + PDPNotification oldNotification = new StdPDPNotification(); + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNotNull(result); + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_5() + throws Exception { + PDPNotification oldNotification = new StdPDPNotification(); + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNotNull(result); + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_6() + throws Exception { + PDPNotification oldNotification = new StdPDPNotification(); + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNotNull(result); + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_7() + throws Exception { + PDPNotification oldNotification = new StdPDPNotification(); + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNotNull(result); + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_8() + throws Exception { + PDPNotification oldNotification = new StdPDPNotification(); + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNotNull(result); + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_9() + throws Exception { + PDPNotification oldNotification = new StdPDPNotification(); + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNotNull(result); + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_10() + throws Exception { + PDPNotification oldNotification = new StdPDPNotification(); + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNotNull(result); + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_11() + throws Exception { + PDPNotification oldNotification = new StdPDPNotification(); + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNotNull(result); + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_12() + throws Exception { + PDPNotification oldNotification = new StdPDPNotification(); + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNotNull(result); + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_13() + throws Exception { + PDPNotification oldNotification = new StdPDPNotification(); + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNotNull(result); + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_14() + throws Exception { + PDPNotification oldNotification = new StdPDPNotification(); + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNotNull(result); + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_15() + throws Exception { + PDPNotification oldNotification = new StdPDPNotification(); + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNotNull(result); + } + + /** + * Run the PDPNotification checkMatch(PDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testCheckMatch_16() + throws Exception { + PDPNotification oldNotification = new StdPDPNotification(); + + PDPNotification result = MatchStore.checkMatch(oldNotification); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + assertNotNull(result); + } + + /** + * Run the HashSet getMatchStore() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetMatchStore_1() + throws Exception { + + HashSet result = MatchStore.getMatchStore(); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.ExceptionInInitializerError + // at org.apache.log4j.Logger.getLogger(Logger.java:104) + // at org.onap.policy.std.MatchStore.(MatchStore.java:15) + assertNotNull(result); + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_1() + throws Exception { + Matches newMatch = new Matches(); + newMatch.setConfigName(""); + newMatch.setOnapName(""); + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_2() + throws Exception { + Matches newMatch = new Matches(); + newMatch.setConfigName(""); + newMatch.setOnapName(""); + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_3() + throws Exception { + Matches newMatch = new Matches(); + newMatch.setConfigName(""); + newMatch.setOnapName(""); + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_4() + throws Exception { + Matches newMatch = new Matches(); + newMatch.setConfigAttributes(new Hashtable()); + newMatch.setConfigName(""); + newMatch.setOnapName(""); + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_5() + throws Exception { + Matches newMatch = new Matches(); + newMatch.setConfigAttributes(new Hashtable()); + newMatch.setConfigName(""); + newMatch.setOnapName(""); + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_6() + throws Exception { + Matches newMatch = new Matches(); + newMatch.setConfigAttributes(new Hashtable()); + newMatch.setConfigName(""); + newMatch.setOnapName(""); + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_7() + throws Exception { + Matches newMatch = new Matches(); + newMatch.setConfigAttributes(new Hashtable()); + newMatch.setConfigName(""); + newMatch.setOnapName(""); + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_8() + throws Exception { + Matches newMatch = new Matches(); + newMatch.setConfigName(""); + newMatch.setOnapName(""); + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_9() + throws Exception { + Matches newMatch = new Matches(); + newMatch.setOnapName(""); + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_10() + throws Exception { + Matches newMatch = new Matches(); + newMatch.setConfigAttributes(new Hashtable()); + newMatch.setConfigName(""); + newMatch.setOnapName(""); + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_11() + throws Exception { + Matches newMatch = new Matches(); + newMatch.setConfigAttributes(new Hashtable()); + newMatch.setConfigName(""); + newMatch.setOnapName(""); + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_12() + throws Exception { + Matches newMatch = new Matches(); + newMatch.setConfigAttributes(new Hashtable()); + newMatch.setConfigName(""); + newMatch.setOnapName(""); + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_13() + throws Exception { + Matches newMatch = new Matches(); + newMatch.setConfigAttributes(new Hashtable()); + newMatch.setConfigName(""); + newMatch.setOnapName(""); + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_14() + throws Exception { + Matches newMatch = new Matches(); + newMatch.setConfigAttributes(new Hashtable()); + newMatch.setConfigName(""); + newMatch.setOnapName(""); + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_15() + throws Exception { + Matches newMatch = new Matches(); + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Run the void storeMatch(Matches) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStoreMatch_16() + throws Exception { + Matches newMatch = null; + + MatchStore.storeMatch(newMatch); + + // add additional test code here + // An unexpected exception was thrown in user code while executing this test: + // java.lang.NoClassDefFoundError: Could not initialize class org.onap.policy.std.MatchStore + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(MatchStoreTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/MatchesTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/MatchesTest.java new file mode 100644 index 000000000..f71d93cb8 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/MatchesTest.java @@ -0,0 +1,216 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import java.util.Hashtable; +import java.util.Map; + +import org.junit.*; +import org.onap.policy.std.Matches; + +import static org.junit.Assert.*; + +/** + * The class MatchesTest contains tests for the class {@link Matches}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class MatchesTest { + /** + * Run the Matches() constructor test. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testMatches_1() + throws Exception { + Matches result = new Matches(); + assertNotNull(result); + // add additional test code here + } + + /** + * Run the Map getConfigAttributes() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetConfigAttributes_1() + throws Exception { + Matches fixture = new Matches(); + fixture.setOnapName(""); + fixture.setConfigAttributes(new Hashtable()); + fixture.setConfigName(""); + + Map result = fixture.getConfigAttributes(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the String getConfigName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetConfigName_1() + throws Exception { + Matches fixture = new Matches(); + fixture.setOnapName(""); + fixture.setConfigAttributes(new Hashtable()); + fixture.setConfigName(""); + + String result = fixture.getConfigName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getOnapName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetOnapName_1() + throws Exception { + Matches fixture = new Matches(); + fixture.setOnapName(""); + fixture.setConfigAttributes(new Hashtable()); + fixture.setConfigName(""); + + String result = fixture.getOnapName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the void setConfigAttributes(Map) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetConfigAttributes_1() + throws Exception { + Matches fixture = new Matches(); + fixture.setOnapName(""); + fixture.setConfigAttributes(new Hashtable()); + fixture.setConfigName(""); + Map configAttributes = new Hashtable(); + + fixture.setConfigAttributes(configAttributes); + + // add additional test code here + } + + /** + * Run the void setConfigName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetConfigName_1() + throws Exception { + Matches fixture = new Matches(); + fixture.setOnapName(""); + fixture.setConfigAttributes(new Hashtable()); + fixture.setConfigName(""); + String configName = ""; + + fixture.setConfigName(configName); + + // add additional test code here + } + + /** + * Run the void setOnapName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetOnapName_1() + throws Exception { + Matches fixture = new Matches(); + fixture.setOnapName(""); + fixture.setConfigAttributes(new Hashtable()); + fixture.setConfigName(""); + String onapName = ""; + + fixture.setOnapName(onapName); + + // add additional test code here + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(MatchesTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/NotificationStoreTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/NotificationStoreTest.java new file mode 100644 index 000000000..ed7383e1a --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/NotificationStoreTest.java @@ -0,0 +1,359 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import org.junit.*; +import org.onap.policy.std.NotificationStore; +import org.onap.policy.std.StdPDPNotification; + +import static org.junit.Assert.*; + +/** + * The class NotificationStoreTest contains tests for the class {@link NotificationStore}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class NotificationStoreTest { + /** + * Run the NotificationStore() constructor test. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testNotificationStore_1() + throws Exception { + NotificationStore result = new NotificationStore(); + assertNotNull(result); + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_1() + throws Exception { + StdPDPNotification notification = new StdPDPNotification(); + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_2() + throws Exception { + StdPDPNotification notification = new StdPDPNotification(); + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_3() + throws Exception { + StdPDPNotification notification = new StdPDPNotification(); + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_4() + throws Exception { + StdPDPNotification notification = new StdPDPNotification(); + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_5() + throws Exception { + StdPDPNotification notification = new StdPDPNotification(); + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_6() + throws Exception { + StdPDPNotification notification = new StdPDPNotification(); + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_7() + throws Exception { + StdPDPNotification notification = new StdPDPNotification(); + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_8() + throws Exception { + StdPDPNotification notification = new StdPDPNotification(); + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_9() + throws Exception { + StdPDPNotification notification = new StdPDPNotification(); + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_10() + throws Exception { + StdPDPNotification notification = new StdPDPNotification(); + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_11() + throws Exception { + StdPDPNotification notification = new StdPDPNotification(); + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_12() + throws Exception { + StdPDPNotification notification = new StdPDPNotification(); + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_13() + throws Exception { + StdPDPNotification notification = new StdPDPNotification(); + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_14() + throws Exception { + StdPDPNotification notification = new StdPDPNotification(); + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_15() + throws Exception { + StdPDPNotification notification = new StdPDPNotification(); + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Run the void recordNotification(StdPDPNotification) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testRecordNotification_16() + throws Exception { + StdPDPNotification notification = null; + + NotificationStore.recordNotification(notification); + + // add additional test code here + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(NotificationStoreTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/NotificationUnMarshalTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/NotificationUnMarshalTest.java new file mode 100644 index 000000000..fb42f98aa --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/NotificationUnMarshalTest.java @@ -0,0 +1,256 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import static org.junit.Assert.assertNotNull; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.std.NotificationUnMarshal; +import org.onap.policy.std.StdPDPNotification; + +/** + * The class NotificationUnMarshalTest contains tests for the class {@link NotificationUnMarshal}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class NotificationUnMarshalTest { + /** + * Run the StdPDPNotification notificationJSON(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) + public void testNotificationJSON_1() + throws Exception { + String json = ""; + + StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); + + // add additional test code here + assertNotNull(result); + } + + /** + * Run the StdPDPNotification notificationJSON(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) + public void testNotificationJSON_2() + throws Exception { + String json = ""; + + StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); + + // add additional test code here + assertNotNull(result); + } + + /** + * Run the StdPDPNotification notificationJSON(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) + public void testNotificationJSON_3() + throws Exception { + String json = ""; + + StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); + + // add additional test code here + assertNotNull(result); + } + + /** + * Run the StdPDPNotification notificationJSON(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) + public void testNotificationJSON_4() + throws Exception { + String json = ""; + + StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); + + // add additional test code here + assertNotNull(result); + } + + /** + * Run the StdPDPNotification notificationJSON(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) + public void testNotificationJSON_5() + throws Exception { + String json = ""; + + StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); + + // add additional test code here + assertNotNull(result); + } + + /** + * Run the StdPDPNotification notificationJSON(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) + public void testNotificationJSON_6() + throws Exception { + String json = ""; + + StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); + + // add additional test code here + assertNotNull(result); + } + + /** + * Run the StdPDPNotification notificationJSON(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) + public void testNotificationJSON_7() + throws Exception { + String json = ""; + + StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); + + // add additional test code here + assertNotNull(result); + } + + /** + * Run the StdPDPNotification notificationJSON(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) + public void testNotificationJSON_8() + throws Exception { + String json = ""; + + StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); + + // add additional test code here + assertNotNull(result); + } + + /** + * Run the StdPDPNotification notificationJSON(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) + public void testNotificationJSON_9() + throws Exception { + String json = ""; + + StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); + + // add additional test code here + assertNotNull(result); + } + + /** + * Run the StdPDPNotification notificationJSON(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) + public void testNotificationJSON_10() + throws Exception { + String json = ""; + + StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); + + // add additional test code here + assertNotNull(result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(NotificationUnMarshalTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdLoadedPolicyTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdLoadedPolicyTest.java new file mode 100644 index 000000000..c45a5aca7 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdLoadedPolicyTest.java @@ -0,0 +1,314 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import java.util.Hashtable; +import java.util.Map; + +import org.junit.*; +import org.onap.policy.api.UpdateType; +import org.onap.policy.std.StdLoadedPolicy; + +import static org.junit.Assert.*; + +/** + * The class StdLoadedPolicyTest contains tests for the class {@link StdLoadedPolicy}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class StdLoadedPolicyTest { + /** + * Run the StdLoadedPolicy() constructor test. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testStdLoadedPolicy_1() + throws Exception { + StdLoadedPolicy result = new StdLoadedPolicy(); + assertNotNull(result); + // add additional test code here + } + + /** + * Run the Map getMatches() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetMatches_1() + throws Exception { + StdLoadedPolicy fixture = new StdLoadedPolicy(); + fixture.setPolicyName(""); + fixture.setVersionNo(""); + fixture.setUpdateType(UpdateType.NEW); + fixture.setMatches(new Hashtable()); + + Map result = fixture.getMatches(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyName_1() + throws Exception { + StdLoadedPolicy fixture = new StdLoadedPolicy(); + fixture.setPolicyName(""); + fixture.setVersionNo(""); + fixture.setUpdateType(UpdateType.NEW); + fixture.setMatches(new Hashtable()); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyName_2() + throws Exception { + StdLoadedPolicy fixture = new StdLoadedPolicy(); + fixture.setPolicyName((String) null); + fixture.setVersionNo(""); + fixture.setUpdateType(UpdateType.NEW); + fixture.setMatches(new Hashtable()); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals(null, result); + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyName_3() + throws Exception { + StdLoadedPolicy fixture = new StdLoadedPolicy(); + fixture.setPolicyName(""); + fixture.setVersionNo(""); + fixture.setUpdateType(UpdateType.NEW); + fixture.setMatches(new Hashtable()); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the UpdateType getUpdateType() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetUpdateType_1() + throws Exception { + StdLoadedPolicy fixture = new StdLoadedPolicy(); + fixture.setPolicyName(""); + fixture.setVersionNo(""); + fixture.setUpdateType(UpdateType.NEW); + fixture.setMatches(new Hashtable()); + + UpdateType result = fixture.getUpdateType(); + + // add additional test code here + assertNotNull(result); + assertEquals("new", result.toString()); + assertEquals("NEW", result.name()); + assertEquals(1, result.ordinal()); + } + + /** + * Run the String getVersionNo() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetVersionNo_1() + throws Exception { + StdLoadedPolicy fixture = new StdLoadedPolicy(); + fixture.setPolicyName(""); + fixture.setVersionNo(""); + fixture.setUpdateType(UpdateType.NEW); + fixture.setMatches(new Hashtable()); + + String result = fixture.getVersionNo(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the void setMatches(Map) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetMatches_1() + throws Exception { + StdLoadedPolicy fixture = new StdLoadedPolicy(); + fixture.setPolicyName(""); + fixture.setVersionNo(""); + fixture.setUpdateType(UpdateType.NEW); + fixture.setMatches(new Hashtable()); + Map matches = new Hashtable(); + + fixture.setMatches(matches); + + // add additional test code here + } + + /** + * Run the void setPolicyName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyName_1() + throws Exception { + StdLoadedPolicy fixture = new StdLoadedPolicy(); + fixture.setPolicyName(""); + fixture.setVersionNo(""); + fixture.setUpdateType(UpdateType.NEW); + fixture.setMatches(new Hashtable()); + String policyName = ""; + + fixture.setPolicyName(policyName); + + // add additional test code here + } + + /** + * Run the void setUpdateType(UpdateType) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetUpdateType_1() + throws Exception { + StdLoadedPolicy fixture = new StdLoadedPolicy(); + fixture.setPolicyName(""); + fixture.setVersionNo(""); + fixture.setUpdateType(UpdateType.NEW); + fixture.setMatches(new Hashtable()); + UpdateType updateType = UpdateType.NEW; + + fixture.setUpdateType(updateType); + + // add additional test code here + } + + /** + * Run the void setVersionNo(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetVersionNo_1() + throws Exception { + StdLoadedPolicy fixture = new StdLoadedPolicy(); + fixture.setPolicyName(""); + fixture.setVersionNo(""); + fixture.setUpdateType(UpdateType.NEW); + fixture.setMatches(new Hashtable()); + String versionNo = ""; + + fixture.setVersionNo(versionNo); + + // add additional test code here + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(StdLoadedPolicyTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPDPNotificationTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPDPNotificationTest.java new file mode 100644 index 000000000..6a558006d --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPDPNotificationTest.java @@ -0,0 +1,311 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import java.util.Collection; +import java.util.LinkedList; + +import org.junit.*; +import org.onap.policy.api.LoadedPolicy; +import org.onap.policy.api.NotificationType; +import org.onap.policy.api.RemovedPolicy; +import org.onap.policy.std.StdLoadedPolicy; +import org.onap.policy.std.StdPDPNotification; +import org.onap.policy.std.StdRemovedPolicy; + +import static org.junit.Assert.*; + +/** + * The class StdPDPNotificationTest contains tests for the class {@link StdPDPNotification}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class StdPDPNotificationTest { + /** + * Run the StdPDPNotification() constructor test. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testStdPDPNotification_1() + throws Exception { + StdPDPNotification result = new StdPDPNotification(); + assertNotNull(result); + // add additional test code here + } + + /** + * Run the Collection getLoadedPolicies() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetLoadedPolicies_1() + throws Exception { + StdPDPNotification fixture = new StdPDPNotification(); + fixture.setRemovedPolicies(new LinkedList()); + fixture.setNotificationType(NotificationType.BOTH); + fixture.setLoadedPolicies(new LinkedList()); + + Collection result = fixture.getLoadedPolicies(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the Collection getLoadedPolicies() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetLoadedPolicies_2() + throws Exception { + StdPDPNotification fixture = new StdPDPNotification(); + fixture.setRemovedPolicies(new LinkedList()); + fixture.setNotificationType(NotificationType.BOTH); + fixture.setLoadedPolicies(new LinkedList()); + + Collection result = fixture.getLoadedPolicies(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the Collection getLoadedPolicies() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetLoadedPolicies_3() + throws Exception { + StdPDPNotification fixture = new StdPDPNotification(); + fixture.setRemovedPolicies(new LinkedList()); + fixture.setNotificationType(NotificationType.BOTH); + fixture.setLoadedPolicies(null); + + Collection result = fixture.getLoadedPolicies(); + + // add additional test code here + assertEquals(null, result); + } + + /** + * Run the NotificationType getNotificationType() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetNotificationType_1() + throws Exception { + StdPDPNotification fixture = new StdPDPNotification(); + fixture.setRemovedPolicies(new LinkedList()); + fixture.setNotificationType(NotificationType.BOTH); + fixture.setLoadedPolicies(new LinkedList()); + + NotificationType result = fixture.getNotificationType(); + + // add additional test code here + assertNotNull(result); + assertEquals("both", result.toString()); + assertEquals("BOTH", result.name()); + assertEquals(2, result.ordinal()); + } + + /** + * Run the Collection getRemovedPolicies() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetRemovedPolicies_1() + throws Exception { + StdPDPNotification fixture = new StdPDPNotification(); + fixture.setRemovedPolicies(new LinkedList()); + fixture.setNotificationType(NotificationType.BOTH); + fixture.setLoadedPolicies(new LinkedList()); + + Collection result = fixture.getRemovedPolicies(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the Collection getRemovedPolicies() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetRemovedPolicies_2() + throws Exception { + StdPDPNotification fixture = new StdPDPNotification(); + fixture.setRemovedPolicies(new LinkedList()); + fixture.setNotificationType(NotificationType.BOTH); + fixture.setLoadedPolicies(new LinkedList()); + + Collection result = fixture.getRemovedPolicies(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the Collection getRemovedPolicies() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetRemovedPolicies_3() + throws Exception { + StdPDPNotification fixture = new StdPDPNotification(); + fixture.setRemovedPolicies(null); + fixture.setNotificationType(NotificationType.BOTH); + fixture.setLoadedPolicies(new LinkedList()); + + Collection result = fixture.getRemovedPolicies(); + + // add additional test code here + assertEquals(null, result); + } + + /** + * Run the void setNotificationType(NotificationType) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetNotificationType_1() + throws Exception { + StdPDPNotification fixture = new StdPDPNotification(); + fixture.setRemovedPolicies(new LinkedList()); + fixture.setNotificationType(NotificationType.BOTH); + fixture.setLoadedPolicies(new LinkedList()); + NotificationType notificationType = NotificationType.BOTH; + + fixture.setNotificationType(notificationType); + + // add additional test code here + } + + /** + * Run the void setRemovedPolicies(Collection) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetRemovedPolicies_1() + throws Exception { + StdPDPNotification fixture = new StdPDPNotification(); + fixture.setRemovedPolicies(new LinkedList()); + fixture.setNotificationType(NotificationType.BOTH); + fixture.setLoadedPolicies(new LinkedList()); + Collection removedPolicies = new LinkedList(); + + fixture.setRemovedPolicies(removedPolicies); + + // add additional test code here + } + + /** + * Run the void setUpdatedPolicies(Collection) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetUpdatedPolicies_1() + throws Exception { + StdPDPNotification fixture = new StdPDPNotification(); + fixture.setRemovedPolicies(new LinkedList()); + fixture.setNotificationType(NotificationType.BOTH); + fixture.setLoadedPolicies(new LinkedList()); + Collection updatedPolicies = new LinkedList(); + + fixture.setLoadedPolicies(updatedPolicies); + + // add additional test code here + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(StdPDPNotificationTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPolicyChangeResponseTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPolicyChangeResponseTest.java new file mode 100644 index 000000000..5ce53d133 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPolicyChangeResponseTest.java @@ -0,0 +1,166 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import org.junit.*; +import org.onap.policy.std.StdPolicyChangeResponse; + +import static org.junit.Assert.*; + +/** + * The class StdPolicyChangeResponseTest contains tests for the class {@link StdPolicyChangeResponse}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class StdPolicyChangeResponseTest { + /** + * Run the StdPolicyChangeResponse() constructor test. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testStdPolicyChangeResponse_1() + throws Exception { + StdPolicyChangeResponse result = new StdPolicyChangeResponse(); + assertNotNull(result); + // add additional test code here + } + + /** + * Run the int getResponseCode() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetResponseCode_1() + throws Exception { + StdPolicyChangeResponse fixture = new StdPolicyChangeResponse(); + fixture.setResponseMessage(""); + fixture.setResponseCode(1); + + int result = fixture.getResponseCode(); + + // add additional test code here + assertEquals(1, result); + } + + /** + * Run the String getResponseMessage() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetResponseMessage_1() + throws Exception { + StdPolicyChangeResponse fixture = new StdPolicyChangeResponse(); + fixture.setResponseMessage(""); + fixture.setResponseCode(1); + + String result = fixture.getResponseMessage(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the void setResponseCode(int) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetResponseCode_1() + throws Exception { + StdPolicyChangeResponse fixture = new StdPolicyChangeResponse(); + fixture.setResponseMessage(""); + fixture.setResponseCode(1); + int responseCode = 1; + + fixture.setResponseCode(responseCode); + + // add additional test code here + } + + /** + * Run the void setResponseMessage(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetResponseMessage_1() + throws Exception { + StdPolicyChangeResponse fixture = new StdPolicyChangeResponse(); + fixture.setResponseMessage(""); + fixture.setResponseCode(1); + String responseMessage = ""; + + fixture.setResponseMessage(responseMessage); + + // add additional test code here + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(StdPolicyChangeResponseTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPolicyConfigTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPolicyConfigTest.java new file mode 100644 index 000000000..736f51b57 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPolicyConfigTest.java @@ -0,0 +1,821 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import java.util.Hashtable; +import java.util.Map; +import java.util.Properties; + +import javax.json.JsonObject; + +import org.junit.*; +import org.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.api.PolicyType; +import org.onap.policy.std.StdPolicyConfig; + +import static org.junit.Assert.*; + +import org.w3c.dom.Document; + +/** + * The class StdPolicyConfigTest contains tests for the class {@link StdPolicyConfig}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class StdPolicyConfigTest { + /** + * Run the Map getMatchingConditions() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetMatchingConditions_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + + Map result = fixture.getMatchingConditions(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the String getPolicyConfigMessage() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetPolicyConfigMessage_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + + String result = fixture.getPolicyConfigMessage(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the PolicyConfigStatus getPolicyConfigStatus() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetPolicyConfigStatus_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + + PolicyConfigStatus result = fixture.getPolicyConfigStatus(); + + // add additional test code here + assertNotNull(result); + assertEquals("not_found", result.toString()); + assertEquals("CONFIG_NOT_FOUND", result.name()); + assertEquals(1, result.ordinal()); + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetPolicyName_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetPolicyName_2() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName((String) null); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals(null, result); + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetPolicyName_3() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getPolicyVersion() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetPolicyVersion_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + + String result = fixture.getPolicyVersion(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the Map getResponseAttributes() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetResponseAttributes_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + + Map result = fixture.getResponseAttributes(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the PolicyType getType() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetType_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + + PolicyType result = fixture.getType(); + + // add additional test code here + assertNotNull(result); + assertEquals("json", result.toString()); + assertEquals("JSON", result.name()); + assertEquals(1, result.ordinal()); + } + + /** + * Run the void setConfigStatus(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetConfigStatus_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + String configStatus = ""; + + fixture.setConfigStatus(configStatus); + + // add additional test code here + } + + /** + * Run the void setConfigStatus(String,PolicyConfigStatus) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetConfigStatus_2() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + String configStatus = ""; + PolicyConfigStatus policyConfigStatus = PolicyConfigStatus.CONFIG_NOT_FOUND; + + fixture.setConfigStatus(configStatus, policyConfigStatus); + + // add additional test code here + } + + /** + * Run the void setDocument(Document) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetDocument_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + Document document = null; + + fixture.setDocument(document); + + // add additional test code here + } + + /** + * Run the void setJsonObject(JsonObject) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetJsonObject_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + JsonObject jsonObject = null; + + fixture.setJsonObject(jsonObject); + + // add additional test code here + } + + /** + * Run the void setMatchingConditions(Map) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetMatchingConditions_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + Map matchingConditions = new Hashtable(); + + fixture.setMatchingConditions(matchingConditions); + + // add additional test code here + } + + /** + * Run the void setOther(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetOther_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + String other = ""; + + fixture.setOther(other); + + // add additional test code here + } + + /** + * Run the void setPolicyConfigStatus(PolicyConfigStatus) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetPolicyConfigStatus_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + PolicyConfigStatus policyConfigStatus = PolicyConfigStatus.CONFIG_NOT_FOUND; + + fixture.setPolicyConfigStatus(policyConfigStatus); + + // add additional test code here + } + + /** + * Run the void setPolicyName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetPolicyName_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + String policyName = ""; + + fixture.setPolicyName(policyName); + + // add additional test code here + } + + /** + * Run the void setPolicyType(PolicyType) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetPolicyType_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + PolicyType policyType = PolicyType.JSON; + + fixture.setPolicyType(policyType); + + // add additional test code here + } + + /** + * Run the void setPolicyVersion(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetPolicyVersion_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + String policyVersion = ""; + + fixture.setPolicyVersion(policyVersion); + + // add additional test code here + } + + /** + * Run the void setProperties(Properties) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetProperties_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + Properties properties = new Properties(); + + fixture.setProperties(properties); + + // add additional test code here + } + + /** + * Run the void setResponseAttributes(Map) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetResponseAttributes_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + Map responseAttributes = new Hashtable(); + + fixture.setResponseAttributes(responseAttributes); + + // add additional test code here + } + + /** + * Run the JsonObject toJSON() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testToJSON_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + + JsonObject result = fixture.toJSON(); + + // add additional test code here + assertEquals(null, result); + } + + /** + * Run the String toOther() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testToOther_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + + String result = fixture.toOther(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the Properties toProperties() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testToProperties_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + + Properties result = fixture.toProperties(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the String toString() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testToString_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName("test"); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + + String result = fixture.toString(); + + // add additional test code here + assertEquals("PolicyConfig [ policyConfigStatus=not_found, policyConfigMessage=, policyName=test]", result); + } + + /** + * Run the Document toXML() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testToXML_1() + throws Exception { + StdPolicyConfig fixture = new StdPolicyConfig(); + fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setDocument((Document) null); + fixture.setResponseAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setOther(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setPolicyName(""); + fixture.setProperties(new Properties()); + fixture.setJsonObject((JsonObject) null); + fixture.setMatchingConditions(new Hashtable()); + + Document result = fixture.toXML(); + + // add additional test code here + assertEquals(null, result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(StdPolicyConfigTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPolicyResponseTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPolicyResponseTest.java new file mode 100644 index 000000000..11179aece --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdPolicyResponseTest.java @@ -0,0 +1,348 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import java.util.Hashtable; +import java.util.Map; + +import org.junit.*; +import org.onap.policy.api.PolicyResponseStatus; +import org.onap.policy.std.StdPolicyResponse; + +import static org.junit.Assert.*; + +/** + * The class StdPolicyResponseTest contains tests for the class {@link StdPolicyResponse}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class StdPolicyResponseTest { + /** + * Run the Map getActionAdvised() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetActionAdvised_1() + throws Exception { + StdPolicyResponse fixture = new StdPolicyResponse(); + fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); + fixture.setRequestAttributes(new Hashtable()); + fixture.setActionAdvised(new Hashtable()); + fixture.setActionTaken(new Hashtable()); + + Map result = fixture.getActionAdvised(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the Map getActionTaken() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetActionTaken_1() + throws Exception { + StdPolicyResponse fixture = new StdPolicyResponse(); + fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); + fixture.setRequestAttributes(new Hashtable()); + fixture.setActionAdvised(new Hashtable()); + fixture.setActionTaken(new Hashtable()); + + Map result = fixture.getActionTaken(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the String getPolicyResponseMessage() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyResponseMessage_1() + throws Exception { + StdPolicyResponse fixture = new StdPolicyResponse(); + fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); + fixture.setRequestAttributes(new Hashtable()); + fixture.setActionAdvised(new Hashtable()); + fixture.setActionTaken(new Hashtable()); + + String result = fixture.getPolicyResponseMessage(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the PolicyResponseStatus getPolicyResponseStatus() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyResponseStatus_1() + throws Exception { + StdPolicyResponse fixture = new StdPolicyResponse(); + fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); + fixture.setRequestAttributes(new Hashtable()); + fixture.setActionAdvised(new Hashtable()); + fixture.setActionTaken(new Hashtable()); + + PolicyResponseStatus result = fixture.getPolicyResponseStatus(); + + // add additional test code here + assertNotNull(result); + assertEquals("action_advised", result.toString()); + assertEquals("ACTION_ADVISED", result.name()); + assertEquals(1, result.ordinal()); + } + + /** + * Run the Map getRequestAttributes() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetRequestAttributes_1() + throws Exception { + StdPolicyResponse fixture = new StdPolicyResponse(); + fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); + fixture.setRequestAttributes(new Hashtable()); + fixture.setActionAdvised(new Hashtable()); + fixture.setActionTaken(new Hashtable()); + + Map result = fixture.getRequestAttributes(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the void setActionAdvised(Map) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetActionAdvised_1() + throws Exception { + StdPolicyResponse fixture = new StdPolicyResponse(); + fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); + fixture.setRequestAttributes(new Hashtable()); + fixture.setActionAdvised(new Hashtable()); + fixture.setActionTaken(new Hashtable()); + Map actionAdvised = new Hashtable(); + + fixture.setActionAdvised(actionAdvised); + + // add additional test code here + } + + /** + * Run the void setActionTaken(Map) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetActionTaken_1() + throws Exception { + StdPolicyResponse fixture = new StdPolicyResponse(); + fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); + fixture.setRequestAttributes(new Hashtable()); + fixture.setActionAdvised(new Hashtable()); + fixture.setActionTaken(new Hashtable()); + Map actionTaken = new Hashtable(); + + fixture.setActionTaken(actionTaken); + + // add additional test code here + } + + /** + * Run the void setPolicyResponseMessage(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyResponseMessage_1() + throws Exception { + StdPolicyResponse fixture = new StdPolicyResponse(); + fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); + fixture.setRequestAttributes(new Hashtable()); + fixture.setActionAdvised(new Hashtable()); + fixture.setActionTaken(new Hashtable()); + String policyResponseMessage = ""; + + fixture.setPolicyResponseMessage(policyResponseMessage); + + // add additional test code here + } + + /** + * Run the void setPolicyResponseStatus(PolicyResponseStatus) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyResponseStatus_1() + throws Exception { + StdPolicyResponse fixture = new StdPolicyResponse(); + fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); + fixture.setRequestAttributes(new Hashtable()); + fixture.setActionAdvised(new Hashtable()); + fixture.setActionTaken(new Hashtable()); + PolicyResponseStatus policyResponseStatus = PolicyResponseStatus.ACTION_ADVISED; + + fixture.setPolicyResponseStatus(policyResponseStatus); + + // add additional test code here + } + + /** + * Run the void setPolicyResponseStatus(String,PolicyResponseStatus) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyResponseStatus_2() + throws Exception { + StdPolicyResponse fixture = new StdPolicyResponse(); + fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); + fixture.setRequestAttributes(new Hashtable()); + fixture.setActionAdvised(new Hashtable()); + fixture.setActionTaken(new Hashtable()); + String policyResponseMessage = ""; + PolicyResponseStatus policyResponseStatus = PolicyResponseStatus.ACTION_ADVISED; + + fixture.setPolicyResponseStatus(policyResponseMessage, policyResponseStatus); + + // add additional test code here + } + + /** + * Run the void setRequestAttributes(Map) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetRequestAttributes_1() + throws Exception { + StdPolicyResponse fixture = new StdPolicyResponse(); + fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); + fixture.setRequestAttributes(new Hashtable()); + fixture.setActionAdvised(new Hashtable()); + fixture.setActionTaken(new Hashtable()); + Map requestAttributes = new Hashtable(); + + fixture.setRequestAttributes(requestAttributes); + + // add additional test code here + } + + /** + * Run the String toString() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testToString_1() + throws Exception { + StdPolicyResponse fixture = new StdPolicyResponse(); + fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); + fixture.setRequestAttributes(new Hashtable()); + fixture.setActionAdvised(new Hashtable()); + fixture.setActionTaken(new Hashtable()); + + String result = fixture.toString(); + + // add additional test code here + assertEquals("PolicyResponse [ policyResponseStatus=action_advised, policyResponseMessage=, ]", result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(StdPolicyResponseTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdRemovedPolicyTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdRemovedPolicyTest.java new file mode 100644 index 000000000..2482c3015 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdRemovedPolicyTest.java @@ -0,0 +1,206 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import org.junit.*; +import org.onap.policy.std.StdRemovedPolicy; + +import static org.junit.Assert.*; + +/** + * The class StdRemovedPolicyTest contains tests for the class {@link StdRemovedPolicy}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class StdRemovedPolicyTest { + /** + * Run the StdRemovedPolicy() constructor test. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testStdRemovedPolicy_1() + throws Exception { + StdRemovedPolicy result = new StdRemovedPolicy(); + assertNotNull(result); + // add additional test code here + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyName_1() + throws Exception { + StdRemovedPolicy fixture = new StdRemovedPolicy(); + fixture.setVersionNo(""); + fixture.setPolicyName(""); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyName_2() + throws Exception { + StdRemovedPolicy fixture = new StdRemovedPolicy(); + fixture.setVersionNo(""); + fixture.setPolicyName((String) null); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals(null, result); + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyName_3() + throws Exception { + StdRemovedPolicy fixture = new StdRemovedPolicy(); + fixture.setVersionNo(""); + fixture.setPolicyName(""); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getVersionNo() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetVersionNo_1() + throws Exception { + StdRemovedPolicy fixture = new StdRemovedPolicy(); + fixture.setVersionNo(""); + fixture.setPolicyName(""); + + String result = fixture.getVersionNo(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the void setPolicyName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyName_1() + throws Exception { + StdRemovedPolicy fixture = new StdRemovedPolicy(); + fixture.setVersionNo(""); + fixture.setPolicyName(""); + String policyName = ""; + + fixture.setPolicyName(policyName); + + // add additional test code here + } + + /** + * Run the void setVersionNo(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetVersionNo_1() + throws Exception { + StdRemovedPolicy fixture = new StdRemovedPolicy(); + fixture.setVersionNo(""); + fixture.setPolicyName(""); + String versionNo = ""; + + fixture.setVersionNo(versionNo); + + // add additional test code here + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(StdRemovedPolicyTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdStatusTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdStatusTest.java new file mode 100644 index 000000000..b72d2568d --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/StdStatusTest.java @@ -0,0 +1,1433 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; + +import java.util.Hashtable; +import java.util.Map; +import java.util.Properties; + +import javax.json.JsonObject; + +import org.junit.*; +import org.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.api.PolicyDecision; +import org.onap.policy.api.PolicyResponseStatus; +import org.onap.policy.api.PolicyType; +import org.onap.policy.std.StdStatus; + +import static org.junit.Assert.*; + +import org.w3c.dom.Document; + +/** + * The class StdStatusTest contains tests for the class {@link StdStatus}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class StdStatusTest { + /** + * Run the Map getActionAdvised() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetActionAdvised_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + Map result = fixture.getActionAdvised(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the Map getActionTaken() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetActionTaken_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + Map result = fixture.getActionTaken(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the Map getMatchingConditions() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetMatchingConditions_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + Map result = fixture.getMatchingConditions(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the String getPolicyConfigMessage() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyConfigMessage_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + String result = fixture.getPolicyConfigMessage(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the PolicyConfigStatus getPolicyConfigStatus() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyConfigStatus_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + PolicyConfigStatus result = fixture.getPolicyConfigStatus(); + + // add additional test code here + assertNotNull(result); + assertEquals("not_found", result.toString()); + assertEquals("CONFIG_NOT_FOUND", result.name()); + assertEquals(1, result.ordinal()); + } + + /** + * Run the PolicyDecision getPolicyDecision() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyDecision_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + PolicyDecision result = fixture.getDecision(); + + // add additional test code here + assertNotNull(result); + assertEquals("deny", result.toString()); + assertEquals("DENY", result.name()); + assertEquals(1, result.ordinal()); + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyName_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyName_2() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName((String) null); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals(null, result); + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyName_3() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getPolicyResponseMessage() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyResponseMessage_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + String result = fixture.getPolicyResponseMessage(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the PolicyResponseStatus getPolicyResponseStatus() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyResponseStatus_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + PolicyResponseStatus result = fixture.getPolicyResponseStatus(); + + // add additional test code here + assertNotNull(result); + assertEquals("action_advised", result.toString()); + assertEquals("ACTION_ADVISED", result.name()); + assertEquals(1, result.ordinal()); + } + + /** + * Run the String getPolicyVersion() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyVersion_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + String result = fixture.getPolicyVersion(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the Map getRequestAttributes() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetRequestAttributes_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + Map result = fixture.getRequestAttributes(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the Map getResponseAttributes() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetResponseAttributes_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + Map result = fixture.getResponseAttributes(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the PolicyType getType() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetType_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + PolicyType result = fixture.getType(); + + // add additional test code here + assertNotNull(result); + assertEquals("json", result.toString()); + assertEquals("JSON", result.name()); + assertEquals(1, result.ordinal()); + } + + /** + * Run the void setActionAdvised(Map) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetActionAdvised_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + Map actionAdvised = new Hashtable(); + + fixture.setActionAdvised(actionAdvised); + + // add additional test code here + } + + /** + * Run the void setActionTaken(Map) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetActionTaken_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + Map actionTaken = new Hashtable(); + + fixture.setActionTaken(actionTaken); + + // add additional test code here + } + + /** + * Run the void setConfigStatus(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetConfigStatus_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + String configStatus = ""; + + fixture.setConfigStatus(configStatus); + + // add additional test code here + } + + /** + * Run the void setDocument(Document) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetDocument_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + Document document = null; + + fixture.setDocument(document); + + // add additional test code here + } + + /** + * Run the void setJsonObject(JsonObject) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetJsonObject_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + JsonObject jsonObject = null; + + fixture.setJsonObject(jsonObject); + + // add additional test code here + } + + /** + * Run the void setMatchingConditions(Map) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetMatchingConditions_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + Map matchingConditions = new Hashtable(); + + fixture.setMatchingConditions(matchingConditions); + + // add additional test code here + } + + /** + * Run the void setOther(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetOther_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + String other = ""; + + fixture.setOther(other); + + // add additional test code here + } + + /** + * Run the void setPolicyConfigStatus(PolicyConfigStatus) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyConfigStatus_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + PolicyConfigStatus policyConfigStatus = PolicyConfigStatus.CONFIG_NOT_FOUND; + + fixture.setPolicyConfigStatus(policyConfigStatus); + + // add additional test code here + } + + /** + * Run the void setPolicyConfigStatus(String,PolicyConfigStatus) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyConfigStatus_2() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + String configStatus = ""; + PolicyConfigStatus policyConfigStatus = PolicyConfigStatus.CONFIG_NOT_FOUND; + + fixture.setPolicyConfigStatus(configStatus, policyConfigStatus); + + // add additional test code here + } + + /** + * Run the void setPolicyDecision(PolicyDecision) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyDecision_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + PolicyDecision policyDecision = PolicyDecision.DENY; + + fixture.setDecision(policyDecision); + + // add additional test code here + } + + /** + * Run the void setPolicyName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyName_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + String policyName = ""; + + fixture.setPolicyName(policyName); + + // add additional test code here + } + + /** + * Run the void setPolicyResponseMessage(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyResponseMessage_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + String policyResponseMessage = ""; + + fixture.setPolicyResponseMessage(policyResponseMessage); + + // add additional test code here + } + + /** + * Run the void setPolicyResponseStatus(PolicyResponseStatus) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyResponseStatus_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + PolicyResponseStatus policyResponseStatus = PolicyResponseStatus.ACTION_ADVISED; + + fixture.setPolicyResponseStatus(policyResponseStatus); + + // add additional test code here + } + + /** + * Run the void setPolicyResponseStatus(String,PolicyResponseStatus) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyResponseStatus_2() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + String policyResponseMessage = ""; + PolicyResponseStatus policyResponseStatus = PolicyResponseStatus.ACTION_ADVISED; + + fixture.setPolicyResponseStatus(policyResponseMessage, policyResponseStatus); + + // add additional test code here + } + + /** + * Run the void setPolicyType(PolicyType) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyType_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + PolicyType policyType = PolicyType.JSON; + + fixture.setPolicyType(policyType); + + // add additional test code here + } + + /** + * Run the void setPolicyVersion(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyVersion_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + String policyVersion = ""; + + fixture.setPolicyVersion(policyVersion); + + // add additional test code here + } + + /** + * Run the void setProperties(Properties) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetProperties_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + Properties properties = new Properties(); + + fixture.setProperties(properties); + + // add additional test code here + } + + /** + * Run the void setRequestAttributes(Map) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetRequestAttributes_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + Map requestAttributes = new Hashtable(); + + fixture.setRequestAttributes(requestAttributes); + + // add additional test code here + } + + /** + * Run the void setResposneAttributes(Map) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetResposneAttributes_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + Map responseAttributes = new Hashtable(); + + fixture.setResposneAttributes(responseAttributes); + + // add additional test code here + } + + /** + * Run the void setStatus(String,PolicyResponseStatus,PolicyConfigStatus) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetStatus_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + String message = ""; + PolicyResponseStatus policyResponseStatus = PolicyResponseStatus.ACTION_ADVISED; + PolicyConfigStatus policyConfigStatus = PolicyConfigStatus.CONFIG_NOT_FOUND; + + fixture.setStatus(message, policyResponseStatus, policyConfigStatus); + + // add additional test code here + } + + /** + * Run the JsonObject toJSON() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testToJSON_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + JsonObject result = fixture.toJSON(); + + // add additional test code here + assertEquals(null, result); + } + + /** + * Run the String toOther() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testToOther_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + String result = fixture.toOther(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the Properties toProperties() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testToProperties_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + Properties result = fixture.toProperties(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the Document toXML() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testToXML_1() + throws Exception { + StdStatus fixture = new StdStatus(); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setPolicyName(""); + fixture.setPolicyType(PolicyType.JSON); + fixture.setResposneAttributes(new Hashtable()); + fixture.setMatchingConditions(new Hashtable()); + fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); + fixture.setJsonObject((JsonObject) null); + fixture.setDocument((Document) null); + fixture.setProperties(new Properties()); + fixture.setRequestAttributes(new Hashtable()); + fixture.setPolicyVersion(""); + fixture.setActionAdvised(new Hashtable()); + fixture.setOther(""); + fixture.setDecision(PolicyDecision.DENY); + fixture.setDetails(""); + fixture.setActionTaken(new Hashtable()); + + Document result = fixture.toXML(); + + // add additional test code here + assertEquals(null, result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(StdStatusTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/package-info.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/package-info.java new file mode 100644 index 000000000..4c98f98a9 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/package-info.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.std.test; diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/ActionPolicyApiTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ActionPolicyApiTest.java new file mode 100644 index 000000000..a66256432 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ActionPolicyApiTest.java @@ -0,0 +1,239 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyClass; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.std.StdPolicyChangeResponse; + +import junit.framework.TestCase; + +public class ActionPolicyApiTest extends TestCase { + + private static final Logger logger = FlexLogger.getLogger(ActionPolicyApiTest.class); + + private PolicyEngine policyEngine = null; + private PolicyEngine mockPolicyEngine = null; + + PolicyChangeResponse result = null; + StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + PolicyParameters policyParameters = new PolicyParameters(); + + @Before + protected void setUp() throws Exception { + try { + policyEngine = new PolicyEngine("Test/config_pass.properties"); + } catch (PolicyEngineException e) { + logger.error(e.getMessage()); + fail("PolicyEngine Instantiation Error" + e); + } + logger.info("Loaded.. PolicyEngine"); + + mockPolicyEngine = Mockito.mock(PolicyEngine.class); + + policyParameters.setPolicyClass(PolicyClass.Action); //required + policyParameters.setPolicyName("test.junitTest"); //required + policyParameters.setPolicyDescription("testing"); //optional + //policyParameters.setPolicyScope("test"); //Directory will be created where the Policies are saved... this displays a a subscope on the GUI + + //Set the Component Attributes... These are Optional + Map configAttributes = new HashMap(); + configAttributes.put("test", "testing"); + + Map> attributes = new HashMap>(); + attributes.put(AttributeType.MATCHING, configAttributes); + policyParameters.setAttributes(attributes); + + policyParameters.setActionPerformer("PEP"); + policyParameters.setActionAttribute("testing"); + policyParameters.setRequestID(UUID.randomUUID()); + } + + protected void tearDown() throws Exception { + super.tearDown(); + } + + @Test + public final void testCreatePolicy() { + response.setResponseMessage("success"); + PolicyChangeResponse result = null; + try { + + Mockito.when(mockPolicyEngine.createPolicy(policyParameters)).thenReturn(response); + result = mockPolicyEngine.createPolicy(policyParameters); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + @Test + public final void testUpdatePolicy() { + response.setResponseMessage("success"); + PolicyChangeResponse result = null; + try { + + Mockito.when(mockPolicyEngine.updatePolicy(policyParameters)).thenReturn(response); + result = mockPolicyEngine.updatePolicy(policyParameters); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + + } + + @Test + public final void testCreatePolicyNullPolicyName() { + response.setResponseMessage("PE300 - Data Issue: No Policy Name given."); + policyParameters.setPolicyName(null); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testCreatePolicyNullPolicyScope() { + response.setResponseMessage("PE300 - Data Issue: No Policy Scope given."); + policyParameters.setPolicyName("test"); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testCreatePolicyNullActionAttributes() { + response.setResponseMessage("PE300 - Data Issue: No Action Attribute given."); + policyParameters.setActionAttribute(null); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testCreatePolicyNullActionPerformer() { + response.setResponseMessage("PE300 - Data Issue: No Action Performer given."); + policyParameters.setActionPerformer(null); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testCreatePolicyInvalidActionPerformer() { + response.setResponseMessage("PE300 - Data Issue: Invalid Action Performer given."); + policyParameters.setActionPerformer("testfail"); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullPolicyName() { + response.setResponseMessage("PE300 - Data Issue: No Policy Name given."); + policyParameters.setPolicyName(null); + try{ + result = policyEngine.updatePolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullPolicyScope() { + response.setResponseMessage("PE300 - Data Issue: No Policy Scope given."); + policyParameters.setPolicyName("test"); + try{ + result = policyEngine.updatePolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullActionAttributes() { + response.setResponseMessage("PE300 - Data Issue: No Action Attribute given."); + policyParameters.setActionAttribute(null); + try{ + result = policyEngine.updatePolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullActionPerformer() { + response.setResponseMessage("PE300 - Data Issue: No Action Performer given."); + policyParameters.setActionPerformer(null); + try{ + result = policyEngine.updatePolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyInvalidActionPerformer() { + response.setResponseMessage("PE300 - Data Issue: Invalid Action Performer given."); + policyParameters.setActionPerformer("testfail"); + try{ + result = policyEngine.updatePolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/AttributeTypeTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/AttributeTypeTest.java new file mode 100644 index 000000000..62c447fae --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/AttributeTypeTest.java @@ -0,0 +1,81 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.*; +import org.onap.policy.api.AttributeType; + +import static org.junit.Assert.*; + +/** + * The class AttributeTypeTest contains tests for the class {@link AttributeType}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class AttributeTypeTest { + /** + * Run the String toString() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testToString_1() + throws Exception { + AttributeType fixture = AttributeType.MATCHING; + + String result = fixture.toString(); + + // add additional test code here + assertEquals("matching", result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigBasePolicyTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigBasePolicyTest.java new file mode 100644 index 000000000..5d5a076ae --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigBasePolicyTest.java @@ -0,0 +1,325 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.PolicyType; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.std.StdPolicyChangeResponse; + +import junit.framework.TestCase; + +/** + * The class ConfigBasePolicyTest contains tests for the class + * {@link PolicyEngine} + * + * @pattern JUnit Test Case + * * + */ +public class ConfigBasePolicyTest extends TestCase { + + private static final Logger logger = FlexLogger.getLogger(DecisionPolicyApiTest.class); + + private PolicyEngine policyEngine = null; + private PolicyEngine mockPolicyEngine = null; + + PolicyChangeResponse result = null; + StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + PolicyParameters policyParameters = new PolicyParameters(); + + /** + * Perform pre-test initialization + * + * @throws Exception + * + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + try { + policyEngine = new PolicyEngine("Test/config_pass.properties"); + } catch (PolicyEngineException e) { + logger.error(e.getMessage()); + fail("PolicyEngine Instantiation Error" + e); + } + logger.info("Loaded.. PolicyEngine"); + + mockPolicyEngine = Mockito.mock(PolicyEngine.class); + + policyParameters.setPolicyConfigType(PolicyConfigType.Base); //required + policyParameters.setPolicyName("test.junitTest"); //required + policyParameters.setOnapName("test"); + policyParameters.setConfigName("testBase"); + policyParameters.setConfigBodyType(PolicyType.OTHER); + policyParameters.setConfigBody("testing"); + policyParameters.setPolicyDescription("testing"); //optional + //policyParameters.setPolicyScope("test"); //Directory will be created where the Policies are saved... this displays a a subscope on the GUI + + //Set the Component Attributes... These are Optional + Map configAttributes = new HashMap(); + configAttributes.put("test", "testing"); + + Map> attributes = new HashMap>(); + attributes.put(AttributeType.MATCHING, configAttributes); + policyParameters.setAttributes(attributes); + + policyParameters.setRequestID(UUID.randomUUID()); + } + + /** + * Perform post-test clean up + * + * @throws Exception + * + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + // Add additional tear down code here + } + + /** + * Run the PolicyChangeResponse createPolicy(PolicyParameters) method test + */ + public void testCreatePolicy() { + response.setResponseMessage("success"); + PolicyChangeResponse result = null; + try { + + Mockito.when(mockPolicyEngine.createPolicy(policyParameters)).thenReturn(response); + result = mockPolicyEngine.createPolicy(policyParameters); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + /** + * Run the String createConfigPolicy() method test + */ + @SuppressWarnings("deprecation") + @Test + public void testCreateConfigPolicy() { + String response = "success"; + String result = null; + try { + + Mockito.when(mockPolicyEngine.createConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null)).thenReturn(response); + result = mockPolicyEngine.createConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + /** + * Run the PolicyChangeResponse updatePolicy(PolicyParameters) method test + */ + public void testUpdatePolicy() { + response.setResponseMessage("success"); + PolicyChangeResponse result = null; + try { + + Mockito.when(mockPolicyEngine.updatePolicy(policyParameters)).thenReturn(response); + result = mockPolicyEngine.updatePolicy(policyParameters); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + /** + * Run the String updateConfigPolicy() method test + */ + @SuppressWarnings("deprecation") + @Test + public void testUpdateConfigPolicy() { + String response = "success"; + String result = null; + try { + + Mockito.when(mockPolicyEngine.updateConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null)).thenReturn(response); + result = mockPolicyEngine.updateConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + @Test + public final void testCreatePolicyNullPolicyName() { + response.setResponseMessage("PE300 - Data Issue: No Policy Name given."); + policyParameters.setPolicyName(null); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testCreatePolicyNullPolicyScope() { + response.setResponseMessage("PE300 - Data Issue: No Policy Scope given."); + policyParameters.setPolicyName("test"); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testCreatePolicyNullOnapName() { + response.setResponseMessage("PE300 - Data Issue: No ONAP Name given."); + policyParameters.setOnapName(null); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testCreatePolicyNullPolicyConfigName() { + response.setResponseMessage("PE300 - Data Issue: No Config Name given."); + policyParameters.setConfigName(null);; + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testCreatePolicyNullPolicyConfigBodyType() { + response.setResponseMessage("PE300 - Data Issue: No Config Body Type given."); + policyParameters.setConfigBodyType(null); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testCreatePolicyNullPolicyConfigBody() { + response.setResponseMessage("PE300 - Data Issue: No Config Body given."); + policyParameters.setConfigBody(null); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullPolicyName() { + response.setResponseMessage("PE300 - Data Issue: No Policy Name given."); + policyParameters.setPolicyName(null); + try{ + result = policyEngine.updatePolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullPolicyScope() { + response.setResponseMessage("PE300 - Data Issue: No Policy Scope given."); + policyParameters.setPolicyName("test"); + try{ + result = policyEngine.updatePolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullOnapName() { + response.setResponseMessage("PE300 - Data Issue: No ONAP Name given."); + policyParameters.setOnapName(null); + try{ + result = policyEngine.updatePolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullPolicyConfigName() { + response.setResponseMessage("PE300 - Data Issue: No Config Name given."); + policyParameters.setConfigName(null);; + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullPolicyConfigBodyType() { + response.setResponseMessage("PE300 - Data Issue: No Config Body Type given."); + policyParameters.setConfigBodyType(null); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullPolicyConfigBody() { + response.setResponseMessage("PE300 - Data Issue: No Config Body given."); + policyParameters.setConfigBody(null); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + //assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } +} \ No newline at end of file diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigFirewallPolicyTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigFirewallPolicyTest.java new file mode 100644 index 000000000..78ae2493b --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigFirewallPolicyTest.java @@ -0,0 +1,254 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import java.io.StringReader; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonReader; + +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.std.StdPolicyChangeResponse; + +import junit.framework.TestCase; + +public class ConfigFirewallPolicyTest extends TestCase { + + private static final Logger logger = FlexLogger.getLogger(DecisionPolicyApiTest.class); + + private PolicyEngine policyEngine = null; + private PolicyEngine mockPolicyEngine = null; + + PolicyChangeResponse result = null; + StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + PolicyParameters policyParameters = new PolicyParameters(); + String json = null; + + /** + * Perform pre-test initialization + * + * @throws Exception + * + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + try { + policyEngine = new PolicyEngine("Test/config_pass.properties"); + } catch (PolicyEngineException e) { + logger.error(e.getMessage()); + fail("PolicyEngine Instantiation Error" + e); + } + logger.info("Loaded.. PolicyEngine"); + + mockPolicyEngine = Mockito.mock(PolicyEngine.class); + + policyParameters.setPolicyConfigType(PolicyConfigType.Firewall); //required + policyParameters.setPolicyName("test.junitTest"); //required + + json = "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"rule1607\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"/v0/firewall/pan\",\"serviceGroups\":[{\"name\":\"1607Group\",\"description\":null,\"members\":[{\"type\":\"REFERENCE\",\"name\":\"SList\"},{\"type\":\"REFERENCE\",\"name\":\"Syslog\"}]},{\"name\":\"Syslog\",\"description\":\"NA\",\"type\":\"SERVICE\",\"transportProtocol\":\"udp\",\"appProtocol\":null,\"ports\":\"514\"},{\"name\":\"SList\",\"description\":\"Service List\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"8080\"}],\"addressGroups\":[{\"name\":\"1607Group\",\"description\":null,\"members\":[{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"},{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"}]},{\"name\":\"PL_CCE3\",\"description\":\"CCE Routers\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"1607Rule\",\"fromZones\":[\"Trusted\"],\"toZones\":[\"Untrusted\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"value\":\"PL_CCE3\"},{\"type\":\"REFERENCE\",\"value\":\"1607Group\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"value\":\"1607Group\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"1607Group\"}],\"action\":\"accept\",\"description\":\"Rule for 1607 templates\",\"enabled\":true,\"log\":true}]}"; + + policyParameters.setConfigBody(buildJSON(json).toString()); + + //policyParameters.setPolicyScope("test"); //Directory will be created where the Policies are saved... this displays a a subscope on the GUI + policyParameters.setRequestID(UUID.randomUUID()); + } + + private static JsonObject buildJSON(String jsonString) { + JsonObject json = null;; + if (jsonString != null) { + StringReader in = null; + + in = new StringReader(jsonString); + + JsonReader jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + } + + return json; + } + /** + * Perform post-test clean up + * + * @throws Exception + * + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + // Add additional tear down code here + } + + /** + * Run the PolicyChangeResponse createPolicy(PolicyParameters) method test + */ + public void testCreatePolicy() { + response.setResponseMessage("success"); + PolicyChangeResponse result = null; + try { + + Mockito.when(mockPolicyEngine.createPolicy(policyParameters)).thenReturn(response); + result = mockPolicyEngine.createPolicy(policyParameters); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + /** + * Run the String createConfigFirewallPolicy() method test + */ + @SuppressWarnings("deprecation") + @Test + public void testCreateConfigFirewallPolicy() { + String response = "success"; + String result = null; + JsonObject jsonObj = buildJSON(json); + try { + + Mockito.when(mockPolicyEngine.createConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null)).thenReturn(response); + result = mockPolicyEngine.createConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + /** + * Run the PolicyChangeResponse updatePolicy(PolicyParameters) method test + */ + public void testUpdatePolicy() { + response.setResponseMessage("success"); + PolicyChangeResponse result = null; + try { + + Mockito.when(mockPolicyEngine.updatePolicy(policyParameters)).thenReturn(response); + result = mockPolicyEngine.updatePolicy(policyParameters); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + /** + * Run the String updateConfigFirewallPolicy() method test + */ + @SuppressWarnings("deprecation") + @Test + public void testUpdateConfigFirewallPolicy() { + String response = "success"; + String result = null; + JsonObject jsonObj = buildJSON(json); + try { + + Mockito.when(mockPolicyEngine.updateConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null)).thenReturn(response); + result = mockPolicyEngine.updateConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + @Test + public final void testCreatePolicyNullPolicyName() { + response.setResponseMessage("PE500 - Process Flow Issue: :500:"); + policyParameters.setPolicyName(null); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testCreatePolicyNullPolicyScope() { + response.setResponseMessage("PE500 - Process Flow Issue: :500:"); + policyParameters.setPolicyName("test"); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testCreatePolicyNullPolicyConfigBody() { + response.setResponseMessage("PE500 - Process Flow Issue: :500:"); + policyParameters.setConfigBody(null); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullPolicyName() { + response.setResponseMessage("PE500 - Process Flow Issue: :500:"); + policyParameters.setPolicyName(null); + try{ + result = policyEngine.updatePolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullPolicyScope() { + response.setResponseMessage("PE500 - Process Flow Issue: :500:"); + policyParameters.setPolicyName("test"); + try{ + result = policyEngine.updatePolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullPolicyConfigBody() { + response.setResponseMessage("PE500 - Process Flow Issue: :500:"); + policyParameters.setConfigBody(null); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigRequestParametersTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigRequestParametersTest.java new file mode 100644 index 000000000..91025f5c0 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ConfigRequestParametersTest.java @@ -0,0 +1,362 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import java.util.Hashtable; +import java.util.Map; +import java.util.UUID; + +import org.junit.*; +import org.onap.policy.api.ConfigRequestParameters; + +import static org.junit.Assert.*; + +/** + * The class ConfigRequestParametersTest contains tests for the class {@link ConfigRequestParameters}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class ConfigRequestParametersTest { + /** + * Run the ConfigRequestParameters() constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testConfigRequestParameters_1() + throws Exception { + + ConfigRequestParameters result = new ConfigRequestParameters(); + + // add additional test code here + assertNotNull(result); + assertEquals(null, result.getPolicyName()); + assertEquals(null, result.getConfigName()); + assertEquals(null, result.getConfigAttributes()); + assertEquals(null, result.getRequestID()); + assertEquals(null, result.getOnapName()); + assertEquals(Boolean.FALSE, result.getUnique()); + } + + /** + * Run the ConfigRequestParameters(String,String,String,Map,Boolean,UUID) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testConfigRequestParameters_2() + throws Exception { + String policyName = ""; + String onapComponentName = ""; + String configName = ""; + Map configAttributes = new Hashtable(); + Boolean unique = new Boolean(true); + UUID requestID = UUID.randomUUID(); + + ConfigRequestParameters result = createConfigRequest(policyName, onapComponentName, configName, configAttributes, unique, requestID); + + // add additional test code here + assertNotNull(result); + assertEquals("", result.getPolicyName()); + assertEquals("", result.getConfigName()); + assertEquals("", result.getOnapName()); + assertEquals(Boolean.TRUE, result.getUnique()); + } + + /** + * Run the Map getConfigAttributes() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetConfigAttributes_1() + throws Exception { + ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); + + Map result = fixture.getConfigAttributes(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the String getConfigName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetConfigName_1() + throws Exception { + ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); + + String result = fixture.getConfigName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getOnapName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetOnapName_1() + throws Exception { + ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); + + String result = fixture.getOnapName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyName_1() + throws Exception { + ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the UUID getRequestID() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetRequestID_1() + throws Exception { + ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.fromString("6b5aa070-90bc-46a6-9a59-e1fe526df7ae")); + + UUID result = fixture.getRequestID(); + + // add additional test code here + assertNotNull(result); + assertEquals("6b5aa070-90bc-46a6-9a59-e1fe526df7ae", result.toString()); + assertEquals(4, result.version()); + assertEquals(2, result.variant()); + assertEquals(-7324574836520519762L, result.getLeastSignificantBits()); + assertEquals(7735671715287287462L, result.getMostSignificantBits()); + } + + /** + * Run the Boolean getUnique() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetUnique_1() + throws Exception { + ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); + + Boolean result = fixture.getUnique(); + + // add additional test code here + assertNotNull(result); + assertEquals("true", result.toString()); + assertEquals(true, result.booleanValue()); + } + + /** + * Run the void makeUnique(Boolean) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testMakeUnique_1() + throws Exception { + ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); + Boolean unique = new Boolean(true); + + fixture.makeUnique(unique); + + // add additional test code here + } + + /** + * Run the void setConfigAttributes(Map) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetConfigAttributes_1() + throws Exception { + ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); + Map configAttributes = new Hashtable(); + + fixture.setConfigAttributes(configAttributes); + + // add additional test code here + } + + /** + * Run the void setConfigName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetConfigName_1() + throws Exception { + ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); + String configName = ""; + + fixture.setConfigName(configName); + + // add additional test code here + } + + /** + * Run the void setOnapName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetOnapName_1() + throws Exception { + ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); + String onapComponentName = ""; + + fixture.setOnapName(onapComponentName); + + // add additional test code here + } + + /** + * Run the void setPolicyName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyName_1() + throws Exception { + ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); + String policyName = ""; + + fixture.setPolicyName(policyName); + + // add additional test code here + } + + /** + * Run the void setRequestID(UUID) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetRequestID_1() + throws Exception { + ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); + UUID requestID = UUID.randomUUID(); + + fixture.setRequestID(requestID); + + // add additional test code here + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(ConfigRequestParametersTest.class); + } + + private ConfigRequestParameters createConfigRequest(String policyName, String onapComponentName, String configName, Map configAttributes, Boolean unique, UUID requestID){ + ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); + configRequestParameters.setRequestID(requestID); + configRequestParameters.setPolicyName(policyName); + configRequestParameters.setOnapName(onapComponentName); + configRequestParameters.setConfigName(configName); + configRequestParameters.setConfigAttributes(configAttributes); + configRequestParameters.makeUnique(unique); + return configRequestParameters; + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/DecisionPolicyApiTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/DecisionPolicyApiTest.java new file mode 100644 index 000000000..a80093470 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/DecisionPolicyApiTest.java @@ -0,0 +1,219 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyClass; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.std.StdPolicyChangeResponse; + +import junit.framework.TestCase; + +/** + * The class DecisionPolicyApiTest contains tests for the class + * {@link PolicyEngine} + * + * @pattern JUnit Test Case + * * + */ +public class DecisionPolicyApiTest extends TestCase { + + private static final Logger logger = FlexLogger.getLogger(DecisionPolicyApiTest.class); + + private PolicyEngine policyEngine = null; + private PolicyEngine mockPolicyEngine = null; + + PolicyChangeResponse result = null; + StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + PolicyParameters policyParameters = new PolicyParameters(); + + /** + * Perform pre-test initialization + * + * @throws Exception + * + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + try { + policyEngine = new PolicyEngine("Test/config_pass.properties"); + } catch (PolicyEngineException e) { + logger.error(e.getMessage()); + fail("PolicyEngine Instantiation Error" + e); + } + logger.info("Loaded.. PolicyEngine"); + + mockPolicyEngine = Mockito.mock(PolicyEngine.class); + + policyParameters.setPolicyClass(PolicyClass.Decision); //required + policyParameters.setPolicyName("test.junitTest"); //required + policyParameters.setOnapName("test"); + policyParameters.setPolicyDescription("testing"); //optional + //policyParameters.setPolicyScope("test"); //Directory will be created where the Policies are saved... this displays a a subscope on the GUI + + //Set the Component Attributes... These are Optional + Map configAttributes = new HashMap(); + configAttributes.put("test", "testing"); + + Map> attributes = new HashMap>(); + attributes.put(AttributeType.MATCHING, configAttributes); + policyParameters.setAttributes(attributes); + + //Set the settings... These are Optional +/* Map settingsMap = new HashMap(); + settingsMap.put("server", "5"); + + Map> settings = new HashMap>(); + settings.put(AttributeType.SETTINGS, settingsMap); + policyParameters.setSettings(settings);*/ + + policyParameters.setRequestID(UUID.randomUUID()); + } + + /** + * Perform post-test clean up + * + * @throws Exception + * + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + // Add additional tear down code here + } + + /** + * Run the PolicyChangeResponse createPolicy(PolicyParameters) method test + */ + public void testCreatePolicy() { + response.setResponseMessage("success"); + PolicyChangeResponse result = null; + try { + + Mockito.when(mockPolicyEngine.createPolicy(policyParameters)).thenReturn(response); + result = mockPolicyEngine.createPolicy(policyParameters); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + /** + * Run the PolicyChangeResponse updatePolicy(PolicyParameters) method test + */ + public void testUpdatePolicy() { + response.setResponseMessage("success"); + PolicyChangeResponse result = null; + try { + + Mockito.when(mockPolicyEngine.updatePolicy(policyParameters)).thenReturn(response); + result = mockPolicyEngine.updatePolicy(policyParameters); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + @Test + public final void testCreatePolicyNullPolicyName() { + response.setResponseMessage("PE500 - Process Flow Issue: :500:"); + policyParameters.setPolicyName(null); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testCreatePolicyNullPolicyScope() { + response.setResponseMessage("PE500 - Process Flow Issue: :500:"); + policyParameters.setPolicyName("test"); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testCreatePolicyNullOnapName() { + response.setResponseMessage("PE500 - Process Flow Issue: :500:"); + policyParameters.setOnapName(null); + try{ + result = policyEngine.createPolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullPolicyName() { + response.setResponseMessage("PE500 - Process Flow Issue: :500:"); + policyParameters.setPolicyName(null); + try{ + result = policyEngine.updatePolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullPolicyScope() { + response.setResponseMessage("PE500 - Process Flow Issue: :500:"); + policyParameters.setPolicyName("test"); + try{ + result = policyEngine.updatePolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } + + @Test + public final void testUpdatePolicyNullOnapName() { + response.setResponseMessage("PE500 - Process Flow Issue: :500:"); + policyParameters.setOnapName(null); + try{ + result = policyEngine.updatePolicy(policyParameters); + } catch (Exception e){ + logger.warn(e.getMessage()); + } + assertEquals(result.getResponseMessage(), response.getResponseMessage()); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/DecisionRequestParametersTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/DecisionRequestParametersTest.java new file mode 100644 index 000000000..746822f94 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/DecisionRequestParametersTest.java @@ -0,0 +1,232 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import java.util.Hashtable; +import java.util.Map; +import java.util.UUID; + +import org.junit.*; +import org.onap.policy.api.DecisionRequestParameters; + +import static org.junit.Assert.*; + +/** + * The class DecisionRequestParametersTest contains tests for the class {@link DecisionRequestParameters}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class DecisionRequestParametersTest { + /** + * Run the DecisionRequestParameters() constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testDecisionRequestParameters_1() + throws Exception { + + DecisionRequestParameters result = new DecisionRequestParameters(); + + // add additional test code here + assertNotNull(result); + assertEquals(null, result.getONAPComponentName()); + assertEquals(null, result.getDecisionAttributes()); + assertEquals(null, result.getRequestID()); + } + + /** + * Run the DecisionRequestParameters(String,Map,UUID) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testDecisionRequestParameters_2() + throws Exception { + String onapComponentName = ""; + Map decisionAttributes = new Hashtable(); + UUID requestID = UUID.randomUUID(); + + DecisionRequestParameters result = new DecisionRequestParameters(onapComponentName, decisionAttributes, requestID); + + // add additional test code here + assertNotNull(result); + assertEquals("", result.getONAPComponentName()); + } + + /** + * Run the Map getDecisionAttributes() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetDecisionAttributes_1() + throws Exception { + DecisionRequestParameters fixture = new DecisionRequestParameters("", new Hashtable(), UUID.randomUUID()); + + Map result = fixture.getDecisionAttributes(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the String getONAPComponentName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetONAPComponentName_1() + throws Exception { + DecisionRequestParameters fixture = new DecisionRequestParameters("", new Hashtable(), UUID.randomUUID()); + + String result = fixture.getONAPComponentName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the UUID getRequestID() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetRequestID_1() + throws Exception { + DecisionRequestParameters fixture = new DecisionRequestParameters("", new Hashtable(), UUID.fromString("d1db6a6d-7140-4864-8200-6b541261fdd2")); + + UUID result = fixture.getRequestID(); + + // add additional test code here + assertNotNull(result); + assertEquals("d1db6a6d-7140-4864-8200-6b541261fdd2", result.toString()); + assertEquals(4, result.version()); + assertEquals(2, result.variant()); + assertEquals(-9079138839949083182L, result.getLeastSignificantBits()); + assertEquals(-3324946881598961564L, result.getMostSignificantBits()); + } + + /** + * Run the void setDecisionAttributes(Map) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetDecisionAttributes_1() + throws Exception { + DecisionRequestParameters fixture = new DecisionRequestParameters("", new Hashtable(), UUID.randomUUID()); + Map decisionAttributes = new Hashtable(); + + fixture.setDecisionAttributes(decisionAttributes); + + // add additional test code here + } + + /** + * Run the void setONAPComponentName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetONAPComponentName_1() + throws Exception { + DecisionRequestParameters fixture = new DecisionRequestParameters("", new Hashtable(), UUID.randomUUID()); + String onapComponentName = ""; + + fixture.setONAPComponentName(onapComponentName); + + // add additional test code here + } + + /** + * Run the void setRequestID(UUID) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetRequestID_1() + throws Exception { + DecisionRequestParameters fixture = new DecisionRequestParameters("", new Hashtable(), UUID.randomUUID()); + UUID requestID = UUID.randomUUID(); + + fixture.setRequestID(requestID); + + // add additional test code here + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(DecisionRequestParametersTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/DeletePolicyConditionTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/DeletePolicyConditionTest.java new file mode 100644 index 000000000..2513816bb --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/DeletePolicyConditionTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.*; +import org.onap.policy.api.DeletePolicyCondition; + +import static org.junit.Assert.*; + +/** + * The class DeletePolicyConditionTest contains tests for the class {@link DeletePolicyCondition}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class DeletePolicyConditionTest { + /** + * Run the String toString() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testToString_1() + throws Exception { + DeletePolicyCondition fixture = DeletePolicyCondition.ALL; + + String result = fixture.toString(); + + // add additional test code here + assertEquals("All Versions", result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(DeletePolicyConditionTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/DeletePolicyParametersTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/DeletePolicyParametersTest.java new file mode 100644 index 000000000..423b839f6 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/DeletePolicyParametersTest.java @@ -0,0 +1,314 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import java.util.UUID; + +import org.junit.*; +import org.onap.policy.api.DeletePolicyCondition; +import org.onap.policy.api.DeletePolicyParameters; + +import static org.junit.Assert.*; + +/** + * The class DeletePolicyParametersTest contains tests for the class {@link DeletePolicyParameters}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class DeletePolicyParametersTest { + /** + * Run the DeletePolicyCondition getDeleteCondition() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetDeleteCondition_1() + throws Exception { + DeletePolicyParameters fixture = new DeletePolicyParameters(); + fixture.setPolicyComponent(""); + fixture.setPolicyName(""); + fixture.setDeleteCondition(DeletePolicyCondition.ALL); + fixture.setRequestID(UUID.randomUUID()); + fixture.setPdpGroup(""); + + DeletePolicyCondition result = fixture.getDeleteCondition(); + + // add additional test code here + assertNotNull(result); + assertEquals("All Versions", result.toString()); + assertEquals("ALL", result.name()); + assertEquals(1, result.ordinal()); + } + + /** + * Run the String getPdpGroup() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPdpGroup_1() + throws Exception { + DeletePolicyParameters fixture = new DeletePolicyParameters(); + fixture.setPolicyComponent(""); + fixture.setPolicyName(""); + fixture.setDeleteCondition(DeletePolicyCondition.ALL); + fixture.setRequestID(UUID.randomUUID()); + fixture.setPdpGroup(""); + + String result = fixture.getPdpGroup(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getPolicyComponent() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyComponent_1() + throws Exception { + DeletePolicyParameters fixture = new DeletePolicyParameters(); + fixture.setPolicyComponent(""); + fixture.setPolicyName(""); + fixture.setDeleteCondition(DeletePolicyCondition.ALL); + fixture.setRequestID(UUID.randomUUID()); + fixture.setPdpGroup(""); + + String result = fixture.getPolicyComponent(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyName_1() + throws Exception { + DeletePolicyParameters fixture = new DeletePolicyParameters(); + fixture.setPolicyComponent(""); + fixture.setPolicyName(""); + fixture.setDeleteCondition(DeletePolicyCondition.ALL); + fixture.setRequestID(UUID.randomUUID()); + fixture.setPdpGroup(""); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the UUID getRequestID() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetRequestID_1() + throws Exception { + DeletePolicyParameters fixture = new DeletePolicyParameters(); + fixture.setPolicyComponent(""); + fixture.setPolicyName(""); + fixture.setDeleteCondition(DeletePolicyCondition.ALL); + fixture.setRequestID(UUID.fromString("482e90e2-2ad7-4265-9893-4cfe08ef1e3d")); + fixture.setPdpGroup(""); + + UUID result = fixture.getRequestID(); + + // add additional test code here + assertNotNull(result); + assertEquals("482e90e2-2ad7-4265-9893-4cfe08ef1e3d", result.toString()); + assertEquals(4, result.version()); + assertEquals(2, result.variant()); + assertEquals(-7452528304412746179L, result.getLeastSignificantBits()); + assertEquals(5201253920715260517L, result.getMostSignificantBits()); + } + + /** + * Run the void setDeleteCondition(DeletePolicyCondition) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetDeleteCondition_1() + throws Exception { + DeletePolicyParameters fixture = new DeletePolicyParameters(); + fixture.setPolicyComponent(""); + fixture.setPolicyName(""); + fixture.setDeleteCondition(DeletePolicyCondition.ALL); + fixture.setRequestID(UUID.randomUUID()); + fixture.setPdpGroup(""); + DeletePolicyCondition deleteCondition = DeletePolicyCondition.ALL; + + fixture.setDeleteCondition(deleteCondition); + + // add additional test code here + } + + /** + * Run the void setPdpGroup(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPdpGroup_1() + throws Exception { + DeletePolicyParameters fixture = new DeletePolicyParameters(); + fixture.setPolicyComponent(""); + fixture.setPolicyName(""); + fixture.setDeleteCondition(DeletePolicyCondition.ALL); + fixture.setRequestID(UUID.randomUUID()); + fixture.setPdpGroup(""); + String pdpGroup = ""; + + fixture.setPdpGroup(pdpGroup); + + // add additional test code here + } + + /** + * Run the void setPolicyComponent(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyComponent_1() + throws Exception { + DeletePolicyParameters fixture = new DeletePolicyParameters(); + fixture.setPolicyComponent(""); + fixture.setPolicyName(""); + fixture.setDeleteCondition(DeletePolicyCondition.ALL); + fixture.setRequestID(UUID.randomUUID()); + fixture.setPdpGroup(""); + String policyComponent = ""; + + fixture.setPolicyComponent(policyComponent); + + // add additional test code here + } + + /** + * Run the void setPolicyName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyName_1() + throws Exception { + DeletePolicyParameters fixture = new DeletePolicyParameters(); + fixture.setPolicyComponent(""); + fixture.setPolicyName(""); + fixture.setDeleteCondition(DeletePolicyCondition.ALL); + fixture.setRequestID(UUID.randomUUID()); + fixture.setPdpGroup(""); + String policyName = ""; + + fixture.setPolicyName(policyName); + + // add additional test code here + } + + /** + * Run the void setRequestID(UUID) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetRequestID_1() + throws Exception { + DeletePolicyParameters fixture = new DeletePolicyParameters(); + fixture.setPolicyComponent(""); + fixture.setPolicyName(""); + fixture.setDeleteCondition(DeletePolicyCondition.ALL); + fixture.setRequestID(UUID.randomUUID()); + fixture.setPdpGroup(""); + UUID requestID = UUID.randomUUID(); + + fixture.setRequestID(requestID); + + // add additional test code here + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(DeletePolicyParametersTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/EventRequestParametersTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/EventRequestParametersTest.java new file mode 100644 index 000000000..4fecea8c2 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/EventRequestParametersTest.java @@ -0,0 +1,193 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import java.util.Hashtable; +import java.util.Map; +import java.util.UUID; + +import org.junit.*; +import org.onap.policy.api.EventRequestParameters; + +import static org.junit.Assert.*; + +/** + * The class EventRequestParametersTest contains tests for the class {@link EventRequestParameters}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class EventRequestParametersTest { + /** + * Run the EventRequestParameters() constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testEventRequestParameters_1() + throws Exception { + + EventRequestParameters result = new EventRequestParameters(); + + // add additional test code here + assertNotNull(result); + assertEquals(null, result.getEventAttributes()); + assertEquals(null, result.getRequestID()); + } + + /** + * Run the EventRequestParameters(Map,UUID) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testEventRequestParameters_2() + throws Exception { + Map eventAttributes = new Hashtable(); + UUID requestID = UUID.randomUUID(); + + EventRequestParameters result = new EventRequestParameters(eventAttributes, requestID); + + // add additional test code here + assertNotNull(result); + } + + /** + * Run the Map getEventAttributes() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetEventAttributes_1() + throws Exception { + EventRequestParameters fixture = new EventRequestParameters(new Hashtable(), UUID.randomUUID()); + + Map result = fixture.getEventAttributes(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the UUID getRequestID() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetRequestID_1() + throws Exception { + EventRequestParameters fixture = new EventRequestParameters(new Hashtable(), UUID.fromString("5b15376d-569b-4772-ac75-9362043f6a6c")); + + UUID result = fixture.getRequestID(); + + // add additional test code here + assertNotNull(result); + assertEquals("5b15376d-569b-4772-ac75-9362043f6a6c", result.toString()); + assertEquals(4, result.version()); + assertEquals(2, result.variant()); + assertEquals(-6019743277723456916L, result.getLeastSignificantBits()); + assertEquals(6563212974706345842L, result.getMostSignificantBits()); + } + + /** + * Run the void setEventAttributes(Map) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetEventAttributes_1() + throws Exception { + EventRequestParameters fixture = new EventRequestParameters(new Hashtable(), UUID.randomUUID()); + Map eventAttributes = new Hashtable(); + + fixture.setEventAttributes(eventAttributes); + + // add additional test code here + } + + /** + * Run the void setRequestID(UUID) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetRequestID_1() + throws Exception { + EventRequestParameters fixture = new EventRequestParameters(new Hashtable(), UUID.randomUUID()); + UUID requestID = UUID.randomUUID(); + + fixture.setRequestID(requestID); + + // add additional test code here + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(EventRequestParametersTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigByPolicyNameTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigByPolicyNameTest.java new file mode 100644 index 000000000..07af71eaf --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigByPolicyNameTest.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import java.util.Collection; + +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.api.PolicyConfig; +import org.onap.policy.api.PolicyConfigException; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +import junit.framework.TestCase; + +public class GetConfigByPolicyNameTest extends TestCase { + private PolicyEngine policyEngine = null; + private String policyName = null; + private Collection policyConfig = null; + private static final Logger logger = FlexLogger.getLogger(GetConfigByPolicyNameTest.class); + @Before + public void setUp() { + try { + policyEngine = new PolicyEngine("Test/config_pass.properties"); + } catch (PolicyEngineException e) { + logger.error(e.getMessage()); + fail("PolicyEngine Instantiation Error" + e); + } + logger.info("Loaded.. PolicyEngine"); + } + + @SuppressWarnings("deprecation") + @Test + public void testGetConfigPolicyNameNotValid(){ + policyName = null; + try{ + policyConfig = policyEngine.getConfigByPolicyName(policyName); + } catch (PolicyConfigException e){ + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigStringStringMapTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigStringStringMapTest.java new file mode 100644 index 000000000..f70a16a98 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigStringStringMapTest.java @@ -0,0 +1,259 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.api.PolicyConfig; +import org.onap.policy.api.PolicyConfigException; +import org.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.api.PolicyType; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +public class GetConfigStringStringMapTest { + + private PolicyEngine policyEngine = null; + private String onapComponentName = null; + private String configName = null; + private Map configAttributes = new HashMap(); + private Collection policyConfig = null; + private static final Logger logger = FlexLogger.getLogger(GetConfigStringStringMapTest.class); + @Before + public void setUp() { + try { + policyEngine = new PolicyEngine("Test/config_pass.properties"); + } catch (PolicyEngineException e) { + logger.error(e.getMessage()); + fail("PolicyEngine Instantiation Error" + e); + } + logger.info("Loaded.. PolicyEngine"); + } + + @SuppressWarnings("deprecation") + @Test + public void testGetConfigStringStringMapFail() { + onapComponentName = null; + configName = null; + configAttributes = null; + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName, configAttributes); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + @SuppressWarnings("deprecation") + @Test + public void testGetConfigStringStringMapFail1() { + onapComponentName = null; + configName = "testFail"; + configAttributes.put("TestValue", "Fail"); + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName, configAttributes); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + @SuppressWarnings("deprecation") + @Test + public void testGetConfigStringStringMapFail2() { + onapComponentName = "TestFail"; + configName = null; + configAttributes.put("TestValue", "Fail"); + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName, configAttributes); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + @SuppressWarnings("deprecation") + @Test + public void testGetConfigStringStringMapFail3() { + onapComponentName = "TestFail"; + configName = "configFail"; + configAttributes= null; + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName, configAttributes); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + @SuppressWarnings("deprecation") + @Test + public void testGetConfigStringStringMapfail4() { + onapComponentName = "TestFail"; + configName = "configFail"; + configAttributes.put("", ""); + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName, configAttributes); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + //@Test + @SuppressWarnings("deprecation") + public void testGetConfigStringStringMapNotValid() { + onapComponentName = "TestFail"; + configName = "configFail"; + configAttributes.put("Action:com.test.fail", "Value"); + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName, configAttributes); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + for(PolicyConfig policyConfig : this.policyConfig){ + logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig); + assertEquals(PolicyConfigStatus.CONFIG_NOT_FOUND,policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig.getPolicyConfigMessage()); + assertNull(policyConfig.getType()); + assertNull(policyConfig.toJSON()); + assertNull(policyConfig.toProperties()); + assertNull(policyConfig.toXML()); + assertNull(policyConfig.toOther()); + } + } + + //@Test + @SuppressWarnings("deprecation") + public void testGetConfigStringStringMapValidJSON() { + onapComponentName = "JSON"; + configName = "JSONconfig"; + configAttributes.put("Resource.com:test:resource:json", "Test"); + configAttributes.put("Action.com:test:action:json", "TestJSON"); + configAttributes.put("Subject.com:test:subject:json", "TestSubject"); + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName, configAttributes); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + for(PolicyConfig policyConfig : this.policyConfig){ + logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig); + assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig.getPolicyConfigMessage()); + assertEquals(PolicyType.JSON,policyConfig.getType()); + assertNotNull(policyConfig.toJSON()); + assertNull(policyConfig.toProperties()); + assertNull(policyConfig.toXML()); + assertNull(policyConfig.toOther()); + } + } + + //@Test + @SuppressWarnings("deprecation") + public void testGetConfigStringStringMapValidXML() { + onapComponentName = "XML"; + configName = "XMLconfig"; + configAttributes.put("Resource.com:test:resource:json", "Test"); + configAttributes.put("Action.com:test:action:json", "TestJSON"); + configAttributes.put("Subject.com:test:subject:json", "TestSubject"); + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName, configAttributes); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + for(PolicyConfig policyConfig : this.policyConfig){ + logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig); + assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig.getPolicyConfigMessage()); + assertEquals(PolicyType.XML,policyConfig.getType()); + assertNull(policyConfig.toJSON()); + assertNull(policyConfig.toProperties()); + assertNotNull(policyConfig.toXML()); + assertNull(policyConfig.toOther()); + } + } + + //@Test + @SuppressWarnings("deprecation") + public void testGetConfigStringStringMapValidProperties() { + onapComponentName = "Properties"; + configName = "PropConfig" ; + configAttributes.put("Resource.com:test:resource:json", "Test"); + configAttributes.put("Action.com:test:action:json", "TestJSON"); + configAttributes.put("Subject.com:test:subject:json", "TestSubject"); + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName, configAttributes); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + for(PolicyConfig policyConfig : this.policyConfig){ + logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig); + assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig.getPolicyConfigMessage()); + assertEquals(PolicyType.PROPERTIES,policyConfig.getType()); + assertNull(policyConfig.toJSON()); + assertNotNull(policyConfig.toProperties()); + assertNull(policyConfig.toXML()); + assertNull(policyConfig.toOther()); + } + } + + //@Test + @SuppressWarnings("deprecation") + public void testGetConfigStringStringMapValidOther() { + onapComponentName = "Other"; + configName = "OtherConfig" ; + configAttributes.put("Resource.com:test:resource:json", "Test"); + configAttributes.put("Action.com:test:action:json", "TestJSON"); + configAttributes.put("Subject.com:test:subject:json", "TestSubject"); + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName, configAttributes); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + for(PolicyConfig policyConfig : this.policyConfig){ + logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig); + assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig.getPolicyConfigMessage()); + assertEquals(PolicyType.OTHER,policyConfig.getType()); + assertNull(policyConfig.toJSON()); + assertNull(policyConfig.toProperties()); + assertNull(policyConfig.toXML()); + assertNotNull(policyConfig.toOther()); + } + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigStringStringTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigStringStringTest.java new file mode 100644 index 000000000..0a6db2dd4 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigStringStringTest.java @@ -0,0 +1,213 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.util.Collection; + +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.api.PolicyConfig; +import org.onap.policy.api.PolicyConfigException; +import org.onap.policy.api.PolicyConfigStatus; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.api.PolicyType; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +public class GetConfigStringStringTest { + + private PolicyEngine policyEngine = null; + private String onapComponentName = null; + private String configName = null; + private Collection policyConfig = null; + private static final Logger logger = FlexLogger.getLogger(GetConfigStringStringTest.class); + @Before + public void setUp() { + try { + policyEngine = new PolicyEngine("Test/config_pass.properties"); + } catch (PolicyEngineException e) { + logger.error(e.getMessage()); + fail("PolicyEngine Instantiation Error" + e); + } + logger.info("Loaded.. PolicyEngine"); + } + + @SuppressWarnings("deprecation") + @Test + public void testGetConfigStringStringFail() { + onapComponentName = null; + configName = null; + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + @SuppressWarnings("deprecation") + @Test + public void testGetConfigStringStringFail1() { + onapComponentName = null; + configName = ""; + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + @SuppressWarnings("deprecation") + @Test + public void testGetConfigStringStringFail2() { + onapComponentName = ""; + configName = null; + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + //@Test + @SuppressWarnings("deprecation") + public void testGetConfigStringStringNotvalid() { + onapComponentName = "fail"; + configName = "fail"; + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + for(PolicyConfig policyConfig : this.policyConfig){ + logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig); + assertEquals(PolicyConfigStatus.CONFIG_NOT_FOUND,policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig.getPolicyConfigMessage()); + assertNull(policyConfig.getType()); + assertNull(policyConfig.toJSON()); + assertNull(policyConfig.toProperties()); + assertNull(policyConfig.toXML()); + assertNull(policyConfig.toOther()); + } + } + + //@Test + @SuppressWarnings("deprecation") + public void testGetConfigStringStringValidJSON() { + onapComponentName = "JSON"; + configName = "JSONconfig"; + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + for(PolicyConfig policyConfig : this.policyConfig){ + logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig); + assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig.getPolicyConfigMessage()); + assertEquals(PolicyType.JSON,policyConfig.getType()); + assertNotNull(policyConfig.toJSON()); + assertNull(policyConfig.toProperties()); + assertNull(policyConfig.toXML()); + assertNull(policyConfig.toOther()); + } + } + + //@Test + @SuppressWarnings("deprecation") + public void testGetConfigStringStringValidXML() { + onapComponentName = "XML"; + configName = "XMLconfig"; + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + for(PolicyConfig policyConfig : this.policyConfig){ + logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig); + assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig.getPolicyConfigMessage()); + assertEquals(PolicyType.XML,policyConfig.getType()); + assertNull(policyConfig.toJSON()); + assertNull(policyConfig.toProperties()); + assertNotNull(policyConfig.toXML()); + assertNull(policyConfig.toOther()); + } + } + + //@Test + @SuppressWarnings("deprecation") + public void testGetConfigStringStringValidProperties() { + onapComponentName = "Properties"; + configName = "PropConfig" ; + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + for(PolicyConfig policyConfig : this.policyConfig){ + logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig); + assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig.getPolicyConfigMessage()); + assertEquals(PolicyType.PROPERTIES,policyConfig.getType()); + assertNull(policyConfig.toJSON()); + assertNotNull(policyConfig.toProperties()); + assertNull(policyConfig.toXML()); + assertNull(policyConfig.toOther()); + } + } + + //@Test + @SuppressWarnings("deprecation") + public void testGetConfigStringStringValidOther() { + onapComponentName = "Other"; + configName = "OtherConfig" ; + try { + policyConfig = policyEngine.getConfig(onapComponentName, configName); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + for(PolicyConfig policyConfig : this.policyConfig){ + logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig); + assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig.getPolicyConfigMessage()); + assertEquals(PolicyType.OTHER,policyConfig.getType()); + assertNull(policyConfig.toJSON()); + assertNull(policyConfig.toProperties()); + assertNull(policyConfig.toXML()); + assertNotNull(policyConfig.toOther()); + } + } + +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigStringTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigStringTest.java new file mode 100644 index 000000000..f87a59c09 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/GetConfigStringTest.java @@ -0,0 +1,170 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import java.util.Collection; + +import org.junit.Before; +import org.onap.policy.api.PolicyConfig; +import org.onap.policy.api.PolicyConfigException; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +import junit.framework.TestCase; + +public class GetConfigStringTest extends TestCase{ + + private PolicyEngine policyEngine = null; + private String onapComponentName = null; + private Collection policyConfig = null; + private static final Logger logger = FlexLogger.getLogger(GetConfigStringTest.class); + @Before + public void setUp() { + try { + policyEngine = new PolicyEngine("Test/config_pass.properties"); + } catch (PolicyEngineException e) { + logger.error(e.getMessage()); + fail("PolicyEngine Instantiation Error" + e); + } + logger.info("Loaded.. PolicyEngine"); + } + + //@Test + @SuppressWarnings("deprecation") + public void testGetConfigStringFail() { + onapComponentName = null; + try { + policyConfig = policyEngine.getConfig(onapComponentName); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + /*@Test + public void testGetConfigStringNotvalid() { + onapComponentName = "fail"; + try { + policyConfig = policyEngine.getConfig(onapComponentName); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + for(PolicyConfig policyConfig : this.policyConfig){ + logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig); + assertEquals(PolicyConfigStatus.CONFIG_NOT_FOUND,policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig.getPolicyConfigMessage()); + assertNull(policyConfig.getType()); + assertNull(policyConfig.toJSON()); + assertNull(policyConfig.toProperties()); + assertNull(policyConfig.toXML()); + assertNull(policyConfig.toOther()); + } + } + */ + + /*@Test + public void testGetConfigStringValidJSON() { + onapComponentName = "JSON"; + try { + policyConfig = policyEngine.getConfig(onapComponentName); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + for(PolicyConfig policyConfig : this.policyConfig){ + logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig); + assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig.getPolicyConfigMessage()); + assertEquals(PolicyType.JSON,policyConfig.getType()); + assertNotNull(policyConfig.toJSON()); + assertNull(policyConfig.toProperties()); + assertNull(policyConfig.toXML()); + assertNull(policyConfig.toOther()); + } + } + */ + /*@Test + public void testGetConfigStringValidXML() { + onapComponentName = "XML"; + try { + policyConfig = policyEngine.getConfig(onapComponentName); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + for(PolicyConfig policyConfig : this.policyConfig){ + logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig); + assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig.getPolicyConfigMessage()); + assertEquals(PolicyType.XML,policyConfig.getType()); + assertNull(policyConfig.toJSON()); + assertNull(policyConfig.toProperties()); + assertNotNull(policyConfig.toXML()); + assertNull(policyConfig.toOther()); + } + } + */ + /*@Test + public void testGetConfigStringValidProperties() { + onapComponentName = "Properties"; + try { + policyConfig = policyEngine.getConfig(onapComponentName); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + for(PolicyConfig policyConfig : this.policyConfig){ + logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig); + assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig.getPolicyConfigMessage()); + assertEquals(PolicyType.PROPERTIES,policyConfig.getType()); + assertNull(policyConfig.toJSON()); + assertNotNull(policyConfig.toProperties()); + assertNull(policyConfig.toXML()); + assertNull(policyConfig.toOther()); + } + } + */ + /*@Test + public void testGetConfigStringValidOther() { + onapComponentName = "Other"; + try { + policyConfig = policyEngine.getConfig(onapComponentName); + } catch (PolicyConfigException e) { + logger.warn(e.getMessage()); + } + for(PolicyConfig policyConfig : this.policyConfig){ + logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig); + assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); + assertNotNull(policyConfig.getPolicyConfigMessage()); + assertEquals(PolicyType.OTHER,policyConfig.getType()); + assertNull(policyConfig.toJSON()); + assertNull(policyConfig.toProperties()); + assertNull(policyConfig.toXML()); + assertNotNull(policyConfig.toOther()); + } + } + */ +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/ImportParametersTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ImportParametersTest.java new file mode 100644 index 000000000..be3e9c39b --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/ImportParametersTest.java @@ -0,0 +1,403 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.UUID; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.api.ImportParameters; + +/** + * The class ImportParametersTest contains tests for the class {@link ImportParameters}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class ImportParametersTest { + /** + * Run the String getDescription() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetDescription_1() + throws Exception { + ImportParameters fixture = new ImportParameters(); + fixture.setFilePath(""); + fixture.setVersion(""); + fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); + fixture.setRequestID(UUID.randomUUID()); + fixture.setDescription(""); + fixture.setServiceName(""); + + String result = fixture.getDescription(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getFilePath() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetFilePath_1() + throws Exception { + ImportParameters fixture = new ImportParameters(); + fixture.setFilePath(""); + fixture.setVersion(""); + fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); + fixture.setRequestID(UUID.randomUUID()); + fixture.setDescription(""); + fixture.setServiceName(""); + + String result = fixture.getFilePath(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the UUID getRequestID() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetRequestID_1() + throws Exception { + ImportParameters fixture = new ImportParameters(); + fixture.setFilePath(""); + fixture.setVersion(""); + fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); + fixture.setRequestID(UUID.fromString("731dca0a-fe99-456c-8ad2-87cff8437b2f")); + fixture.setDescription(""); + fixture.setServiceName(""); + + UUID result = fixture.getRequestID(); + + // add additional test code here + assertNotNull(result); + assertEquals("731dca0a-fe99-456c-8ad2-87cff8437b2f", result.toString()); + assertEquals(4, result.version()); + assertEquals(2, result.variant()); + assertEquals(-8443537024073106641L, result.getLeastSignificantBits()); + assertEquals(8295008237256263020L, result.getMostSignificantBits()); + } + + /** + * Run the String getServiceName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetServiceName_1() + throws Exception { + ImportParameters fixture = new ImportParameters(); + fixture.setFilePath(""); + fixture.setVersion(""); + fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); + fixture.setRequestID(UUID.randomUUID()); + fixture.setDescription(""); + fixture.setServiceName(""); + + String result = fixture.getServiceName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the ImportParameters.IMPORT_TYPE getServiceType() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetServiceType_1() + throws Exception { + ImportParameters fixture = new ImportParameters(); + fixture.setFilePath(""); + fixture.setVersion(""); + fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); + fixture.setRequestID(UUID.randomUUID()); + fixture.setDescription(""); + fixture.setServiceName(""); + + ImportParameters.IMPORT_TYPE result = fixture.getServiceType(); + + // add additional test code here + assertNotNull(result); + assertEquals("MICROSERVICE", result.name()); + assertEquals("MICROSERVICE", result.toString()); + assertEquals(0, result.ordinal()); + } + + /** + * Run the String getVersion() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetVersion_1() + throws Exception { + ImportParameters fixture = new ImportParameters(); + fixture.setFilePath(""); + fixture.setVersion(""); + fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); + fixture.setRequestID(UUID.randomUUID()); + fixture.setDescription(""); + fixture.setServiceName(""); + + String result = fixture.getVersion(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the void setDescription(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetDescription_1() + throws Exception { + ImportParameters fixture = new ImportParameters(); + fixture.setFilePath(""); + fixture.setVersion(""); + fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); + fixture.setRequestID(UUID.randomUUID()); + fixture.setDescription(""); + fixture.setServiceName(""); + String description = ""; + + fixture.setDescription(description); + + // add additional test code here + } + + /** + * Run the void setFilePath(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetFilePath_1() + throws Exception { + ImportParameters fixture = new ImportParameters(); + fixture.setFilePath(""); + fixture.setVersion(""); + fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); + fixture.setRequestID(UUID.randomUUID()); + fixture.setDescription(""); + fixture.setServiceName(""); + String filePath = ""; + + fixture.setFilePath(filePath); + + // add additional test code here + } + + /** + * Run the void setImportParameters(String,String,UUID,String,IMPORT_TYPE,String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetImportParameters_1() + throws Exception { + ImportParameters fixture = new ImportParameters(); + fixture.setFilePath(""); + fixture.setVersion(""); + fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); + fixture.setRequestID(UUID.randomUUID()); + fixture.setDescription(""); + fixture.setServiceName(""); + String serviceName = ""; + String description = ""; + UUID requestID = UUID.randomUUID(); + String filePath = ""; + ImportParameters.IMPORT_TYPE importType = ImportParameters.IMPORT_TYPE.MICROSERVICE; + String version = ""; + + fixture.setImportParameters(serviceName, description, requestID, filePath, importType, version); + + // add additional test code here + } + + /** + * Run the void setRequestID(UUID) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetRequestID_1() + throws Exception { + ImportParameters fixture = new ImportParameters(); + fixture.setFilePath(""); + fixture.setVersion(""); + fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); + fixture.setRequestID(UUID.randomUUID()); + fixture.setDescription(""); + fixture.setServiceName(""); + UUID requestID = UUID.randomUUID(); + + fixture.setRequestID(requestID); + + // add additional test code here + } + + /** + * Run the void setServiceName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetServiceName_1() + throws Exception { + ImportParameters fixture = new ImportParameters(); + fixture.setFilePath(""); + fixture.setVersion(""); + fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); + fixture.setRequestID(UUID.randomUUID()); + fixture.setDescription(""); + fixture.setServiceName(""); + String serviceName = ""; + + fixture.setServiceName(serviceName); + + // add additional test code here + } + + /** + * Run the void setServiceType(IMPORT_TYPE) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetServiceType_1() + throws Exception { + ImportParameters fixture = new ImportParameters(); + fixture.setFilePath(""); + fixture.setVersion(""); + fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); + fixture.setRequestID(UUID.randomUUID()); + fixture.setDescription(""); + fixture.setServiceName(""); + ImportParameters.IMPORT_TYPE enumImportType = ImportParameters.IMPORT_TYPE.MICROSERVICE; + + fixture.setServiceType(enumImportType); + + // add additional test code here + } + + /** + * Run the void setVersion(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetVersion_1() + throws Exception { + ImportParameters fixture = new ImportParameters(); + fixture.setFilePath(""); + fixture.setVersion(""); + fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); + fixture.setRequestID(UUID.randomUUID()); + fixture.setDescription(""); + fixture.setServiceName(""); + String version = ""; + + fixture.setVersion(version); + + // add additional test code here + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(ImportParametersTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/LoadedPolicyTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/LoadedPolicyTest.java new file mode 100644 index 000000000..1cc9de8df --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/LoadedPolicyTest.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.After; +import org.junit.Before; +import org.onap.policy.api.LoadedPolicy; + +/** + * The class LoadedPolicyTest contains tests for the class {@link LoadedPolicy}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class LoadedPolicyTest { + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(LoadedPolicyTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/NotificationHandlerTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/NotificationHandlerTest.java new file mode 100644 index 000000000..4b996ce35 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/NotificationHandlerTest.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.After; +import org.junit.Before; +import org.onap.policy.api.NotificationHandler; + +/** + * The class NotificationHandlerTest contains tests for the class {@link NotificationHandler}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class NotificationHandlerTest { + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(NotificationHandlerTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/NotificationSchemeTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/NotificationSchemeTest.java new file mode 100644 index 000000000..3274cf3ac --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/NotificationSchemeTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.*; +import org.onap.policy.api.NotificationScheme; + +import static org.junit.Assert.*; + +/** + * The class NotificationSchemeTest contains tests for the class {@link NotificationScheme}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class NotificationSchemeTest { + /** + * Run the String toString() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testToString_1() + throws Exception { + NotificationScheme fixture = NotificationScheme.AUTO_ALL_NOTIFICATIONS; + + String result = fixture.toString(); + + // add additional test code here + assertEquals("auto_all_notifications", result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(NotificationSchemeTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/NotificationTypeTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/NotificationTypeTest.java new file mode 100644 index 000000000..53ef086e2 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/NotificationTypeTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.*; +import org.onap.policy.api.NotificationType; + +import static org.junit.Assert.*; + +/** + * The class NotificationTypeTest contains tests for the class {@link NotificationType}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class NotificationTypeTest { + /** + * Run the String toString() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testToString_1() + throws Exception { + NotificationType fixture = NotificationType.BOTH; + + String result = fixture.toString(); + + // add additional test code here + assertEquals("both", result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(NotificationTypeTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PDPNotificationTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PDPNotificationTest.java new file mode 100644 index 000000000..50d0aa324 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PDPNotificationTest.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.After; +import org.junit.Before; +import org.onap.policy.api.PDPNotification; + +/** + * The class PDPNotificationTest contains tests for the class {@link PDPNotification}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class PDPNotificationTest { + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PDPNotificationTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyChangeResponseTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyChangeResponseTest.java new file mode 100644 index 000000000..e8fd6346a --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyChangeResponseTest.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.After; +import org.junit.Before; +import org.onap.policy.api.PolicyChangeResponse; + +/** + * The class PolicyChangeResponseTest contains tests for the class {@link PolicyChangeResponse}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class PolicyChangeResponseTest { + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PolicyChangeResponseTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyClassTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyClassTest.java new file mode 100644 index 000000000..24eafc1ad --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyClassTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.*; +import org.onap.policy.api.PolicyClass; + +import static org.junit.Assert.*; + +/** + * The class PolicyClassTest contains tests for the class {@link PolicyClass}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class PolicyClassTest { + /** + * Run the String toString() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testToString_1() + throws Exception { + PolicyClass fixture = PolicyClass.Action; + + String result = fixture.toString(); + + // add additional test code here + assertEquals("Action", result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PolicyClassTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigExceptionTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigExceptionTest.java new file mode 100644 index 000000000..60b11b5c4 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigExceptionTest.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.*; +import org.onap.policy.api.PolicyConfigException; + +import static org.junit.Assert.*; + +/** + * The class PolicyConfigExceptionTest contains tests for the class {@link PolicyConfigException}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class PolicyConfigExceptionTest { + /** + * Run the PolicyConfigException() constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPolicyConfigException_1() + throws Exception { + + PolicyConfigException result = new PolicyConfigException(); + + // add additional test code here + assertNotNull(result); + assertEquals(null, result.getCause()); + assertEquals("org.onap.policy.api.PolicyConfigException", result.toString()); + assertEquals(null, result.getLocalizedMessage()); + assertEquals(null, result.getMessage()); + } + + /** + * Run the PolicyConfigException(String) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPolicyConfigException_2() + throws Exception { + String message = ""; + + PolicyConfigException result = new PolicyConfigException(message); + + // add additional test code here + assertNotNull(result); + assertEquals(null, result.getCause()); + assertEquals("org.onap.policy.api.PolicyConfigException: ", result.toString()); + assertEquals("", result.getLocalizedMessage()); + assertEquals("", result.getMessage()); + } + + /** + * Run the PolicyConfigException(Throwable) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPolicyConfigException_3() + throws Exception { + Throwable cause = new Throwable(); + + PolicyConfigException result = new PolicyConfigException(cause); + + // add additional test code here + assertNotNull(result); + assertEquals("org.onap.policy.api.PolicyConfigException: java.lang.Throwable", result.toString()); + assertEquals("java.lang.Throwable", result.getLocalizedMessage()); + assertEquals("java.lang.Throwable", result.getMessage()); + } + + /** + * Run the PolicyConfigException(String,Throwable) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPolicyConfigException_4() + throws Exception { + String message = ""; + Throwable cause = new Throwable(); + + PolicyConfigException result = new PolicyConfigException(message, cause); + + // add additional test code here + assertNotNull(result); + assertEquals("org.onap.policy.api.PolicyConfigException: ", result.toString()); + assertEquals("", result.getLocalizedMessage()); + assertEquals("", result.getMessage()); + } + + /** + * Run the PolicyConfigException(String,Throwable,boolean,boolean) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPolicyConfigException_5() + throws Exception { + String message = ""; + Throwable cause = new Throwable(); + boolean enableSuppression = true; + boolean writableStackTrace = true; + + PolicyConfigException result = new PolicyConfigException(message, cause, enableSuppression, writableStackTrace); + + // add additional test code here + assertNotNull(result); + assertEquals("org.onap.policy.api.PolicyConfigException: ", result.toString()); + assertEquals("", result.getLocalizedMessage()); + assertEquals("", result.getMessage()); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PolicyConfigExceptionTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigStatusTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigStatusTest.java new file mode 100644 index 000000000..7a93f0505 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigStatusTest.java @@ -0,0 +1,133 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.*; +import org.onap.policy.api.PolicyConfigStatus; + +import static org.junit.Assert.*; + +/** + * The class PolicyConfigStatusTest contains tests for the class {@link PolicyConfigStatus}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class PolicyConfigStatusTest { + /** + * Run the PolicyConfigStatus getStatus(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetStatus_1() + throws Exception { + String configStatus = ""; + + PolicyConfigStatus result = PolicyConfigStatus.getStatus(configStatus); + + // add additional test code here + assertNotNull(result); + assertEquals("not_found", result.toString()); + assertEquals("CONFIG_NOT_FOUND", result.name()); + assertEquals(1, result.ordinal()); + } + + /** + * Run the PolicyConfigStatus getStatus(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetStatus_2() + throws Exception { + String configStatus = ""; + + PolicyConfigStatus result = PolicyConfigStatus.getStatus(configStatus); + + // add additional test code here + assertNotNull(result); + assertEquals("not_found", result.toString()); + assertEquals("CONFIG_NOT_FOUND", result.name()); + assertEquals(1, result.ordinal()); + } + + /** + * Run the String toString() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testToString_1() + throws Exception { + PolicyConfigStatus fixture = PolicyConfigStatus.CONFIG_NOT_FOUND; + + String result = fixture.toString(); + + // add additional test code here + assertEquals("not_found", result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PolicyConfigStatusTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigTest.java new file mode 100644 index 000000000..0aa4fbbfa --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigTest.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.After; +import org.junit.Before; +import org.onap.policy.api.PolicyConfig; + +/** + * The class PolicyConfigTest contains tests for the class {@link PolicyConfig}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class PolicyConfigTest { + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PolicyConfigTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigTypeTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigTypeTest.java new file mode 100644 index 000000000..e5e0b5494 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigTypeTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.*; +import org.onap.policy.api.PolicyConfigType; + +import static org.junit.Assert.*; + +/** + * The class PolicyConfigTypeTest contains tests for the class {@link PolicyConfigType}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class PolicyConfigTypeTest { + /** + * Run the String toString() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testToString_1() + throws Exception { + PolicyConfigType fixture = PolicyConfigType.BRMS_PARAM; + + String result = fixture.toString(); + + // add additional test code here + assertEquals("BRMS_Param", result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PolicyConfigTypeTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyDecisionExceptionTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyDecisionExceptionTest.java new file mode 100644 index 000000000..f0ee88151 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyDecisionExceptionTest.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.*; +import org.onap.policy.api.PolicyDecisionException; + +import static org.junit.Assert.*; + +/** + * The class PolicyDecisionExceptionTest contains tests for the class {@link PolicyDecisionException}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class PolicyDecisionExceptionTest { + /** + * Run the PolicyDecisionException() constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPolicyDecisionException_1() + throws Exception { + + PolicyDecisionException result = new PolicyDecisionException(); + + // add additional test code here + assertNotNull(result); + assertEquals(null, result.getCause()); + assertEquals("org.onap.policy.api.PolicyDecisionException", result.toString()); + assertEquals(null, result.getLocalizedMessage()); + assertEquals(null, result.getMessage()); + } + + /** + * Run the PolicyDecisionException(String) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPolicyDecisionException_2() + throws Exception { + String message = ""; + + PolicyDecisionException result = new PolicyDecisionException(message); + + // add additional test code here + assertNotNull(result); + assertEquals(null, result.getCause()); + assertEquals("org.onap.policy.api.PolicyDecisionException: ", result.toString()); + assertEquals("", result.getLocalizedMessage()); + assertEquals("", result.getMessage()); + } + + /** + * Run the PolicyDecisionException(Throwable) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPolicyDecisionException_3() + throws Exception { + Throwable cause = new Throwable(); + + PolicyDecisionException result = new PolicyDecisionException(cause); + + // add additional test code here + assertNotNull(result); + assertEquals("org.onap.policy.api.PolicyDecisionException: java.lang.Throwable", result.toString()); + assertEquals("java.lang.Throwable", result.getLocalizedMessage()); + assertEquals("java.lang.Throwable", result.getMessage()); + } + + /** + * Run the PolicyDecisionException(String,Throwable) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPolicyDecisionException_4() + throws Exception { + String message = ""; + Throwable cause = new Throwable(); + + PolicyDecisionException result = new PolicyDecisionException(message, cause); + + // add additional test code here + assertNotNull(result); + assertEquals("org.onap.policy.api.PolicyDecisionException: ", result.toString()); + assertEquals("", result.getLocalizedMessage()); + assertEquals("", result.getMessage()); + } + + /** + * Run the PolicyDecisionException(String,Throwable,boolean,boolean) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPolicyDecisionException_5() + throws Exception { + String message = ""; + Throwable cause = new Throwable(); + boolean enableSuppression = true; + boolean writableStackTrace = true; + + PolicyDecisionException result = new PolicyDecisionException(message, cause, enableSuppression, writableStackTrace); + + // add additional test code here + assertNotNull(result); + assertEquals("org.onap.policy.api.PolicyDecisionException: ", result.toString()); + assertEquals("", result.getLocalizedMessage()); + assertEquals("", result.getMessage()); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PolicyDecisionExceptionTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyDecisionTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyDecisionTest.java new file mode 100644 index 000000000..4d9523859 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyDecisionTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.*; +import org.onap.policy.api.PolicyDecision; + +import static org.junit.Assert.*; + +/** + * The class PolicyDecisionTest contains tests for the class {@link PolicyDecision}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class PolicyDecisionTest { + /** + * Run the String toString() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testToString_1() + throws Exception { + PolicyDecision fixture = PolicyDecision.DENY; + + String result = fixture.toString(); + + // add additional test code here + assertEquals("deny", result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PolicyDecisionTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineExceptionTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineExceptionTest.java new file mode 100644 index 000000000..58c45b97c --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineExceptionTest.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.*; +import org.onap.policy.api.PolicyEngineException; + +import static org.junit.Assert.*; + +/** + * The class PolicyEngineExceptionTest contains tests for the class {@link PolicyEngineException}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class PolicyEngineExceptionTest { + /** + * Run the PolicyEngineException() constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testPolicyEngineException_1() + throws Exception { + + PolicyEngineException result = new PolicyEngineException(); + + // add additional test code here + assertNotNull(result); + assertEquals(null, result.getCause()); + assertEquals("org.onap.policy.api.PolicyEngineException", result.toString()); + assertEquals(null, result.getLocalizedMessage()); + assertEquals(null, result.getMessage()); + } + + /** + * Run the PolicyEngineException(String) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testPolicyEngineException_2() + throws Exception { + String message = ""; + + PolicyEngineException result = new PolicyEngineException(message); + + // add additional test code here + assertNotNull(result); + assertEquals(null, result.getCause()); + assertEquals("org.onap.policy.api.PolicyEngineException: ", result.toString()); + assertEquals("", result.getLocalizedMessage()); + assertEquals("", result.getMessage()); + } + + /** + * Run the PolicyEngineException(Throwable) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testPolicyEngineException_3() + throws Exception { + Throwable cause = new Throwable(); + + PolicyEngineException result = new PolicyEngineException(cause); + + // add additional test code here + assertNotNull(result); + assertEquals("org.onap.policy.api.PolicyEngineException: java.lang.Throwable", result.toString()); + assertEquals("java.lang.Throwable", result.getLocalizedMessage()); + assertEquals("java.lang.Throwable", result.getMessage()); + } + + /** + * Run the PolicyEngineException(String,Throwable) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testPolicyEngineException_4() + throws Exception { + String message = ""; + Throwable cause = new Throwable(); + + PolicyEngineException result = new PolicyEngineException(message, cause); + + // add additional test code here + assertNotNull(result); + assertEquals("org.onap.policy.api.PolicyEngineException: ", result.toString()); + assertEquals("", result.getLocalizedMessage()); + assertEquals("", result.getMessage()); + } + + /** + * Run the PolicyEngineException(String,Throwable,boolean,boolean) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testPolicyEngineException_5() + throws Exception { + String message = ""; + Throwable cause = new Throwable(); + boolean enableSuppression = true; + boolean writableStackTrace = true; + + PolicyEngineException result = new PolicyEngineException(message, cause, enableSuppression, writableStackTrace); + + // add additional test code here + assertNotNull(result); + assertEquals("org.onap.policy.api.PolicyEngineException: ", result.toString()); + assertEquals("", result.getLocalizedMessage()); + assertEquals("", result.getMessage()); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PolicyEngineExceptionTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineInterfaceTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineInterfaceTest.java new file mode 100644 index 000000000..be9e0e7e8 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineInterfaceTest.java @@ -0,0 +1,670 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import java.io.StringReader; +import java.net.HttpURLConnection; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonReader; + +import org.mockito.Mockito; +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.ConfigRequestParameters; +import org.onap.policy.api.DecisionRequestParameters; +import org.onap.policy.api.DecisionResponse; +import org.onap.policy.api.DeletePolicyCondition; +import org.onap.policy.api.DeletePolicyParameters; +import org.onap.policy.api.EventRequestParameters; +import org.onap.policy.api.ImportParameters; +import org.onap.policy.api.ImportParameters.IMPORT_TYPE; +import org.onap.policy.api.NotificationHandler; +import org.onap.policy.api.NotificationScheme; +import org.onap.policy.api.PDPNotification; +import org.onap.policy.api.PolicyChangeResponse; +import org.onap.policy.api.PolicyClass; +import org.onap.policy.api.PolicyConfig; +import org.onap.policy.api.PolicyConfigException; +import org.onap.policy.api.PolicyDecisionException; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.api.PolicyEventException; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.PolicyResponse; +import org.onap.policy.api.PushPolicyParameters; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.std.StdPDPNotification; +import org.onap.policy.std.StdPolicyChangeResponse; +import org.onap.policy.std.StdPolicyResponse; + +import junit.framework.TestCase; + +/** + * The class PolicyEngineInterfaceTest contains tests for the + * class {@link PolicyEngine} + * + * @pattern JUnit Test Case + * + * @generatedBy CodePro at 5/27/16 10:33 AM + * + * + * @version $Revision$ + */ +public class PolicyEngineInterfaceTest extends TestCase { + + private static final Logger logger = FlexLogger.getLogger(PolicyEngineInterfaceTest.class); + + private PolicyEngine policyEngine = null; + private PolicyEngine mockPolicyEngine = null; + private Collection policyConfig = null; + private UUID requestID = UUID.randomUUID(); + + + PolicyChangeResponse result = null; + StdPolicyChangeResponse response = new StdPolicyChangeResponse(); + + + /** + * Construct new test instance + * + * @param name the test name + */ + public PolicyEngineInterfaceTest(String name) { + super(name); + } + + /** + * Perform pre-test initialization + * + * @throws Exception + * + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + try { + policyEngine = new PolicyEngine("Test/config_pass.properties"); + } catch (PolicyEngineException e) { + logger.error(e.getMessage()); + fail("PolicyEngine Instantiation Error" + e); + } + logger.info("Loaded.. PolicyEngine"); + + mockPolicyEngine = Mockito.mock(PolicyEngine.class); + HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); + Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + + } + + /** + * Perform post-test clean up + * + * @throws Exception + * + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + // Add additional tear down code here + } + + /** + * Run the Collection getConfigByPolicyName(String) method + * test + */ + @SuppressWarnings("deprecation") + public void testGetConfigByPolicyName() { + String policyName = null; + try{ + policyConfig = policyEngine.getConfigByPolicyName(policyName); + } catch (PolicyConfigException e){ + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + @SuppressWarnings("deprecation") + public void testGetConfigByPolicyName2() { + String policyName = null; + + try{ + policyConfig = policyEngine.getConfigByPolicyName(policyName, requestID); + } catch (PolicyConfigException e){ + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + /** + * Run the Collection getConfig(String) method test + */ + @SuppressWarnings("deprecation") + public void testGetConfig() { + String onapName = null; + + try{ + policyConfig = policyEngine.getConfig(onapName); + } catch (PolicyConfigException e){ + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + @SuppressWarnings("deprecation") + public void testGetConfig2() { + String onapName = null; + + try{ + policyConfig = policyEngine.getConfig(onapName,requestID); + } catch (PolicyConfigException e){ + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + + @SuppressWarnings("deprecation") + public void testGetConfig3() { + String onapName = null; + String configName = null; + + try{ + policyConfig = policyEngine.getConfig(onapName,configName,requestID); + } catch (PolicyConfigException e){ + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + @SuppressWarnings("deprecation") + public void testGetConfig4() { + String onapName = null; + String configName = null; + Map configAttributes = null; + + try{ + policyConfig = policyEngine.getConfig(onapName,configName,configAttributes); + } catch (PolicyConfigException e){ + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + @SuppressWarnings("deprecation") + public void testGetConfig5() { + String onapName = null; + String configName = null; + Map configAttributes = null; + + try{ + policyConfig = policyEngine.getConfig(onapName,configName,configAttributes,requestID); + } catch (PolicyConfigException e){ + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + public void testGetConfig6() { + ConfigRequestParameters parameters = new ConfigRequestParameters(); + + try{ + policyConfig = policyEngine.getConfig(parameters); + } catch (PolicyConfigException e){ + logger.warn(e.getMessage()); + } + assertNull(policyConfig); + } + + + /** + * Run the Collection sendEvent(Map) method + * test + */ + @SuppressWarnings("deprecation") + public void testSendEvent() + { + Collection result = null; + Collection response = null; + Map eventAttributes = null; + + try { + Mockito.when(mockPolicyEngine.sendEvent(eventAttributes)).thenReturn(result); + result = mockPolicyEngine.sendEvent(eventAttributes); + } catch (PolicyEventException e) { + logger.error("Exception Occured"+e); + } + + + assertEquals(result,response); + + } + + @SuppressWarnings("deprecation") + public void testSendEvent2() + { + Collection result = null; + Collection response = null; + Map eventAttributes = null; + + try { + Mockito.when(mockPolicyEngine.sendEvent(eventAttributes,requestID)).thenReturn(result); + result = mockPolicyEngine.sendEvent(eventAttributes,requestID); + } catch (PolicyEventException e) { + logger.error("Exception Occured"+e); + } + + + assertEquals(result,response); + + } + + public void testSendEvent3() + { + Collection result = null; + Collection response = null; + EventRequestParameters parameters = new EventRequestParameters(); + + try { + Mockito.when(mockPolicyEngine.sendEvent(parameters)).thenReturn(result); + result = mockPolicyEngine.sendEvent(parameters); + } catch (PolicyEventException e) { + logger.error("Exception Occured"+e); + } + + assertEquals(result,response); + + } + + + + /** + * Run the PolicyDecision getDecision(String, Map) method + * test + */ + @SuppressWarnings("deprecation") + public void testGetDecision() + { + String onapComponentName = null; + Map decisionAttributes = null; + + DecisionResponse result = null; + + try { + Mockito.when(mockPolicyEngine.getDecision(onapComponentName,decisionAttributes)).thenReturn(null); + result = mockPolicyEngine.getDecision(onapComponentName,decisionAttributes); + } catch (PolicyDecisionException e) { + logger.error("Exception Occured"+e); + } + + assertEquals(result,null); + } + + @SuppressWarnings("deprecation") + public void testGetDecision2() + { + String onapComponentName = null; + Map decisionAttributes = null; + + DecisionResponse result = null; + + try { + Mockito.when(mockPolicyEngine.getDecision(onapComponentName,decisionAttributes,requestID)).thenReturn(null); + result = mockPolicyEngine.getDecision(onapComponentName,decisionAttributes); + } catch (PolicyDecisionException e) { + logger.error("Exception Occured"+e); + } + + assertEquals(result,null); + } + + public void testGetDecision3() + { + DecisionRequestParameters parameters = new DecisionRequestParameters(); + DecisionResponse result = null; + + try { + Mockito.when(mockPolicyEngine.getDecision(parameters)).thenReturn(null); + result = mockPolicyEngine.getDecision(parameters); + } catch (PolicyDecisionException e) { + logger.error("Exception Occured"+e); + } + + assertEquals(result,null); + } + + /** + * Run the void setNotification(NotificationScheme, NotificationHandler) + * method test + */ + public void testSetNotification() { + // add test code here + + NotificationScheme scheme = null; + NotificationHandler handler = null; + + Mockito.doNothing().when(mockPolicyEngine).setNotification(scheme, handler); + mockPolicyEngine.setNotification(scheme, handler); + //assertTrue(true); + } + + /** + * Run the void clearNotification() method test + */ + public void testClearNotification() { + // add test code here + + Mockito.doNothing().when(mockPolicyEngine).clearNotification(); + mockPolicyEngine.clearNotification(); + //assertTrue(true); + } + + /** + * Run the void setScheme(NotificationScheme) method test + */ + public void testSetScheme() { + NotificationScheme scheme = null; + + Mockito.doNothing().when(mockPolicyEngine).setScheme(scheme); + mockPolicyEngine.setScheme(scheme); + //assertTrue(true); + } + + /** + * Run the PDPNotification getNotification() method test + */ + public void testGetNotification() { + PDPNotification result = null; + StdPDPNotification response = null; + Mockito.when(mockPolicyEngine.getNotification()).thenReturn(response); + result = mockPolicyEngine.getNotification(); + + assertEquals(result,response); + } + + /** + * Run the String createConfigPolicy(String, String, String, String, + * Map, String, String, String, UUID) method test + */ + @SuppressWarnings("deprecation") + public void testCreateConfigPolicy() + { + String response = "success"; + String result = null; + try { + + Mockito.when(mockPolicyEngine.createConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null)).thenReturn(response); + result = mockPolicyEngine.createConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + /** + * Run the String updateConfigPolicy(String, String, String, String, + * Map, String, String, String, UUID) method test + */ + @SuppressWarnings("deprecation") + public void testUpdateConfigPolicy() + { + String response = "success"; + String result = null; + try { + + Mockito.when(mockPolicyEngine.updateConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null)).thenReturn(response); + result = mockPolicyEngine.updateConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + /** + * Run the String createConfigFirewallPolicy(String, JsonObject, String, + * UUID) method test + */ + @SuppressWarnings("deprecation") + public void testCreateConfigFirewallPolicy() { + String response = "success"; + String result = null; + String json = "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"rule1607\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"/v0/firewall/pan\",\"serviceGroups\":[{\"name\":\"1607Group\",\"description\":null,\"members\":[{\"type\":\"REFERENCE\",\"name\":\"SList\"},{\"type\":\"REFERENCE\",\"name\":\"Syslog\"}]},{\"name\":\"Syslog\",\"description\":\"NA\",\"type\":\"SERVICE\",\"transportProtocol\":\"udp\",\"appProtocol\":null,\"ports\":\"514\"},{\"name\":\"SList\",\"description\":\"Service List\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"8080\"}],\"addressGroups\":[{\"name\":\"1607Group\",\"description\":null,\"members\":[{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"},{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"}]},{\"name\":\"PL_CCE3\",\"description\":\"CCE Routers\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"1607Rule\",\"fromZones\":[\"Trusted\"],\"toZones\":[\"Untrusted\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"value\":\"PL_CCE3\"},{\"type\":\"REFERENCE\",\"value\":\"1607Group\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"value\":\"1607Group\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"1607Group\"}],\"action\":\"accept\",\"description\":\"Rule for 1607 templates\",\"enabled\":true,\"log\":true}]}"; + JsonObject jsonObj = buildJSON(json); + try { + + Mockito.when(mockPolicyEngine.createConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null)).thenReturn(response); + result = mockPolicyEngine.createConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + /** + * Run the String updateConfigFirewallPolicy(String, JsonObject, String, + * UUID) method test + */ + @SuppressWarnings("deprecation") + public void testUpdateConfigFirewallPolicy() { + String response = "success"; + String result = null; + String json = "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"rule1607\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"/v0/firewall/pan\",\"serviceGroups\":[{\"name\":\"1607Group\",\"description\":null,\"members\":[{\"type\":\"REFERENCE\",\"name\":\"SList\"},{\"type\":\"REFERENCE\",\"name\":\"Syslog\"}]},{\"name\":\"Syslog\",\"description\":\"NA\",\"type\":\"SERVICE\",\"transportProtocol\":\"udp\",\"appProtocol\":null,\"ports\":\"514\"},{\"name\":\"SList\",\"description\":\"Service List\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"8080\"}],\"addressGroups\":[{\"name\":\"1607Group\",\"description\":null,\"members\":[{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"},{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"}]},{\"name\":\"PL_CCE3\",\"description\":\"CCE Routers\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"1607Rule\",\"fromZones\":[\"Trusted\"],\"toZones\":[\"Untrusted\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"value\":\"PL_CCE3\"},{\"type\":\"REFERENCE\",\"value\":\"1607Group\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"value\":\"1607Group\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"1607Group\"}],\"action\":\"accept\",\"description\":\"Rule for 1607 templates\",\"enabled\":true,\"log\":true}]}"; + JsonObject jsonObj = buildJSON(json); + try { + + Mockito.when(mockPolicyEngine.updateConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null)).thenReturn(response); + result = mockPolicyEngine.updateConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + /** + * Run the PolicyChangeResponse createPolicy(PolicyParameters) method test + */ + public void testCreatePolicy() { + response.setResponseMessage("success"); + PolicyChangeResponse result = null; + PolicyParameters policyParameters = new PolicyParameters(); + + policyParameters.setPolicyClass(PolicyClass.Action); //required + policyParameters.setPolicyName("test.junitTest"); //required + policyParameters.setPolicyDescription("testing"); //optional + + //Set the Component Attributes... These are Optional + Map configAttributes = new HashMap(); + configAttributes.put("test", "testing"); + + Map> attributes = new HashMap>(); + attributes.put(AttributeType.MATCHING, configAttributes); + policyParameters.setAttributes(attributes); + + policyParameters.setActionPerformer("PEP"); + policyParameters.setActionAttribute("testing"); + policyParameters.setRequestID(UUID.randomUUID()); + + try { + + //stdPolicyEngine = Mockito.mock(StdPolicyEngine.class); + //Mockito.when(stdPolicyEngine.callPAP(newPAPPolicy, new String[] {"operation=create", "apiflag=api", "policyType=Action"}, null, "Action")).thenReturn(callPapResponse); + Mockito.when(mockPolicyEngine.createPolicy(policyParameters)).thenReturn(response); + result = mockPolicyEngine.createPolicy(policyParameters); + + } catch (Exception e) { + logger.warn(e.getMessage()); + logger.error("Exception Occured"+e); + } + assertEquals(result, response); + } + + /** + * Run the PolicyChangeResponse updatePolicy(PolicyParameters) method test + */ + public void testUpdatePolicy() { + response.setResponseMessage("success"); + PolicyChangeResponse result = null; + PolicyParameters policyParameters = new PolicyParameters(); + + policyParameters.setPolicyClass(PolicyClass.Action); //required + policyParameters.setPolicyName("test.junitTest"); //required + policyParameters.setPolicyDescription("testing"); //optional + + //Set the Component Attributes... These are Optional + Map configAttributes = new HashMap(); + configAttributes.put("test", "testing"); + + Map> attributes = new HashMap>(); + attributes.put(AttributeType.MATCHING, configAttributes); + policyParameters.setAttributes(attributes); + + policyParameters.setActionPerformer("PEP"); + policyParameters.setActionAttribute("testing"); + policyParameters.setRequestID(UUID.randomUUID()); + + try { + + Mockito.when(mockPolicyEngine.updatePolicy(policyParameters)).thenReturn(response); + result = mockPolicyEngine.updatePolicy(policyParameters); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + assertEquals(result, response); + } + + /** + * Run the String pushPolicy(String, String, String, String, UUID) method + * test + */ + @SuppressWarnings("deprecation") + public void testPushPolicy() { + String response = "Success"; + String result = null; + try { + + Mockito.when(mockPolicyEngine.pushPolicy("testing","test","Base","default",requestID)).thenReturn(response); + result = mockPolicyEngine.pushPolicy("testing","test","Base","default",requestID); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + + assertEquals(result, response); + } + + public void testPushPolicy2() { + PushPolicyParameters policyParameters = new PushPolicyParameters(); + PolicyChangeResponse result = null; + + //String policyScope = null; + policyParameters.setPolicyName("test.junitTest"); + policyParameters.setPolicyType("Action"); + policyParameters.setPdpGroup("Default"); + + try { + + Mockito.when(mockPolicyEngine.pushPolicy(policyParameters)).thenReturn(response); + result = mockPolicyEngine.pushPolicy(policyParameters); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + + assertEquals(result, response); + } + + /** + * Run the PolicyChangeResponse deletePolicy(DeletePolicyParameters) method + * test + */ + public void testDeletePolicy() { + DeletePolicyParameters policyParameters = new DeletePolicyParameters(); + PolicyChangeResponse result = null; + + //String policyScope = null; + policyParameters.setPolicyName("test.junitTest.1.xml"); + policyParameters.setDeleteCondition(DeletePolicyCondition.ALL); + policyParameters.setPolicyComponent("PAP"); + policyParameters.setPdpGroup("Default"); + + try { + + Mockito.when(mockPolicyEngine.deletePolicy(policyParameters)).thenReturn(response); + result = mockPolicyEngine.deletePolicy(policyParameters); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + + assertEquals(result, response); + } + + /** + * Run the PolicyChangeResponse policyEngineImport(ImportParameters) method + * test + */ + public void testPolicyEngineImport() { + ImportParameters importParameters = new ImportParameters(); + PolicyChangeResponse result = null; + + importParameters.setFilePath("C:\\Workspaces\\models\\TestingModel\\ControllerServiceSampleSdnlServiceInstance-v0.1.0-SNAPSHOT.zip"); + importParameters.setServiceName("ControllerServiceSampleSdnlServiceInstance"); + + importParameters.setRequestID(UUID.randomUUID()); + importParameters.setServiceType(IMPORT_TYPE.MICROSERVICE); + importParameters.setVersion("1607-2"); + + + try { + + Mockito.when(mockPolicyEngine.policyEngineImport(importParameters)).thenReturn(response); + result = mockPolicyEngine.policyEngineImport(importParameters); + + } catch (Exception e) { + logger.warn(e.getMessage()); + } + + assertEquals(result, response); + } + + private static JsonObject buildJSON(String jsonString) { + JsonObject json = null;; + if (jsonString != null) { + StringReader in = null; + + in = new StringReader(jsonString); + + JsonReader jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + } + + return json; + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineTest.java new file mode 100644 index 000000000..abfab075b --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEngineTest.java @@ -0,0 +1,170 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import org.junit.Test; +import org.onap.policy.api.NotificationScheme; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +public class PolicyEngineTest { + + private static final Logger logger = FlexLogger.getLogger(PolicyEngineTest.class); + private PolicyEngine policyEngine = null; + private String filePath = null; + + @Test + public void testPolicyEngineForFail() { + filePath = null; + try { + policyEngine = new PolicyEngine(filePath); + } catch (PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNull(policyEngine); + // Test even for this case. + filePath = "NotNull"; + try { + policyEngine = new PolicyEngine(filePath); + } catch (PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNull(policyEngine); + } + + @Test + public void testPolicyEngineforPropertyFileError() { + filePath = "Test/config_error.property"; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + } catch (PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNull(policyEngine); + } + + @Test + public void testPolicyEngineforPDPURLError() { + String filePath = "Test/config_fail.properties"; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + } catch (PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNull(policyEngine); + } + + @Test + public void testPolicyEngineForPass() { + String filePath = "Test/config_pass.properties"; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + } catch (PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNotNull(policyEngine); + } + + @Test + public void testPolicyEngineForUEBPass() { + String filePath = "Test/config_UEB_pass.properties"; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + } catch (PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNotNull(policyEngine); + } + + + @Test + public void testPolicyEngineForUEBBadType() { + String filePath = "Test/config_UEB_bad_type.properties"; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + } catch (PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNotNull(policyEngine); + } + + @Test + public void testPolicyEngineForUEBBadServerType() { + String filePath = "Test/config_UEB_badservers.properties"; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + } catch (PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNotNull(policyEngine); + } + + @Test + public void testPolicyEngineNotficationAutoUEB() { + String filePath = "Test/config_UEB_pass.properties"; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + policyEngine.setScheme(NotificationScheme.AUTO_ALL_NOTIFICATIONS); + } catch (PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNotNull(policyEngine); + } + + @Test + public void testPolicyEngineNotficationAuto() { + String filePath = "Test/config_pass.properties"; + isFileAvailable(filePath); + try { + policyEngine = new PolicyEngine(filePath); + policyEngine.setScheme(NotificationScheme.AUTO_ALL_NOTIFICATIONS); + //policyEngine.getNotification(); + } catch (PolicyEngineException e) { + logger.warn(e.getMessage()); + } + assertNotNull(policyEngine); + } + + public void isFileAvailable(String filePath) { + Path file = Paths.get(filePath); + if (Files.notExists(file)) { + logger.error("File Doesn't Exist "+ file.toString()); + fail("File: " +filePath + " Not found"); + } + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEventExceptionTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEventExceptionTest.java new file mode 100644 index 000000000..6f7573352 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyEventExceptionTest.java @@ -0,0 +1,183 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.*; +import org.onap.policy.api.PolicyEventException; + +import static org.junit.Assert.*; + +/** + * The class PolicyEventExceptionTest contains tests for the class {@link PolicyEventException}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class PolicyEventExceptionTest { + /** + * Run the PolicyEventException() constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPolicyEventException_1() + throws Exception { + + PolicyEventException result = new PolicyEventException(); + + // add additional test code here + assertNotNull(result); + assertEquals(null, result.getCause()); + assertEquals("org.onap.policy.api.PolicyEventException", result.toString()); + assertEquals(null, result.getLocalizedMessage()); + assertEquals(null, result.getMessage()); + } + + /** + * Run the PolicyEventException(String) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPolicyEventException_2() + throws Exception { + String message = ""; + + PolicyEventException result = new PolicyEventException(message); + + // add additional test code here + assertNotNull(result); + assertEquals(null, result.getCause()); + assertEquals("org.onap.policy.api.PolicyEventException: ", result.toString()); + assertEquals("", result.getLocalizedMessage()); + assertEquals("", result.getMessage()); + } + + /** + * Run the PolicyEventException(Throwable) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPolicyEventException_3() + throws Exception { + Throwable cause = new Throwable(); + + PolicyEventException result = new PolicyEventException(cause); + + // add additional test code here + assertNotNull(result); + assertEquals("org.onap.policy.api.PolicyEventException: java.lang.Throwable", result.toString()); + assertEquals("java.lang.Throwable", result.getLocalizedMessage()); + assertEquals("java.lang.Throwable", result.getMessage()); + } + + /** + * Run the PolicyEventException(String,Throwable) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPolicyEventException_4() + throws Exception { + String message = ""; + Throwable cause = new Throwable(); + + PolicyEventException result = new PolicyEventException(message, cause); + + // add additional test code here + assertNotNull(result); + assertEquals("org.onap.policy.api.PolicyEventException: ", result.toString()); + assertEquals("", result.getLocalizedMessage()); + assertEquals("", result.getMessage()); + } + + /** + * Run the PolicyEventException(String,Throwable,boolean,boolean) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPolicyEventException_5() + throws Exception { + String message = ""; + Throwable cause = new Throwable(); + boolean enableSuppression = true; + boolean writableStackTrace = true; + + PolicyEventException result = new PolicyEventException(message, cause, enableSuppression, writableStackTrace); + + // add additional test code here + assertNotNull(result); + assertEquals("org.onap.policy.api.PolicyEventException: ", result.toString()); + assertEquals("", result.getLocalizedMessage()); + assertEquals("", result.getMessage()); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PolicyEventExceptionTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyParametersTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyParametersTest.java new file mode 100644 index 000000000..ff192dcab --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyParametersTest.java @@ -0,0 +1,1409 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.Hashtable; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.api.AttributeType; +import org.onap.policy.api.PolicyClass; +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.PolicyType; + +/** + * The class PolicyParametersTest contains tests for the class {@link PolicyParameters}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class PolicyParametersTest { + /** + * Run the String getActionAttribute() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetActionAttribute_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + String result = fixture.getActionAttribute(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getActionPerformer() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetActionPerformer_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + String result = fixture.getActionPerformer(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the Map> getAttributes() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetAttributes_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + Map> result = fixture.getAttributes(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the String getConfigBody() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetConfigBody_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + String result = fixture.getConfigBody(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the PolicyType getConfigBodyType() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetConfigBodyType_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + PolicyType result = fixture.getConfigBodyType(); + + // add additional test code here + assertNotNull(result); + assertEquals("json", result.toString()); + assertEquals("JSON", result.name()); + assertEquals(1, result.ordinal()); + } + + /** + * Run the String getConfigName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetConfigName_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + String result = fixture.getConfigName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the List getDynamicRuleAlgorithmField1() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetDynamicRuleAlgorithmField1_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + List result = fixture.getDynamicRuleAlgorithmField1(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the List getDynamicRuleAlgorithmField2() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetDynamicRuleAlgorithmField2_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + List result = fixture.getDynamicRuleAlgorithmField2(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the List getDynamicRuleAlgorithmFunctions() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetDynamicRuleAlgorithmFunctions_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + List result = fixture.getDynamicRuleAlgorithmFunctions(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the List getDynamicRuleAlgorithmLabels() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetDynamicRuleAlgorithmLabels_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + List result = fixture.getDynamicRuleAlgorithmLabels(); + + // add additional test code here + assertNotNull(result); + assertEquals(0, result.size()); + } + + /** + * Run the String getOnapName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetOnapName_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + String result = fixture.getOnapName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the PolicyClass getPolicyClass() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetPolicyClass_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + PolicyClass result = fixture.getPolicyClass(); + + // add additional test code here + assertNotNull(result); + assertEquals("Action", result.toString()); + assertEquals("Action", result.name()); + assertEquals(1, result.ordinal()); + } + + /** + * Run the PolicyConfigType getPolicyConfigType() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetPolicyConfigType_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + PolicyConfigType result = (PolicyConfigType) fixture.getPolicyConfigType(); + + // add additional test code here + assertNotNull(result); + assertEquals("BRMS_Param", result.toString()); + assertEquals("BRMS_PARAM", result.name()); + assertEquals(5, result.ordinal()); + } + + /** + * Run the String getPolicyDescription() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetPolicyDescription_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + String result = fixture.getPolicyDescription(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetPolicyName_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getPriority() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetPriority_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + String result = fixture.getPriority(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the UUID getRequestID() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetRequestID_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.fromString("878d319c-2799-4684-b480-99f40e1042b2")); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + + UUID result = fixture.getRequestID(); + + // add additional test code here + assertNotNull(result); + assertEquals("878d319c-2799-4684-b480-99f40e1042b2", result.toString()); + assertEquals(4, result.version()); + assertEquals(2, result.variant()); + assertEquals(-5440179076376542542L, result.getLeastSignificantBits()); + assertEquals(-8679226360124062076L, result.getMostSignificantBits()); + } + + /** + * Run the void setActionAttribute(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetActionAttribute_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + String actionAttribute = ""; + + fixture.setActionAttribute(actionAttribute); + + // add additional test code here + } + + /** + * Run the void setActionPerformer(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetActionPerformer_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + String actionPerformer = ""; + + fixture.setActionPerformer(actionPerformer); + + // add additional test code here + } + + /** + * Run the void setAttributes(Map>) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetAttributes_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + Map> attributes = new Hashtable>(); + + fixture.setAttributes(attributes); + + // add additional test code here + } + + /** + * Run the void setConfigBody(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetConfigBody_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + String configBody = ""; + + fixture.setConfigBody(configBody); + + // add additional test code here + } + + /** + * Run the void setConfigBodyType(PolicyType) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetConfigBodyType_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + PolicyType configBodyType = PolicyType.JSON; + + fixture.setConfigBodyType(configBodyType); + + // add additional test code here + } + + /** + * Run the void setConfigFirewallPolicyParameters(String,String,UUID) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetConfigFirewallPolicyParameters_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + String policyName = ""; + String firewallJson = ""; + UUID requestID = UUID.randomUUID(); + + fixture.setConfigFirewallPolicyParameters(policyName, firewallJson, requestID); + + // add additional test code here + } + + /** + * Run the void setConfigName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetConfigName_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + String configName = ""; + + fixture.setConfigName(configName); + + // add additional test code here + } + + /** + * Run the void setConfigPolicyParameters(PolicyConfigType,String,String,String,String,Map>,PolicyType,String,UUID) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetConfigPolicyParameters_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + PolicyConfigType policyConfigType = PolicyConfigType.BRMS_PARAM; + String policyName = ""; + String policyDescription = ""; + String onapName = ""; + String configName = ""; + Map> attributes = new Hashtable>(); + PolicyType configBodyType = PolicyType.JSON; + String configBody = ""; + UUID requestID = UUID.randomUUID(); + + fixture.setConfigPolicyParameters(policyConfigType, policyName, policyDescription, onapName, configName, attributes, configBodyType, configBody, requestID); + + // add additional test code here + } + + /** + * Run the void setDynamicRuleAlgorithmField1(List) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetDynamicRuleAlgorithmField1_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + List dynamicRuleAlgorithmField1 = new LinkedList(); + + fixture.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); + + // add additional test code here + } + + /** + * Run the void setDynamicRuleAlgorithmField2(List) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetDynamicRuleAlgorithmField2_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + List dynamicRuleAlgorithmField2 = new LinkedList(); + + fixture.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); + + // add additional test code here + } + + /** + * Run the void setDynamicRuleAlgorithmFunctions(List) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetDynamicRuleAlgorithmFunctions_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + List dynamicRuleAlgorithmFunctions = new LinkedList(); + + fixture.setDynamicRuleAlgorithmFunctions(dynamicRuleAlgorithmFunctions); + + // add additional test code here + } + + /** + * Run the void setDynamicRuleAlgorithmLabels(List) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetDynamicRuleAlgorithmLabels_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + List dynamicRuleAlgorithmLabels = new LinkedList(); + + fixture.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); + + // add additional test code here + } + + /** + * Run the void setOnapName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetOnapName_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + String onapName = ""; + + fixture.setOnapName(onapName); + + // add additional test code here + } + + /** + * Run the void setPolicyClass(PolicyClass) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetPolicyClass_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + PolicyClass policyClass = PolicyClass.Action; + + fixture.setPolicyClass(policyClass); + + // add additional test code here + } + + /** + * Run the void setPolicyConfigType(PolicyConfigType) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetPolicyConfigType_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + PolicyConfigType policyConfigType = PolicyConfigType.BRMS_PARAM; + + fixture.setPolicyConfigType(policyConfigType); + + // add additional test code here + } + + /** + * Run the void setPolicyDescription(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetPolicyDescription_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + String policyDescription = ""; + + fixture.setPolicyDescription(policyDescription); + + // add additional test code here + } + + /** + * Run the void setPolicyName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetPolicyName_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + String policyName = ""; + + fixture.setPolicyName(policyName); + + // add additional test code here + } + + /** + * Run the void setPriority(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetPriority_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + String priority = ""; + + fixture.setPriority(priority); + + // add additional test code here + } + + /** + * Run the void setRequestID(UUID) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testSetRequestID_1() + throws Exception { + PolicyParameters fixture = new PolicyParameters(); + fixture.setRequestID(UUID.randomUUID()); + fixture.setActionAttribute(""); + fixture.setAttributes(new Hashtable>()); + fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); + fixture.setPolicyDescription(""); + + fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); + fixture.setDynamicRuleAlgorithmField2(new LinkedList()); + fixture.setPolicyName(""); + fixture.setConfigName(""); + fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); + fixture.setPolicyClass(PolicyClass.Action); + fixture.setOnapName(""); + fixture.setConfigBodyType(PolicyType.JSON); + fixture.setDynamicRuleAlgorithmField1(new LinkedList()); + fixture.setPriority(""); + fixture.setActionPerformer(""); + fixture.setConfigBody(""); + UUID requestID = UUID.randomUUID(); + + fixture.setRequestID(requestID); + + // add additional test code here + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PolicyParametersTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyResponseStatusTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyResponseStatusTest.java new file mode 100644 index 000000000..294f0929d --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyResponseStatusTest.java @@ -0,0 +1,154 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.*; +import org.onap.policy.api.PolicyResponseStatus; + +import static org.junit.Assert.*; + +/** + * The class PolicyResponseStatusTest contains tests for the class {@link PolicyResponseStatus}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class PolicyResponseStatusTest { + /** + * Run the PolicyResponseStatus getStatus(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetStatus_1() + throws Exception { + String responseStatus = ""; + + PolicyResponseStatus result = PolicyResponseStatus.getStatus(responseStatus); + + // add additional test code here + assertNotNull(result); + assertEquals("no_action", result.toString()); + assertEquals("NO_ACTION_REQUIRED", result.name()); + assertEquals(0, result.ordinal()); + } + + /** + * Run the PolicyResponseStatus getStatus(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetStatus_2() + throws Exception { + String responseStatus = ""; + + PolicyResponseStatus result = PolicyResponseStatus.getStatus(responseStatus); + + // add additional test code here + assertNotNull(result); + assertEquals("no_action", result.toString()); + assertEquals("NO_ACTION_REQUIRED", result.name()); + assertEquals(0, result.ordinal()); + } + + /** + * Run the PolicyResponseStatus getStatus(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testGetStatus_3() + throws Exception { + String responseStatus = ""; + + PolicyResponseStatus result = PolicyResponseStatus.getStatus(responseStatus); + + // add additional test code here + assertNotNull(result); + assertEquals("no_action", result.toString()); + assertEquals("NO_ACTION_REQUIRED", result.name()); + assertEquals(0, result.ordinal()); + } + + /** + * Run the String toString() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testToString_1() + throws Exception { + PolicyResponseStatus fixture = PolicyResponseStatus.ACTION_ADVISED; + + String result = fixture.toString(); + + // add additional test code here + assertEquals("action_advised", result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PolicyResponseStatusTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyResponseTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyResponseTest.java new file mode 100644 index 000000000..b0a71d375 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyResponseTest.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.After; +import org.junit.Before; +import org.onap.policy.api.PolicyResponse; + +/** + * The class PolicyResponseTest contains tests for the class {@link PolicyResponse}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class PolicyResponseTest { + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PolicyResponseTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyTypeTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyTypeTest.java new file mode 100644 index 000000000..9f1a608da --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyTypeTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.*; +import org.onap.policy.api.PolicyType; + +import static org.junit.Assert.*; + +/** + * The class PolicyTypeTest contains tests for the class {@link PolicyType}. + * + * @generatedBy CodePro at 6/1/16 1:41 PM + * @version $Revision: 1.0 $ + */ +public class PolicyTypeTest { + /** + * Run the String toString() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Test + public void testToString_1() + throws Exception { + PolicyType fixture = PolicyType.JSON; + + String result = fixture.toString(); + + // add additional test code here + assertEquals("json", result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:41 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PolicyTypeTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PushPolicyParametersTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PushPolicyParametersTest.java new file mode 100644 index 000000000..832589757 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PushPolicyParametersTest.java @@ -0,0 +1,269 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import java.util.UUID; + +import org.junit.*; +import org.onap.policy.api.PushPolicyParameters; + +import static org.junit.Assert.*; + +/** + * The class PushPolicyParametersTest contains tests for the class {@link PushPolicyParameters}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class PushPolicyParametersTest { + /** + * Run the PushPolicyParameters() constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPushPolicyParameters_1() + throws Exception { + + PushPolicyParameters result = new PushPolicyParameters(); + + // add additional test code here + assertNotNull(result); + assertEquals(null, result.getPolicyName()); + assertEquals(null, result.getRequestID()); + assertEquals(null, result.getPolicyType()); + assertEquals(null, result.getPdpGroup()); + } + + /** + * Run the PushPolicyParameters(String,String,String,UUID) constructor test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testPushPolicyParameters_2() + throws Exception { + String policyName = ""; + String policyType = ""; + String pdpGroup = ""; + UUID requestID = UUID.randomUUID(); + + PushPolicyParameters result = new PushPolicyParameters(policyName, policyType, pdpGroup, requestID); + + // add additional test code here + assertNotNull(result); + assertEquals("", result.getPolicyName()); + assertEquals("", result.getPolicyType()); + assertEquals("", result.getPdpGroup()); + } + + /** + * Run the String getPdpGroup() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPdpGroup_1() + throws Exception { + PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.randomUUID()); + + String result = fixture.getPdpGroup(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getPolicyName() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyName_1() + throws Exception { + PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.randomUUID()); + + String result = fixture.getPolicyName(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the String getPolicyType() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetPolicyType_1() + throws Exception { + PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.randomUUID()); + + String result = fixture.getPolicyType(); + + // add additional test code here + assertEquals("", result); + } + + /** + * Run the UUID getRequestID() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testGetRequestID() + throws Exception { + PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.fromString("d1dbaac1-0944-4f07-9ce7-733c697537ea")); + + UUID result = fixture.getRequestID(); + + // add additional test code here + assertNotNull(result); + assertEquals("d1dbaac1-0944-4f07-9ce7-733c697537ea", result.toString()); + assertEquals(4, result.version()); + assertEquals(2, result.variant()); + assertEquals(-7140611980868110358L, result.getLeastSignificantBits()); + assertEquals(-3324876153822097657L, result.getMostSignificantBits()); + } + + /** + * Run the void setPdpGroup(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPdpGroup_1() + throws Exception { + PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.randomUUID()); + String pdpGroup = ""; + + fixture.setPdpGroup(pdpGroup); + + // add additional test code here + } + + /** + * Run the void setPolicyName(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyName_1() + throws Exception { + PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.randomUUID()); + String policyName = ""; + + fixture.setPolicyName(policyName); + + // add additional test code here + } + + /** + * Run the void setPolicyType(String) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetPolicyType_1() + throws Exception { + PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.randomUUID()); + String policyType = ""; + + fixture.setPolicyType(policyType); + + // add additional test code here + } + + /** + * Run the void setRequestID(UUID) method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Test + public void testSetRequestID_1() + throws Exception { + PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.randomUUID()); + UUID requestID = UUID.randomUUID(); + + fixture.setRequestID(requestID); + + // add additional test code here + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(PushPolicyParametersTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/RemovedPolicyTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/RemovedPolicyTest.java new file mode 100644 index 000000000..6a53cbfb1 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/RemovedPolicyTest.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.After; +import org.junit.Before; +import org.onap.policy.api.RemovedPolicy; + +/** + * The class RemovedPolicyTest contains tests for the class {@link RemovedPolicy}. + * + * @generatedBy CodePro at 6/1/16 1:40 PM + * @version $Revision: 1.0 $ + */ +public class RemovedPolicyTest { + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:40 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(RemovedPolicyTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/SendEventTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/SendEventTest.java new file mode 100644 index 000000000..560ca463f --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/SendEventTest.java @@ -0,0 +1,155 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.onap.policy.api.PolicyEngine; +import org.onap.policy.api.PolicyEngineException; +import org.onap.policy.api.PolicyEventException; +import org.onap.policy.api.PolicyResponse; +import org.onap.policy.api.PolicyResponseStatus; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +public class SendEventTest { + + private PolicyEngine policyEngine = null; + private Map eventAttributes = new HashMap(); + private Collection policyResponse = null; + private static final Logger logger = FlexLogger.getLogger(SendEventTest.class); + @Before + public void setUp() { + try { + policyEngine = new PolicyEngine("Test/config_pass.properties"); + } catch (PolicyEngineException e) { + logger.error(e.getMessage()); + fail("PolicyEngine Instantiation Error" + e); + } + logger.info("Loaded.. PolicyEngine"); + } + + //@Test + @SuppressWarnings("deprecation") + public void testSendEventFail() { + eventAttributes = null; + try { + policyResponse = policyEngine.sendEvent(eventAttributes); + } catch (PolicyEventException e) { + logger.warn(e.getMessage()); + } + assertNull(policyResponse); + } + + //@Test + @SuppressWarnings("deprecation") + public void testSendEventFailNull() { + eventAttributes.put("", ""); + try { + policyResponse = policyEngine.sendEvent(eventAttributes); + } catch (PolicyEventException e) { + logger.warn(e.getMessage()); + } + assertNull(policyResponse); + } + + // deprecated Test. + /*@Test + public void testSendEventFailAttribute() { + eventAttributes.put("Fail.key", "Value"); + try { + policyResponse = policyEngine.sendEvent(eventAttributes); + } catch (PolicyEventException e) { + logger.warn(e.getMessage()); + } + assertNull(policyResponse.getPolicyResponseMessage()); + }*/ + + //@Test + @SuppressWarnings("deprecation") + public void testSendEventNotValid() { + eventAttributes.put("Action.fail", "Value"); + try { + policyResponse = policyEngine.sendEvent(eventAttributes); + } catch (PolicyEventException e) { + logger.warn(e.getMessage()); + } + for(PolicyResponse policyResponse: this.policyResponse){ + logger.info(policyResponse.getPolicyResponseMessage() + " , " + policyResponse.getPolicyResponseStatus()); + assertNotNull(policyResponse); + assertEquals(PolicyResponseStatus.NO_ACTION_REQUIRED, policyResponse.getPolicyResponseStatus()); + assertNotNull(policyResponse.getPolicyResponseMessage()); + assertNotNull(policyResponse.getRequestAttributes()); + assertNull(policyResponse.getActionTaken()); + assertNull(policyResponse.getActionAdvised()); + } + } + + //@Test + @SuppressWarnings("deprecation") + public void testSendEventActionAdvised() { + eventAttributes.put("Key", "Value"); + eventAttributes.put("cpu", "80"); + try { + policyResponse = policyEngine.sendEvent(eventAttributes); + } catch (PolicyEventException e) { + logger.warn(e.getMessage()); + } + for(PolicyResponse policyResponse: this.policyResponse){ + logger.info(policyResponse.getPolicyResponseMessage() + " , " + policyResponse.getPolicyResponseStatus()); + assertNotNull(policyResponse); + assertEquals(PolicyResponseStatus.ACTION_ADVISED, policyResponse.getPolicyResponseStatus()); + assertNotNull(policyResponse.getPolicyResponseMessage()); + assertNotNull(policyResponse.getRequestAttributes()); + assertNull(policyResponse.getActionTaken()); + assertNotNull(policyResponse.getActionAdvised()); + } + } + + //@Test + @SuppressWarnings("deprecation") + public void testSendEventActionTaken() { + eventAttributes.put("Key", "Value"); + eventAttributes.put("cpu", "91"); + try { + policyResponse = policyEngine.sendEvent(eventAttributes); + } catch (PolicyEventException e) { + logger.warn(e.getMessage()); + } + for(PolicyResponse policyResponse: this.policyResponse){ + logger.info(policyResponse.getPolicyResponseMessage() + " , " + policyResponse.getPolicyResponseStatus()); + assertNotNull(policyResponse); + assertEquals(PolicyResponseStatus.ACTION_TAKEN, policyResponse.getPolicyResponseStatus()); + assertNotNull(policyResponse.getPolicyResponseMessage()); + assertNotNull(policyResponse.getRequestAttributes()); + assertNotNull(policyResponse.getActionTaken()); + assertNull(policyResponse.getActionAdvised()); + } + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/TestRunner.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/TestRunner.java new file mode 100644 index 000000000..87687f0ab --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/TestRunner.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.runner.JUnitCore; +import org.junit.runner.Result; +import org.junit.runner.notification.Failure; + +public class TestRunner { + public static void main(String[] args) { + Result result = JUnitCore.runClasses(PolicyEngineTest.class); + for(Failure failure: result.getFailures()) { + System.out.println("Failed Test: " + failure.toString()); + } + Result results = null; + if(result.wasSuccessful()) { + System.out.println("API Methods are being Tested.. "); + results = JUnitCore.runClasses(GetConfigByPolicyNameTest.class, GetConfigStringTest.class,GetConfigStringStringTest.class,GetConfigStringStringMapTest.class,SendEventTest.class); + for(Failure failure: results.getFailures()) { + System.out.println("Failed Test: " + failure.toString()); + } + System.out.println("Test Results.. "); + System.out.println("Stats: \nRun Time: " + (results.getRunTime()+result.getRunTime()) + "\nTotal Tests:" + results.getRunCount()+ result.getRunCount() + + "\nFailures: " + results.getFailureCount()+ result.getFailureCount()); + System.exit(1); + } + System.out.println("Test Failed.."); + System.out.println("Stats: \nRun Time: " + result.getRunTime() + "\nTests:" + result.getRunCount() + + "\nFailures: " + result.getFailureCount()); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/UpdateTypeTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/UpdateTypeTest.java new file mode 100644 index 000000000..500d6c1c5 --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/UpdateTypeTest.java @@ -0,0 +1,91 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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.test; + +import org.junit.*; +import org.onap.policy.api.UpdateType; + +import static org.junit.Assert.*; + +/** + * The class UpdateTypeTest contains tests for the class {@link UpdateType}. + * + * @generatedBy CodePro at 6/1/16 1:39 PM + * @version $Revision: 1.0 $ + */ +public class UpdateTypeTest { + /** + * Run the String toString() method test. + * + * @throws Exception + * + * @generatedBy CodePro at 6/1/16 1:39 PM + */ + @Test + public void testToString_1() + throws Exception { + UpdateType fixture = UpdateType.NEW; + + String result = fixture.toString(); + + // add additional test code here + assertEquals("new", result); + } + + /** + * Perform pre-test initialization. + * + * @throws Exception + * if the initialization fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:39 PM + */ + @Before + public void setUp() + throws Exception { + // add additional set up code here + } + + /** + * Perform post-test clean-up. + * + * @throws Exception + * if the clean-up fails for some reason + * + * @generatedBy CodePro at 6/1/16 1:39 PM + */ + @After + public void tearDown() + throws Exception { + // Add additional tear down code here + } + + /** + * Launch the test. + * + * @param args the command line arguments + * + * @generatedBy CodePro at 6/1/16 1:39 PM + */ + public static void main(String[] args) { + new org.junit.runner.JUnitCore().run(UpdateTypeTest.class); + } +} diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/package-info.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/package-info.java new file mode 100644 index 000000000..eb92f89bd --- /dev/null +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/package-info.java @@ -0,0 +1,24 @@ +/*- + * ============LICENSE_START======================================================= + * PolicyEngineAPI + * ================================================================================ + * 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========================================================= + */ + +/** + * API JUNIT TestCases. + */ +package org.onap.policy.test; diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/AutoClientEndTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/AutoClientEndTest.java deleted file mode 100644 index 86f15992a..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/AutoClientEndTest.java +++ /dev/null @@ -1,228 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import static org.junit.Assert.assertNotNull; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.policy.api.NotificationHandler; -import org.openecomp.policy.api.NotificationScheme; -import org.openecomp.policy.std.AutoClientEnd; -import org.openecomp.policy.std.StdPolicyEngine; - -/** - * The class AutoClientEndTest contains tests for the class {@link AutoClientEnd}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class AutoClientEndTest { - /** - * Run the AutoClientEnd() constructor test. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testAutoClientEnd_1() - throws Exception { - AutoClientEnd result = new AutoClientEnd(); - assertNotNull(result); - // add additional test code here - } - - /** - * Run the boolean getStatus() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetStatus_1() - throws Exception { - - boolean result = AutoClientEnd.getStatus(); - - assertNotNull(result); - } - - /** - * Run the String getURL() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetURL_1() - throws Exception { - - String result = AutoClientEnd.getURL(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientEnd - assertNotNull(result); - } - - - /** - * Run the void setAuto(NotificationScheme,NotificationHandler) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetAuto() - throws Exception { - NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; - NotificationHandler handler = null; - - AutoClientEnd.setAuto(scheme, handler); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.ExceptionInInitializerError - // at org.apache.log4j.Logger.getLogger(Logger.java:104) - // at org.openecomp.policy.std.AutoClientEnd.(AutoClientEnd.java:39) - } - - /** - * Run the void setScheme(NotificationScheme) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetScheme() - throws Exception { - - NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; - AutoClientEnd.setScheme(scheme); - - } - - /** - * Run the void start(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testStart() - throws Exception { - String url = "http://test.com"; - - AutoClientEnd.start(url); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientEnd - } - - - /** - * Run the void start(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testStart_2() - throws Exception { - String url = null; - - AutoClientEnd.start(url); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientEnd - } - - /** - * Run the void stop() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testStop_1() - throws Exception { - - AutoClientEnd.stop(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientEnd - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add set up code here - StdPolicyEngine policyEngine = new StdPolicyEngine("Test/config_pass.properties", (String) null); - - NotificationHandler handler = policyEngine.getNotificationHandler(); - AutoClientEnd.setAuto(NotificationScheme.AUTO_ALL_NOTIFICATIONS, handler); - AutoClientEnd.start("http://testurl.com"); - - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(AutoClientEndTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/AutoClientUEBTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/AutoClientUEBTest.java deleted file mode 100644 index 28889677b..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/AutoClientUEBTest.java +++ /dev/null @@ -1,567 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import java.util.LinkedList; -import java.util.List; - -import org.junit.*; -import org.openecomp.policy.api.NotificationHandler; -import org.openecomp.policy.api.NotificationScheme; -import org.openecomp.policy.std.AutoClientUEB; - -import static org.junit.Assert.*; - -/** - * The class AutoClientUEBTest contains tests for the class {@link AutoClientUEB}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class AutoClientUEBTest { - /** - * Run the AutoClientUEB(String,List) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testAutoClientUEB_1() - throws Exception { - String url = ""; - String apiKey = ""; - String apiSecret = ""; - List uebURLList = new LinkedList(); - - AutoClientUEB result = new AutoClientUEB(url, uebURLList, apiKey, apiSecret); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.ExceptionInInitializerError - // at org.apache.log4j.Logger.getLogger(Logger.java:104) - // at org.openecomp.policy.std.AutoClientUEB.(AutoClientUEB.java:39) - assertNotNull(result); - } - - /** - * Run the String getNotficationType() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetNotficationType_1() - throws Exception { - - String result = AutoClientUEB.getNotficationType(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - assertNull(result); - } - - /** - * Run the boolean getStatus() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetStatus_1() - throws Exception { - - boolean result = AutoClientUEB.getStatus(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - assertFalse(result); - } - - /** - * Run the String getURL() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetURL_1() - throws Exception { - - String result = AutoClientUEB.getURL(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - assertNotNull(result); - } - - /** - * Run the boolean isRunning() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testIsRunning_1() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(), "", ""); - fixture.isRunning = true; - - boolean result = fixture.isRunning(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - assertTrue(result); - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_1() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(), "", ""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_2() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(), "", ""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_3() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(), "", ""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_4() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(), "", ""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_5() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_6() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_7() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_8() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_9() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_10() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_11() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_12() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_13() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_14() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_15() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void run() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRun_16() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); - fixture.isRunning = true; - - fixture.run(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void setAuto(NotificationScheme,NotificationHandler) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetAuto_1() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); - fixture.isRunning = true; - NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; - NotificationHandler handler = null; - - fixture.setAuto(scheme, handler); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void setScheme(NotificationScheme) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetScheme_1() - throws Exception { - NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; - - AutoClientUEB.setScheme(scheme); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Run the void terminate() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testTerminate_1() - throws Exception { - AutoClientUEB fixture = new AutoClientUEB("", new LinkedList(),"",""); - fixture.isRunning = true; - - fixture.terminate(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.AutoClientUEB - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add set up code here - List urlList = new LinkedList(); - urlList.add("test2.com"); - AutoClientUEB client = new AutoClientUEB("test.com", urlList, "testKey", "testSecret"); - NotificationHandler handler = null; - client.setAuto(NotificationScheme.AUTO_ALL_NOTIFICATIONS, handler); - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(AutoClientUEBTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/Handler.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/Handler.java deleted file mode 100644 index 9879174cb..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/Handler.java +++ /dev/null @@ -1,126 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import java.util.Collection; - -import org.openecomp.policy.api.LoadedPolicy; -import org.openecomp.policy.api.NotificationHandler; -import org.openecomp.policy.api.NotificationType; -import org.openecomp.policy.api.PDPNotification; -import org.openecomp.policy.api.PolicyConfig; -import org.openecomp.policy.api.PolicyConfigException; -import org.openecomp.policy.api.PolicyConfigStatus; -import org.openecomp.policy.api.PolicyEngine; -import org.openecomp.policy.api.PolicyEngineException; -import org.openecomp.policy.api.RemovedPolicy; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -public class Handler implements NotificationHandler{ - - private static final Logger LOGGER = FlexLogger.getLogger(Handler.class); - - @Override - public void notificationReceived(PDPNotification notification) { - System.out.println("Notification Received..."); - System.out.println(notification.getNotificationType()); - if(notification.getNotificationType().equals(NotificationType.REMOVE)){ - System.out.println("Removed Policies: \n"); - for(RemovedPolicy removedPolicy: notification.getRemovedPolicies()){ - System.out.println(removedPolicy.getPolicyName()); - System.out.println(removedPolicy.getVersionNo()); - } - }else if(notification.getNotificationType().equals(NotificationType.UPDATE)){ - System.out.println("Updated Policies: \n"); - for(LoadedPolicy updatedPolicy: notification.getLoadedPolicies()){ - System.out.println("policyName : " + updatedPolicy.getPolicyName()); - System.out.println("policyVersion :" + updatedPolicy.getVersionNo()); - if(updatedPolicy.getPolicyName().contains(".Config_")){ - System.out.println("Matches: " + updatedPolicy.getMatches()); - System.out.println("UpdateType: "+ updatedPolicy.getUpdateType()); - // Checking the Name is correct or not. - try { - PolicyEngine policyEngine = new PolicyEngine("config.properties"); - @SuppressWarnings("deprecation") - Collection policyConfigs = policyEngine.getConfigByPolicyName(updatedPolicy.getPolicyName()); - for(PolicyConfig policyConfig: policyConfigs){ - if(policyConfig.getPolicyConfigStatus().equals(PolicyConfigStatus.CONFIG_RETRIEVED)){ - System.out.println("Policy Retrieved with this Name notified. "); - }else{ - System.err.println("\n\n Fail to retrieve policy !!!!\n\n"); - } - // Also Test this case. - if(policyConfig.getPolicyName().equals(updatedPolicy.getPolicyName())){ - System.out.println("Policy Name is good. "); - }else{ - System.err.println("\n\n Fail to check Name \n\n"); - } - } - } catch (PolicyEngineException e) { - LOGGER.error("Exception Occured"+e); - } catch (PolicyConfigException e) { - LOGGER.error("Exception Occured"+e); - } - } - } - }else if(notification.getNotificationType().equals(NotificationType.BOTH)){ - System.out.println("Both updated and Removed Notification: \n"); - System.out.println("Removed Policies: \n"); - for(RemovedPolicy removedPolicy: notification.getRemovedPolicies()){ - System.out.println(removedPolicy.getPolicyName()); - System.out.println(removedPolicy.getVersionNo()); - } - System.out.println("Updated Policies: \n"); - for(LoadedPolicy updatedPolicy: notification.getLoadedPolicies()){ - System.out.println("policyName : " + updatedPolicy.getPolicyName()); - System.out.println("policyVersion :" + updatedPolicy.getVersionNo()); - System.out.println("Matches: " + updatedPolicy.getMatches()); - System.out.println("UpdateType: "+ updatedPolicy.getUpdateType()); - // Checking the Name is correct or not. - try { - PolicyEngine policyEngine = new PolicyEngine("config.properties"); - @SuppressWarnings("deprecation") - Collection policyConfigs = policyEngine.getConfigByPolicyName(updatedPolicy.getPolicyName()); - for(PolicyConfig policyConfig: policyConfigs){ - if(policyConfig.getPolicyConfigStatus().equals(PolicyConfigStatus.CONFIG_RETRIEVED)){ - System.out.println("Policy Retrieved with this Name notified. "); - }else{ - System.err.println("\n\n Fail to retrieve policy !!!!\n\n"); - } - // Also Test this case. - if(policyConfig.getPolicyName().equals(updatedPolicy.getPolicyName())){ - System.out.println("Policy Name is good. "); - }else{ - System.err.println("\n\n Fail to check Name \n\n"); - } - } - } catch (PolicyEngineException e) { - LOGGER.error("Exception Occured"+e); - } catch (PolicyConfigException e) { - LOGGER.error("Exception Occured"+e); - } - } - } - } - - -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/ManualClientEndTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/ManualClientEndTest.java deleted file mode 100644 index c44dac606..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/ManualClientEndTest.java +++ /dev/null @@ -1,126 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.policy.api.NotificationScheme; -import org.openecomp.policy.api.PDPNotification; -import org.openecomp.policy.std.ManualClientEnd; - -/** - * The class ManualClientEndTest contains tests for the class {@link ManualClientEnd}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class ManualClientEndTest { - /** - * Run the ManualClientEnd() constructor test. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testManualClientEnd_1() - throws Exception { - ManualClientEnd result = new ManualClientEnd(); - assertNotNull(result); - // add additional test code here - } - - - /** - * Run the PDPNotification result(NotificationScheme) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testResult_1() - throws Exception { - NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; - - PDPNotification result = ManualClientEnd.result(scheme); - - assertNull(result); - } - - - /** - * Run the void start(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStart_1() - throws Exception { - String url = ""; - - ManualClientEnd.start(url); - - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(ManualClientEndTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/ManualClientEndUEBTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/ManualClientEndUEBTest.java deleted file mode 100644 index f19697597..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/ManualClientEndUEBTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.util.LinkedList; -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.policy.api.NotificationScheme; -import org.openecomp.policy.api.PDPNotification; -import org.openecomp.policy.std.ManualClientEndUEB; -import org.openecomp.policy.std.StdPDPNotification; - -/** - * The class ManualClientEndUEBTest contains tests for the class {@link ManualClientEndUEB}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class ManualClientEndUEBTest { - - String resultJson = "{'test':'testing'}"; - String json = "{\"test\":\"testing\"}"; - StdPDPNotification notification = new StdPDPNotification(); - ManualClientEndUEB mockManualClient = null; - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - String url = "http://test.com"; - List uebURLList = new LinkedList(); - uebURLList.add(url); - - } - /** - * Run the ManualClientEndUEB() constructor test. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testManualClientEndUEB_1() - throws Exception { - ManualClientEndUEB result = new ManualClientEndUEB(); - assertNotNull(result); - // add additional test code here - } - - /** - * Run the PDPNotification result(NotificationScheme) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testResult_1() - throws Exception { - NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; - - PDPNotification result = ManualClientEndUEB.result(scheme); - - assertNull(result); - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(ManualClientEndUEBTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/MatchStoreTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/MatchStoreTest.java deleted file mode 100644 index ab8946c60..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/MatchStoreTest.java +++ /dev/null @@ -1,776 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -import java.util.HashSet; -import java.util.Hashtable; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.policy.api.PDPNotification; -import org.openecomp.policy.std.MatchStore; -import org.openecomp.policy.std.Matches; -import org.openecomp.policy.std.StdPDPNotification; - -/** - * The class MatchStoreTest contains tests for the class {@link MatchStore}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class MatchStoreTest { - /** - * Run the MatchStore() constructor test. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testMatchStore_1() - throws Exception { - MatchStore result = new MatchStore(); - assertNotNull(result); - // add additional test code here - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_1() - throws Exception { - PDPNotification oldNotification = null; - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNull(result); - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_2() - throws Exception { - PDPNotification oldNotification = new StdPDPNotification(); - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNotNull(result); - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_3() - throws Exception { - PDPNotification oldNotification = new StdPDPNotification(); - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNotNull(result); - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_4() - throws Exception { - PDPNotification oldNotification = new StdPDPNotification(); - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNotNull(result); - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_5() - throws Exception { - PDPNotification oldNotification = new StdPDPNotification(); - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNotNull(result); - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_6() - throws Exception { - PDPNotification oldNotification = new StdPDPNotification(); - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNotNull(result); - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_7() - throws Exception { - PDPNotification oldNotification = new StdPDPNotification(); - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNotNull(result); - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_8() - throws Exception { - PDPNotification oldNotification = new StdPDPNotification(); - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNotNull(result); - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_9() - throws Exception { - PDPNotification oldNotification = new StdPDPNotification(); - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNotNull(result); - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_10() - throws Exception { - PDPNotification oldNotification = new StdPDPNotification(); - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNotNull(result); - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_11() - throws Exception { - PDPNotification oldNotification = new StdPDPNotification(); - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNotNull(result); - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_12() - throws Exception { - PDPNotification oldNotification = new StdPDPNotification(); - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNotNull(result); - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_13() - throws Exception { - PDPNotification oldNotification = new StdPDPNotification(); - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNotNull(result); - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_14() - throws Exception { - PDPNotification oldNotification = new StdPDPNotification(); - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNotNull(result); - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_15() - throws Exception { - PDPNotification oldNotification = new StdPDPNotification(); - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNotNull(result); - } - - /** - * Run the PDPNotification checkMatch(PDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testCheckMatch_16() - throws Exception { - PDPNotification oldNotification = new StdPDPNotification(); - - PDPNotification result = MatchStore.checkMatch(oldNotification); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - assertNotNull(result); - } - - /** - * Run the HashSet getMatchStore() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetMatchStore_1() - throws Exception { - - HashSet result = MatchStore.getMatchStore(); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.ExceptionInInitializerError - // at org.apache.log4j.Logger.getLogger(Logger.java:104) - // at org.openecomp.policy.std.MatchStore.(MatchStore.java:15) - assertNotNull(result); - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_1() - throws Exception { - Matches newMatch = new Matches(); - newMatch.setConfigName(""); - newMatch.setEcompName(""); - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_2() - throws Exception { - Matches newMatch = new Matches(); - newMatch.setConfigName(""); - newMatch.setEcompName(""); - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_3() - throws Exception { - Matches newMatch = new Matches(); - newMatch.setConfigName(""); - newMatch.setEcompName(""); - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_4() - throws Exception { - Matches newMatch = new Matches(); - newMatch.setConfigAttributes(new Hashtable()); - newMatch.setConfigName(""); - newMatch.setEcompName(""); - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_5() - throws Exception { - Matches newMatch = new Matches(); - newMatch.setConfigAttributes(new Hashtable()); - newMatch.setConfigName(""); - newMatch.setEcompName(""); - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_6() - throws Exception { - Matches newMatch = new Matches(); - newMatch.setConfigAttributes(new Hashtable()); - newMatch.setConfigName(""); - newMatch.setEcompName(""); - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_7() - throws Exception { - Matches newMatch = new Matches(); - newMatch.setConfigAttributes(new Hashtable()); - newMatch.setConfigName(""); - newMatch.setEcompName(""); - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_8() - throws Exception { - Matches newMatch = new Matches(); - newMatch.setConfigName(""); - newMatch.setEcompName(""); - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_9() - throws Exception { - Matches newMatch = new Matches(); - newMatch.setEcompName(""); - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_10() - throws Exception { - Matches newMatch = new Matches(); - newMatch.setConfigAttributes(new Hashtable()); - newMatch.setConfigName(""); - newMatch.setEcompName(""); - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_11() - throws Exception { - Matches newMatch = new Matches(); - newMatch.setConfigAttributes(new Hashtable()); - newMatch.setConfigName(""); - newMatch.setEcompName(""); - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_12() - throws Exception { - Matches newMatch = new Matches(); - newMatch.setConfigAttributes(new Hashtable()); - newMatch.setConfigName(""); - newMatch.setEcompName(""); - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_13() - throws Exception { - Matches newMatch = new Matches(); - newMatch.setConfigAttributes(new Hashtable()); - newMatch.setConfigName(""); - newMatch.setEcompName(""); - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_14() - throws Exception { - Matches newMatch = new Matches(); - newMatch.setConfigAttributes(new Hashtable()); - newMatch.setConfigName(""); - newMatch.setEcompName(""); - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_15() - throws Exception { - Matches newMatch = new Matches(); - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Run the void storeMatch(Matches) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStoreMatch_16() - throws Exception { - Matches newMatch = null; - - MatchStore.storeMatch(newMatch); - - // add additional test code here - // An unexpected exception was thrown in user code while executing this test: - // java.lang.NoClassDefFoundError: Could not initialize class org.openecomp.policy.std.MatchStore - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(MatchStoreTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/MatchesTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/MatchesTest.java deleted file mode 100644 index cdc9b5595..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/MatchesTest.java +++ /dev/null @@ -1,216 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import java.util.Hashtable; -import java.util.Map; - -import org.junit.*; -import org.openecomp.policy.std.Matches; - -import static org.junit.Assert.*; - -/** - * The class MatchesTest contains tests for the class {@link Matches}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class MatchesTest { - /** - * Run the Matches() constructor test. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testMatches_1() - throws Exception { - Matches result = new Matches(); - assertNotNull(result); - // add additional test code here - } - - /** - * Run the Map getConfigAttributes() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetConfigAttributes_1() - throws Exception { - Matches fixture = new Matches(); - fixture.setEcompName(""); - fixture.setConfigAttributes(new Hashtable()); - fixture.setConfigName(""); - - Map result = fixture.getConfigAttributes(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the String getConfigName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetConfigName_1() - throws Exception { - Matches fixture = new Matches(); - fixture.setEcompName(""); - fixture.setConfigAttributes(new Hashtable()); - fixture.setConfigName(""); - - String result = fixture.getConfigName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getEcompName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetEcompName_1() - throws Exception { - Matches fixture = new Matches(); - fixture.setEcompName(""); - fixture.setConfigAttributes(new Hashtable()); - fixture.setConfigName(""); - - String result = fixture.getEcompName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the void setConfigAttributes(Map) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetConfigAttributes_1() - throws Exception { - Matches fixture = new Matches(); - fixture.setEcompName(""); - fixture.setConfigAttributes(new Hashtable()); - fixture.setConfigName(""); - Map configAttributes = new Hashtable(); - - fixture.setConfigAttributes(configAttributes); - - // add additional test code here - } - - /** - * Run the void setConfigName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetConfigName_1() - throws Exception { - Matches fixture = new Matches(); - fixture.setEcompName(""); - fixture.setConfigAttributes(new Hashtable()); - fixture.setConfigName(""); - String configName = ""; - - fixture.setConfigName(configName); - - // add additional test code here - } - - /** - * Run the void setEcompName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetEcompName_1() - throws Exception { - Matches fixture = new Matches(); - fixture.setEcompName(""); - fixture.setConfigAttributes(new Hashtable()); - fixture.setConfigName(""); - String ecompName = ""; - - fixture.setEcompName(ecompName); - - // add additional test code here - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(MatchesTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/NotificationStoreTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/NotificationStoreTest.java deleted file mode 100644 index d54c4f4cb..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/NotificationStoreTest.java +++ /dev/null @@ -1,359 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import org.junit.*; -import org.openecomp.policy.std.NotificationStore; -import org.openecomp.policy.std.StdPDPNotification; - -import static org.junit.Assert.*; - -/** - * The class NotificationStoreTest contains tests for the class {@link NotificationStore}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class NotificationStoreTest { - /** - * Run the NotificationStore() constructor test. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testNotificationStore_1() - throws Exception { - NotificationStore result = new NotificationStore(); - assertNotNull(result); - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_1() - throws Exception { - StdPDPNotification notification = new StdPDPNotification(); - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_2() - throws Exception { - StdPDPNotification notification = new StdPDPNotification(); - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_3() - throws Exception { - StdPDPNotification notification = new StdPDPNotification(); - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_4() - throws Exception { - StdPDPNotification notification = new StdPDPNotification(); - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_5() - throws Exception { - StdPDPNotification notification = new StdPDPNotification(); - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_6() - throws Exception { - StdPDPNotification notification = new StdPDPNotification(); - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_7() - throws Exception { - StdPDPNotification notification = new StdPDPNotification(); - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_8() - throws Exception { - StdPDPNotification notification = new StdPDPNotification(); - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_9() - throws Exception { - StdPDPNotification notification = new StdPDPNotification(); - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_10() - throws Exception { - StdPDPNotification notification = new StdPDPNotification(); - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_11() - throws Exception { - StdPDPNotification notification = new StdPDPNotification(); - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_12() - throws Exception { - StdPDPNotification notification = new StdPDPNotification(); - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_13() - throws Exception { - StdPDPNotification notification = new StdPDPNotification(); - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_14() - throws Exception { - StdPDPNotification notification = new StdPDPNotification(); - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_15() - throws Exception { - StdPDPNotification notification = new StdPDPNotification(); - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Run the void recordNotification(StdPDPNotification) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testRecordNotification_16() - throws Exception { - StdPDPNotification notification = null; - - NotificationStore.recordNotification(notification); - - // add additional test code here - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(NotificationStoreTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/NotificationUnMarshalTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/NotificationUnMarshalTest.java deleted file mode 100644 index 674c58a00..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/NotificationUnMarshalTest.java +++ /dev/null @@ -1,256 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import static org.junit.Assert.assertNotNull; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.policy.std.NotificationUnMarshal; -import org.openecomp.policy.std.StdPDPNotification; - -/** - * The class NotificationUnMarshalTest contains tests for the class {@link NotificationUnMarshal}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class NotificationUnMarshalTest { - /** - * Run the StdPDPNotification notificationJSON(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) - public void testNotificationJSON_1() - throws Exception { - String json = ""; - - StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); - - // add additional test code here - assertNotNull(result); - } - - /** - * Run the StdPDPNotification notificationJSON(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) - public void testNotificationJSON_2() - throws Exception { - String json = ""; - - StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); - - // add additional test code here - assertNotNull(result); - } - - /** - * Run the StdPDPNotification notificationJSON(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) - public void testNotificationJSON_3() - throws Exception { - String json = ""; - - StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); - - // add additional test code here - assertNotNull(result); - } - - /** - * Run the StdPDPNotification notificationJSON(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) - public void testNotificationJSON_4() - throws Exception { - String json = ""; - - StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); - - // add additional test code here - assertNotNull(result); - } - - /** - * Run the StdPDPNotification notificationJSON(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) - public void testNotificationJSON_5() - throws Exception { - String json = ""; - - StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); - - // add additional test code here - assertNotNull(result); - } - - /** - * Run the StdPDPNotification notificationJSON(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) - public void testNotificationJSON_6() - throws Exception { - String json = ""; - - StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); - - // add additional test code here - assertNotNull(result); - } - - /** - * Run the StdPDPNotification notificationJSON(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) - public void testNotificationJSON_7() - throws Exception { - String json = ""; - - StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); - - // add additional test code here - assertNotNull(result); - } - - /** - * Run the StdPDPNotification notificationJSON(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) - public void testNotificationJSON_8() - throws Exception { - String json = ""; - - StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); - - // add additional test code here - assertNotNull(result); - } - - /** - * Run the StdPDPNotification notificationJSON(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) - public void testNotificationJSON_9() - throws Exception { - String json = ""; - - StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); - - // add additional test code here - assertNotNull(result); - } - - /** - * Run the StdPDPNotification notificationJSON(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test(expected = com.fasterxml.jackson.databind.JsonMappingException.class) - public void testNotificationJSON_10() - throws Exception { - String json = ""; - - StdPDPNotification result = NotificationUnMarshal.notificationJSON(json); - - // add additional test code here - assertNotNull(result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(NotificationUnMarshalTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdLoadedPolicyTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdLoadedPolicyTest.java deleted file mode 100644 index de8a6a7ad..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdLoadedPolicyTest.java +++ /dev/null @@ -1,314 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import java.util.Hashtable; -import java.util.Map; - -import org.junit.*; -import org.openecomp.policy.api.UpdateType; -import org.openecomp.policy.std.StdLoadedPolicy; - -import static org.junit.Assert.*; - -/** - * The class StdLoadedPolicyTest contains tests for the class {@link StdLoadedPolicy}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class StdLoadedPolicyTest { - /** - * Run the StdLoadedPolicy() constructor test. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testStdLoadedPolicy_1() - throws Exception { - StdLoadedPolicy result = new StdLoadedPolicy(); - assertNotNull(result); - // add additional test code here - } - - /** - * Run the Map getMatches() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetMatches_1() - throws Exception { - StdLoadedPolicy fixture = new StdLoadedPolicy(); - fixture.setPolicyName(""); - fixture.setVersionNo(""); - fixture.setUpdateType(UpdateType.NEW); - fixture.setMatches(new Hashtable()); - - Map result = fixture.getMatches(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyName_1() - throws Exception { - StdLoadedPolicy fixture = new StdLoadedPolicy(); - fixture.setPolicyName(""); - fixture.setVersionNo(""); - fixture.setUpdateType(UpdateType.NEW); - fixture.setMatches(new Hashtable()); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyName_2() - throws Exception { - StdLoadedPolicy fixture = new StdLoadedPolicy(); - fixture.setPolicyName((String) null); - fixture.setVersionNo(""); - fixture.setUpdateType(UpdateType.NEW); - fixture.setMatches(new Hashtable()); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals(null, result); - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyName_3() - throws Exception { - StdLoadedPolicy fixture = new StdLoadedPolicy(); - fixture.setPolicyName(""); - fixture.setVersionNo(""); - fixture.setUpdateType(UpdateType.NEW); - fixture.setMatches(new Hashtable()); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the UpdateType getUpdateType() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetUpdateType_1() - throws Exception { - StdLoadedPolicy fixture = new StdLoadedPolicy(); - fixture.setPolicyName(""); - fixture.setVersionNo(""); - fixture.setUpdateType(UpdateType.NEW); - fixture.setMatches(new Hashtable()); - - UpdateType result = fixture.getUpdateType(); - - // add additional test code here - assertNotNull(result); - assertEquals("new", result.toString()); - assertEquals("NEW", result.name()); - assertEquals(1, result.ordinal()); - } - - /** - * Run the String getVersionNo() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetVersionNo_1() - throws Exception { - StdLoadedPolicy fixture = new StdLoadedPolicy(); - fixture.setPolicyName(""); - fixture.setVersionNo(""); - fixture.setUpdateType(UpdateType.NEW); - fixture.setMatches(new Hashtable()); - - String result = fixture.getVersionNo(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the void setMatches(Map) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetMatches_1() - throws Exception { - StdLoadedPolicy fixture = new StdLoadedPolicy(); - fixture.setPolicyName(""); - fixture.setVersionNo(""); - fixture.setUpdateType(UpdateType.NEW); - fixture.setMatches(new Hashtable()); - Map matches = new Hashtable(); - - fixture.setMatches(matches); - - // add additional test code here - } - - /** - * Run the void setPolicyName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyName_1() - throws Exception { - StdLoadedPolicy fixture = new StdLoadedPolicy(); - fixture.setPolicyName(""); - fixture.setVersionNo(""); - fixture.setUpdateType(UpdateType.NEW); - fixture.setMatches(new Hashtable()); - String policyName = ""; - - fixture.setPolicyName(policyName); - - // add additional test code here - } - - /** - * Run the void setUpdateType(UpdateType) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetUpdateType_1() - throws Exception { - StdLoadedPolicy fixture = new StdLoadedPolicy(); - fixture.setPolicyName(""); - fixture.setVersionNo(""); - fixture.setUpdateType(UpdateType.NEW); - fixture.setMatches(new Hashtable()); - UpdateType updateType = UpdateType.NEW; - - fixture.setUpdateType(updateType); - - // add additional test code here - } - - /** - * Run the void setVersionNo(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetVersionNo_1() - throws Exception { - StdLoadedPolicy fixture = new StdLoadedPolicy(); - fixture.setPolicyName(""); - fixture.setVersionNo(""); - fixture.setUpdateType(UpdateType.NEW); - fixture.setMatches(new Hashtable()); - String versionNo = ""; - - fixture.setVersionNo(versionNo); - - // add additional test code here - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(StdLoadedPolicyTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPDPNotificationTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPDPNotificationTest.java deleted file mode 100644 index 1bda0e59f..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPDPNotificationTest.java +++ /dev/null @@ -1,311 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import java.util.Collection; -import java.util.LinkedList; - -import org.junit.*; -import org.openecomp.policy.api.LoadedPolicy; -import org.openecomp.policy.api.NotificationType; -import org.openecomp.policy.api.RemovedPolicy; -import org.openecomp.policy.std.StdLoadedPolicy; -import org.openecomp.policy.std.StdPDPNotification; -import org.openecomp.policy.std.StdRemovedPolicy; - -import static org.junit.Assert.*; - -/** - * The class StdPDPNotificationTest contains tests for the class {@link StdPDPNotification}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class StdPDPNotificationTest { - /** - * Run the StdPDPNotification() constructor test. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testStdPDPNotification_1() - throws Exception { - StdPDPNotification result = new StdPDPNotification(); - assertNotNull(result); - // add additional test code here - } - - /** - * Run the Collection getLoadedPolicies() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetLoadedPolicies_1() - throws Exception { - StdPDPNotification fixture = new StdPDPNotification(); - fixture.setRemovedPolicies(new LinkedList()); - fixture.setNotificationType(NotificationType.BOTH); - fixture.setLoadedPolicies(new LinkedList()); - - Collection result = fixture.getLoadedPolicies(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the Collection getLoadedPolicies() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetLoadedPolicies_2() - throws Exception { - StdPDPNotification fixture = new StdPDPNotification(); - fixture.setRemovedPolicies(new LinkedList()); - fixture.setNotificationType(NotificationType.BOTH); - fixture.setLoadedPolicies(new LinkedList()); - - Collection result = fixture.getLoadedPolicies(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the Collection getLoadedPolicies() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetLoadedPolicies_3() - throws Exception { - StdPDPNotification fixture = new StdPDPNotification(); - fixture.setRemovedPolicies(new LinkedList()); - fixture.setNotificationType(NotificationType.BOTH); - fixture.setLoadedPolicies(null); - - Collection result = fixture.getLoadedPolicies(); - - // add additional test code here - assertEquals(null, result); - } - - /** - * Run the NotificationType getNotificationType() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetNotificationType_1() - throws Exception { - StdPDPNotification fixture = new StdPDPNotification(); - fixture.setRemovedPolicies(new LinkedList()); - fixture.setNotificationType(NotificationType.BOTH); - fixture.setLoadedPolicies(new LinkedList()); - - NotificationType result = fixture.getNotificationType(); - - // add additional test code here - assertNotNull(result); - assertEquals("both", result.toString()); - assertEquals("BOTH", result.name()); - assertEquals(2, result.ordinal()); - } - - /** - * Run the Collection getRemovedPolicies() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetRemovedPolicies_1() - throws Exception { - StdPDPNotification fixture = new StdPDPNotification(); - fixture.setRemovedPolicies(new LinkedList()); - fixture.setNotificationType(NotificationType.BOTH); - fixture.setLoadedPolicies(new LinkedList()); - - Collection result = fixture.getRemovedPolicies(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the Collection getRemovedPolicies() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetRemovedPolicies_2() - throws Exception { - StdPDPNotification fixture = new StdPDPNotification(); - fixture.setRemovedPolicies(new LinkedList()); - fixture.setNotificationType(NotificationType.BOTH); - fixture.setLoadedPolicies(new LinkedList()); - - Collection result = fixture.getRemovedPolicies(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the Collection getRemovedPolicies() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetRemovedPolicies_3() - throws Exception { - StdPDPNotification fixture = new StdPDPNotification(); - fixture.setRemovedPolicies(null); - fixture.setNotificationType(NotificationType.BOTH); - fixture.setLoadedPolicies(new LinkedList()); - - Collection result = fixture.getRemovedPolicies(); - - // add additional test code here - assertEquals(null, result); - } - - /** - * Run the void setNotificationType(NotificationType) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetNotificationType_1() - throws Exception { - StdPDPNotification fixture = new StdPDPNotification(); - fixture.setRemovedPolicies(new LinkedList()); - fixture.setNotificationType(NotificationType.BOTH); - fixture.setLoadedPolicies(new LinkedList()); - NotificationType notificationType = NotificationType.BOTH; - - fixture.setNotificationType(notificationType); - - // add additional test code here - } - - /** - * Run the void setRemovedPolicies(Collection) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetRemovedPolicies_1() - throws Exception { - StdPDPNotification fixture = new StdPDPNotification(); - fixture.setRemovedPolicies(new LinkedList()); - fixture.setNotificationType(NotificationType.BOTH); - fixture.setLoadedPolicies(new LinkedList()); - Collection removedPolicies = new LinkedList(); - - fixture.setRemovedPolicies(removedPolicies); - - // add additional test code here - } - - /** - * Run the void setUpdatedPolicies(Collection) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetUpdatedPolicies_1() - throws Exception { - StdPDPNotification fixture = new StdPDPNotification(); - fixture.setRemovedPolicies(new LinkedList()); - fixture.setNotificationType(NotificationType.BOTH); - fixture.setLoadedPolicies(new LinkedList()); - Collection updatedPolicies = new LinkedList(); - - fixture.setLoadedPolicies(updatedPolicies); - - // add additional test code here - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(StdPDPNotificationTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPolicyChangeResponseTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPolicyChangeResponseTest.java deleted file mode 100644 index 45c70187d..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPolicyChangeResponseTest.java +++ /dev/null @@ -1,166 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import org.junit.*; -import org.openecomp.policy.std.StdPolicyChangeResponse; - -import static org.junit.Assert.*; - -/** - * The class StdPolicyChangeResponseTest contains tests for the class {@link StdPolicyChangeResponse}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class StdPolicyChangeResponseTest { - /** - * Run the StdPolicyChangeResponse() constructor test. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testStdPolicyChangeResponse_1() - throws Exception { - StdPolicyChangeResponse result = new StdPolicyChangeResponse(); - assertNotNull(result); - // add additional test code here - } - - /** - * Run the int getResponseCode() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetResponseCode_1() - throws Exception { - StdPolicyChangeResponse fixture = new StdPolicyChangeResponse(); - fixture.setResponseMessage(""); - fixture.setResponseCode(1); - - int result = fixture.getResponseCode(); - - // add additional test code here - assertEquals(1, result); - } - - /** - * Run the String getResponseMessage() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetResponseMessage_1() - throws Exception { - StdPolicyChangeResponse fixture = new StdPolicyChangeResponse(); - fixture.setResponseMessage(""); - fixture.setResponseCode(1); - - String result = fixture.getResponseMessage(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the void setResponseCode(int) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetResponseCode_1() - throws Exception { - StdPolicyChangeResponse fixture = new StdPolicyChangeResponse(); - fixture.setResponseMessage(""); - fixture.setResponseCode(1); - int responseCode = 1; - - fixture.setResponseCode(responseCode); - - // add additional test code here - } - - /** - * Run the void setResponseMessage(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetResponseMessage_1() - throws Exception { - StdPolicyChangeResponse fixture = new StdPolicyChangeResponse(); - fixture.setResponseMessage(""); - fixture.setResponseCode(1); - String responseMessage = ""; - - fixture.setResponseMessage(responseMessage); - - // add additional test code here - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(StdPolicyChangeResponseTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPolicyConfigTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPolicyConfigTest.java deleted file mode 100644 index a34737477..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPolicyConfigTest.java +++ /dev/null @@ -1,821 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import java.util.Hashtable; -import java.util.Map; -import java.util.Properties; - -import javax.json.JsonObject; - -import org.junit.*; -import org.openecomp.policy.api.PolicyConfigStatus; -import org.openecomp.policy.api.PolicyType; -import org.openecomp.policy.std.StdPolicyConfig; - -import static org.junit.Assert.*; - -import org.w3c.dom.Document; - -/** - * The class StdPolicyConfigTest contains tests for the class {@link StdPolicyConfig}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class StdPolicyConfigTest { - /** - * Run the Map getMatchingConditions() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetMatchingConditions_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - - Map result = fixture.getMatchingConditions(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the String getPolicyConfigMessage() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetPolicyConfigMessage_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - - String result = fixture.getPolicyConfigMessage(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the PolicyConfigStatus getPolicyConfigStatus() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetPolicyConfigStatus_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - - PolicyConfigStatus result = fixture.getPolicyConfigStatus(); - - // add additional test code here - assertNotNull(result); - assertEquals("not_found", result.toString()); - assertEquals("CONFIG_NOT_FOUND", result.name()); - assertEquals(1, result.ordinal()); - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetPolicyName_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetPolicyName_2() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName((String) null); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals(null, result); - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetPolicyName_3() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getPolicyVersion() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetPolicyVersion_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - - String result = fixture.getPolicyVersion(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the Map getResponseAttributes() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetResponseAttributes_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - - Map result = fixture.getResponseAttributes(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the PolicyType getType() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetType_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - - PolicyType result = fixture.getType(); - - // add additional test code here - assertNotNull(result); - assertEquals("json", result.toString()); - assertEquals("JSON", result.name()); - assertEquals(1, result.ordinal()); - } - - /** - * Run the void setConfigStatus(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetConfigStatus_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - String configStatus = ""; - - fixture.setConfigStatus(configStatus); - - // add additional test code here - } - - /** - * Run the void setConfigStatus(String,PolicyConfigStatus) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetConfigStatus_2() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - String configStatus = ""; - PolicyConfigStatus policyConfigStatus = PolicyConfigStatus.CONFIG_NOT_FOUND; - - fixture.setConfigStatus(configStatus, policyConfigStatus); - - // add additional test code here - } - - /** - * Run the void setDocument(Document) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetDocument_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - Document document = null; - - fixture.setDocument(document); - - // add additional test code here - } - - /** - * Run the void setJsonObject(JsonObject) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetJsonObject_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - JsonObject jsonObject = null; - - fixture.setJsonObject(jsonObject); - - // add additional test code here - } - - /** - * Run the void setMatchingConditions(Map) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetMatchingConditions_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - Map matchingConditions = new Hashtable(); - - fixture.setMatchingConditions(matchingConditions); - - // add additional test code here - } - - /** - * Run the void setOther(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetOther_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - String other = ""; - - fixture.setOther(other); - - // add additional test code here - } - - /** - * Run the void setPolicyConfigStatus(PolicyConfigStatus) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetPolicyConfigStatus_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - PolicyConfigStatus policyConfigStatus = PolicyConfigStatus.CONFIG_NOT_FOUND; - - fixture.setPolicyConfigStatus(policyConfigStatus); - - // add additional test code here - } - - /** - * Run the void setPolicyName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetPolicyName_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - String policyName = ""; - - fixture.setPolicyName(policyName); - - // add additional test code here - } - - /** - * Run the void setPolicyType(PolicyType) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetPolicyType_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - PolicyType policyType = PolicyType.JSON; - - fixture.setPolicyType(policyType); - - // add additional test code here - } - - /** - * Run the void setPolicyVersion(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetPolicyVersion_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - String policyVersion = ""; - - fixture.setPolicyVersion(policyVersion); - - // add additional test code here - } - - /** - * Run the void setProperties(Properties) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetProperties_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - Properties properties = new Properties(); - - fixture.setProperties(properties); - - // add additional test code here - } - - /** - * Run the void setResponseAttributes(Map) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetResponseAttributes_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - Map responseAttributes = new Hashtable(); - - fixture.setResponseAttributes(responseAttributes); - - // add additional test code here - } - - /** - * Run the JsonObject toJSON() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testToJSON_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - - JsonObject result = fixture.toJSON(); - - // add additional test code here - assertEquals(null, result); - } - - /** - * Run the String toOther() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testToOther_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - - String result = fixture.toOther(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the Properties toProperties() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testToProperties_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - - Properties result = fixture.toProperties(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the String toString() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testToString_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName("test"); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - - String result = fixture.toString(); - - // add additional test code here - assertEquals("PolicyConfig [ policyConfigStatus=not_found, policyConfigMessage=, policyName=test]", result); - } - - /** - * Run the Document toXML() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testToXML_1() - throws Exception { - StdPolicyConfig fixture = new StdPolicyConfig(); - fixture.setConfigStatus("", PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setDocument((Document) null); - fixture.setResponseAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setOther(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setPolicyName(""); - fixture.setProperties(new Properties()); - fixture.setJsonObject((JsonObject) null); - fixture.setMatchingConditions(new Hashtable()); - - Document result = fixture.toXML(); - - // add additional test code here - assertEquals(null, result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(StdPolicyConfigTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPolicyResponseTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPolicyResponseTest.java deleted file mode 100644 index a593c460b..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdPolicyResponseTest.java +++ /dev/null @@ -1,348 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import java.util.Hashtable; -import java.util.Map; - -import org.junit.*; -import org.openecomp.policy.api.PolicyResponseStatus; -import org.openecomp.policy.std.StdPolicyResponse; - -import static org.junit.Assert.*; - -/** - * The class StdPolicyResponseTest contains tests for the class {@link StdPolicyResponse}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class StdPolicyResponseTest { - /** - * Run the Map getActionAdvised() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetActionAdvised_1() - throws Exception { - StdPolicyResponse fixture = new StdPolicyResponse(); - fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); - fixture.setRequestAttributes(new Hashtable()); - fixture.setActionAdvised(new Hashtable()); - fixture.setActionTaken(new Hashtable()); - - Map result = fixture.getActionAdvised(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the Map getActionTaken() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetActionTaken_1() - throws Exception { - StdPolicyResponse fixture = new StdPolicyResponse(); - fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); - fixture.setRequestAttributes(new Hashtable()); - fixture.setActionAdvised(new Hashtable()); - fixture.setActionTaken(new Hashtable()); - - Map result = fixture.getActionTaken(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the String getPolicyResponseMessage() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyResponseMessage_1() - throws Exception { - StdPolicyResponse fixture = new StdPolicyResponse(); - fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); - fixture.setRequestAttributes(new Hashtable()); - fixture.setActionAdvised(new Hashtable()); - fixture.setActionTaken(new Hashtable()); - - String result = fixture.getPolicyResponseMessage(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the PolicyResponseStatus getPolicyResponseStatus() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyResponseStatus_1() - throws Exception { - StdPolicyResponse fixture = new StdPolicyResponse(); - fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); - fixture.setRequestAttributes(new Hashtable()); - fixture.setActionAdvised(new Hashtable()); - fixture.setActionTaken(new Hashtable()); - - PolicyResponseStatus result = fixture.getPolicyResponseStatus(); - - // add additional test code here - assertNotNull(result); - assertEquals("action_advised", result.toString()); - assertEquals("ACTION_ADVISED", result.name()); - assertEquals(1, result.ordinal()); - } - - /** - * Run the Map getRequestAttributes() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetRequestAttributes_1() - throws Exception { - StdPolicyResponse fixture = new StdPolicyResponse(); - fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); - fixture.setRequestAttributes(new Hashtable()); - fixture.setActionAdvised(new Hashtable()); - fixture.setActionTaken(new Hashtable()); - - Map result = fixture.getRequestAttributes(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the void setActionAdvised(Map) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetActionAdvised_1() - throws Exception { - StdPolicyResponse fixture = new StdPolicyResponse(); - fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); - fixture.setRequestAttributes(new Hashtable()); - fixture.setActionAdvised(new Hashtable()); - fixture.setActionTaken(new Hashtable()); - Map actionAdvised = new Hashtable(); - - fixture.setActionAdvised(actionAdvised); - - // add additional test code here - } - - /** - * Run the void setActionTaken(Map) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetActionTaken_1() - throws Exception { - StdPolicyResponse fixture = new StdPolicyResponse(); - fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); - fixture.setRequestAttributes(new Hashtable()); - fixture.setActionAdvised(new Hashtable()); - fixture.setActionTaken(new Hashtable()); - Map actionTaken = new Hashtable(); - - fixture.setActionTaken(actionTaken); - - // add additional test code here - } - - /** - * Run the void setPolicyResponseMessage(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyResponseMessage_1() - throws Exception { - StdPolicyResponse fixture = new StdPolicyResponse(); - fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); - fixture.setRequestAttributes(new Hashtable()); - fixture.setActionAdvised(new Hashtable()); - fixture.setActionTaken(new Hashtable()); - String policyResponseMessage = ""; - - fixture.setPolicyResponseMessage(policyResponseMessage); - - // add additional test code here - } - - /** - * Run the void setPolicyResponseStatus(PolicyResponseStatus) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyResponseStatus_1() - throws Exception { - StdPolicyResponse fixture = new StdPolicyResponse(); - fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); - fixture.setRequestAttributes(new Hashtable()); - fixture.setActionAdvised(new Hashtable()); - fixture.setActionTaken(new Hashtable()); - PolicyResponseStatus policyResponseStatus = PolicyResponseStatus.ACTION_ADVISED; - - fixture.setPolicyResponseStatus(policyResponseStatus); - - // add additional test code here - } - - /** - * Run the void setPolicyResponseStatus(String,PolicyResponseStatus) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyResponseStatus_2() - throws Exception { - StdPolicyResponse fixture = new StdPolicyResponse(); - fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); - fixture.setRequestAttributes(new Hashtable()); - fixture.setActionAdvised(new Hashtable()); - fixture.setActionTaken(new Hashtable()); - String policyResponseMessage = ""; - PolicyResponseStatus policyResponseStatus = PolicyResponseStatus.ACTION_ADVISED; - - fixture.setPolicyResponseStatus(policyResponseMessage, policyResponseStatus); - - // add additional test code here - } - - /** - * Run the void setRequestAttributes(Map) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetRequestAttributes_1() - throws Exception { - StdPolicyResponse fixture = new StdPolicyResponse(); - fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); - fixture.setRequestAttributes(new Hashtable()); - fixture.setActionAdvised(new Hashtable()); - fixture.setActionTaken(new Hashtable()); - Map requestAttributes = new Hashtable(); - - fixture.setRequestAttributes(requestAttributes); - - // add additional test code here - } - - /** - * Run the String toString() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testToString_1() - throws Exception { - StdPolicyResponse fixture = new StdPolicyResponse(); - fixture.setPolicyResponseStatus("", PolicyResponseStatus.ACTION_ADVISED); - fixture.setRequestAttributes(new Hashtable()); - fixture.setActionAdvised(new Hashtable()); - fixture.setActionTaken(new Hashtable()); - - String result = fixture.toString(); - - // add additional test code here - assertEquals("PolicyResponse [ policyResponseStatus=action_advised, policyResponseMessage=, ]", result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(StdPolicyResponseTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdRemovedPolicyTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdRemovedPolicyTest.java deleted file mode 100644 index 0a0865c82..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdRemovedPolicyTest.java +++ /dev/null @@ -1,206 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import org.junit.*; -import org.openecomp.policy.std.StdRemovedPolicy; - -import static org.junit.Assert.*; - -/** - * The class StdRemovedPolicyTest contains tests for the class {@link StdRemovedPolicy}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class StdRemovedPolicyTest { - /** - * Run the StdRemovedPolicy() constructor test. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testStdRemovedPolicy_1() - throws Exception { - StdRemovedPolicy result = new StdRemovedPolicy(); - assertNotNull(result); - // add additional test code here - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyName_1() - throws Exception { - StdRemovedPolicy fixture = new StdRemovedPolicy(); - fixture.setVersionNo(""); - fixture.setPolicyName(""); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyName_2() - throws Exception { - StdRemovedPolicy fixture = new StdRemovedPolicy(); - fixture.setVersionNo(""); - fixture.setPolicyName((String) null); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals(null, result); - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyName_3() - throws Exception { - StdRemovedPolicy fixture = new StdRemovedPolicy(); - fixture.setVersionNo(""); - fixture.setPolicyName(""); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getVersionNo() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetVersionNo_1() - throws Exception { - StdRemovedPolicy fixture = new StdRemovedPolicy(); - fixture.setVersionNo(""); - fixture.setPolicyName(""); - - String result = fixture.getVersionNo(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the void setPolicyName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyName_1() - throws Exception { - StdRemovedPolicy fixture = new StdRemovedPolicy(); - fixture.setVersionNo(""); - fixture.setPolicyName(""); - String policyName = ""; - - fixture.setPolicyName(policyName); - - // add additional test code here - } - - /** - * Run the void setVersionNo(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetVersionNo_1() - throws Exception { - StdRemovedPolicy fixture = new StdRemovedPolicy(); - fixture.setVersionNo(""); - fixture.setPolicyName(""); - String versionNo = ""; - - fixture.setVersionNo(versionNo); - - // add additional test code here - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(StdRemovedPolicyTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdStatusTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdStatusTest.java deleted file mode 100644 index 34918c2ea..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/StdStatusTest.java +++ /dev/null @@ -1,1433 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; - -import java.util.Hashtable; -import java.util.Map; -import java.util.Properties; - -import javax.json.JsonObject; - -import org.junit.*; -import org.openecomp.policy.api.PolicyConfigStatus; -import org.openecomp.policy.api.PolicyDecision; -import org.openecomp.policy.api.PolicyResponseStatus; -import org.openecomp.policy.api.PolicyType; -import org.openecomp.policy.std.StdStatus; - -import static org.junit.Assert.*; - -import org.w3c.dom.Document; - -/** - * The class StdStatusTest contains tests for the class {@link StdStatus}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class StdStatusTest { - /** - * Run the Map getActionAdvised() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetActionAdvised_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - Map result = fixture.getActionAdvised(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the Map getActionTaken() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetActionTaken_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - Map result = fixture.getActionTaken(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the Map getMatchingConditions() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetMatchingConditions_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - Map result = fixture.getMatchingConditions(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the String getPolicyConfigMessage() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyConfigMessage_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - String result = fixture.getPolicyConfigMessage(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the PolicyConfigStatus getPolicyConfigStatus() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyConfigStatus_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - PolicyConfigStatus result = fixture.getPolicyConfigStatus(); - - // add additional test code here - assertNotNull(result); - assertEquals("not_found", result.toString()); - assertEquals("CONFIG_NOT_FOUND", result.name()); - assertEquals(1, result.ordinal()); - } - - /** - * Run the PolicyDecision getPolicyDecision() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyDecision_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - PolicyDecision result = fixture.getDecision(); - - // add additional test code here - assertNotNull(result); - assertEquals("deny", result.toString()); - assertEquals("DENY", result.name()); - assertEquals(1, result.ordinal()); - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyName_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyName_2() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName((String) null); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals(null, result); - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyName_3() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getPolicyResponseMessage() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyResponseMessage_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - String result = fixture.getPolicyResponseMessage(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the PolicyResponseStatus getPolicyResponseStatus() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyResponseStatus_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - PolicyResponseStatus result = fixture.getPolicyResponseStatus(); - - // add additional test code here - assertNotNull(result); - assertEquals("action_advised", result.toString()); - assertEquals("ACTION_ADVISED", result.name()); - assertEquals(1, result.ordinal()); - } - - /** - * Run the String getPolicyVersion() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyVersion_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - String result = fixture.getPolicyVersion(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the Map getRequestAttributes() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetRequestAttributes_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - Map result = fixture.getRequestAttributes(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the Map getResponseAttributes() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetResponseAttributes_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - Map result = fixture.getResponseAttributes(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the PolicyType getType() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetType_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - PolicyType result = fixture.getType(); - - // add additional test code here - assertNotNull(result); - assertEquals("json", result.toString()); - assertEquals("JSON", result.name()); - assertEquals(1, result.ordinal()); - } - - /** - * Run the void setActionAdvised(Map) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetActionAdvised_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - Map actionAdvised = new Hashtable(); - - fixture.setActionAdvised(actionAdvised); - - // add additional test code here - } - - /** - * Run the void setActionTaken(Map) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetActionTaken_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - Map actionTaken = new Hashtable(); - - fixture.setActionTaken(actionTaken); - - // add additional test code here - } - - /** - * Run the void setConfigStatus(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetConfigStatus_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - String configStatus = ""; - - fixture.setConfigStatus(configStatus); - - // add additional test code here - } - - /** - * Run the void setDocument(Document) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetDocument_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - Document document = null; - - fixture.setDocument(document); - - // add additional test code here - } - - /** - * Run the void setJsonObject(JsonObject) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetJsonObject_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - JsonObject jsonObject = null; - - fixture.setJsonObject(jsonObject); - - // add additional test code here - } - - /** - * Run the void setMatchingConditions(Map) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetMatchingConditions_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - Map matchingConditions = new Hashtable(); - - fixture.setMatchingConditions(matchingConditions); - - // add additional test code here - } - - /** - * Run the void setOther(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetOther_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - String other = ""; - - fixture.setOther(other); - - // add additional test code here - } - - /** - * Run the void setPolicyConfigStatus(PolicyConfigStatus) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyConfigStatus_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - PolicyConfigStatus policyConfigStatus = PolicyConfigStatus.CONFIG_NOT_FOUND; - - fixture.setPolicyConfigStatus(policyConfigStatus); - - // add additional test code here - } - - /** - * Run the void setPolicyConfigStatus(String,PolicyConfigStatus) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyConfigStatus_2() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - String configStatus = ""; - PolicyConfigStatus policyConfigStatus = PolicyConfigStatus.CONFIG_NOT_FOUND; - - fixture.setPolicyConfigStatus(configStatus, policyConfigStatus); - - // add additional test code here - } - - /** - * Run the void setPolicyDecision(PolicyDecision) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyDecision_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - PolicyDecision policyDecision = PolicyDecision.DENY; - - fixture.setDecision(policyDecision); - - // add additional test code here - } - - /** - * Run the void setPolicyName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyName_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - String policyName = ""; - - fixture.setPolicyName(policyName); - - // add additional test code here - } - - /** - * Run the void setPolicyResponseMessage(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyResponseMessage_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - String policyResponseMessage = ""; - - fixture.setPolicyResponseMessage(policyResponseMessage); - - // add additional test code here - } - - /** - * Run the void setPolicyResponseStatus(PolicyResponseStatus) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyResponseStatus_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - PolicyResponseStatus policyResponseStatus = PolicyResponseStatus.ACTION_ADVISED; - - fixture.setPolicyResponseStatus(policyResponseStatus); - - // add additional test code here - } - - /** - * Run the void setPolicyResponseStatus(String,PolicyResponseStatus) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyResponseStatus_2() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - String policyResponseMessage = ""; - PolicyResponseStatus policyResponseStatus = PolicyResponseStatus.ACTION_ADVISED; - - fixture.setPolicyResponseStatus(policyResponseMessage, policyResponseStatus); - - // add additional test code here - } - - /** - * Run the void setPolicyType(PolicyType) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyType_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - PolicyType policyType = PolicyType.JSON; - - fixture.setPolicyType(policyType); - - // add additional test code here - } - - /** - * Run the void setPolicyVersion(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyVersion_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - String policyVersion = ""; - - fixture.setPolicyVersion(policyVersion); - - // add additional test code here - } - - /** - * Run the void setProperties(Properties) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetProperties_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - Properties properties = new Properties(); - - fixture.setProperties(properties); - - // add additional test code here - } - - /** - * Run the void setRequestAttributes(Map) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetRequestAttributes_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - Map requestAttributes = new Hashtable(); - - fixture.setRequestAttributes(requestAttributes); - - // add additional test code here - } - - /** - * Run the void setResposneAttributes(Map) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetResposneAttributes_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - Map responseAttributes = new Hashtable(); - - fixture.setResposneAttributes(responseAttributes); - - // add additional test code here - } - - /** - * Run the void setStatus(String,PolicyResponseStatus,PolicyConfigStatus) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetStatus_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - String message = ""; - PolicyResponseStatus policyResponseStatus = PolicyResponseStatus.ACTION_ADVISED; - PolicyConfigStatus policyConfigStatus = PolicyConfigStatus.CONFIG_NOT_FOUND; - - fixture.setStatus(message, policyResponseStatus, policyConfigStatus); - - // add additional test code here - } - - /** - * Run the JsonObject toJSON() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testToJSON_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - JsonObject result = fixture.toJSON(); - - // add additional test code here - assertEquals(null, result); - } - - /** - * Run the String toOther() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testToOther_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - String result = fixture.toOther(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the Properties toProperties() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testToProperties_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - Properties result = fixture.toProperties(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the Document toXML() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testToXML_1() - throws Exception { - StdStatus fixture = new StdStatus(); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setPolicyName(""); - fixture.setPolicyType(PolicyType.JSON); - fixture.setResposneAttributes(new Hashtable()); - fixture.setMatchingConditions(new Hashtable()); - fixture.setStatus("", PolicyResponseStatus.ACTION_ADVISED, PolicyConfigStatus.CONFIG_NOT_FOUND); - fixture.setJsonObject((JsonObject) null); - fixture.setDocument((Document) null); - fixture.setProperties(new Properties()); - fixture.setRequestAttributes(new Hashtable()); - fixture.setPolicyVersion(""); - fixture.setActionAdvised(new Hashtable()); - fixture.setOther(""); - fixture.setDecision(PolicyDecision.DENY); - fixture.setDetails(""); - fixture.setActionTaken(new Hashtable()); - - Document result = fixture.toXML(); - - // add additional test code here - assertEquals(null, result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(StdStatusTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/package-info.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/package-info.java deleted file mode 100644 index 75bfc39ad..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/std/test/package-info.java +++ /dev/null @@ -1,27 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.std.test; diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ActionPolicyApiTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ActionPolicyApiTest.java deleted file mode 100644 index 398efe0f1..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ActionPolicyApiTest.java +++ /dev/null @@ -1,239 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.openecomp.policy.api.AttributeType; -import org.openecomp.policy.api.PolicyChangeResponse; -import org.openecomp.policy.api.PolicyClass; -import org.openecomp.policy.api.PolicyEngine; -import org.openecomp.policy.api.PolicyEngineException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.std.StdPolicyChangeResponse; - -import junit.framework.TestCase; - -public class ActionPolicyApiTest extends TestCase { - - private static final Logger logger = FlexLogger.getLogger(ActionPolicyApiTest.class); - - private PolicyEngine policyEngine = null; - private PolicyEngine mockPolicyEngine = null; - - PolicyChangeResponse result = null; - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - PolicyParameters policyParameters = new PolicyParameters(); - - @Before - protected void setUp() throws Exception { - try { - policyEngine = new PolicyEngine("Test/config_pass.properties"); - } catch (PolicyEngineException e) { - logger.error(e.getMessage()); - fail("PolicyEngine Instantiation Error" + e); - } - logger.info("Loaded.. PolicyEngine"); - - mockPolicyEngine = Mockito.mock(PolicyEngine.class); - - policyParameters.setPolicyClass(PolicyClass.Action); //required - policyParameters.setPolicyName("test.junitTest"); //required - policyParameters.setPolicyDescription("testing"); //optional - //policyParameters.setPolicyScope("test"); //Directory will be created where the Policies are saved... this displays a a subscope on the GUI - - //Set the Component Attributes... These are Optional - Map configAttributes = new HashMap(); - configAttributes.put("test", "testing"); - - Map> attributes = new HashMap>(); - attributes.put(AttributeType.MATCHING, configAttributes); - policyParameters.setAttributes(attributes); - - policyParameters.setActionPerformer("PEP"); - policyParameters.setActionAttribute("testing"); - policyParameters.setRequestID(UUID.randomUUID()); - } - - protected void tearDown() throws Exception { - super.tearDown(); - } - - @Test - public final void testCreatePolicy() { - response.setResponseMessage("success"); - PolicyChangeResponse result = null; - try { - - Mockito.when(mockPolicyEngine.createPolicy(policyParameters)).thenReturn(response); - result = mockPolicyEngine.createPolicy(policyParameters); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - @Test - public final void testUpdatePolicy() { - response.setResponseMessage("success"); - PolicyChangeResponse result = null; - try { - - Mockito.when(mockPolicyEngine.updatePolicy(policyParameters)).thenReturn(response); - result = mockPolicyEngine.updatePolicy(policyParameters); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - - } - - @Test - public final void testCreatePolicyNullPolicyName() { - response.setResponseMessage("PE300 - Data Issue: No Policy Name given."); - policyParameters.setPolicyName(null); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testCreatePolicyNullPolicyScope() { - response.setResponseMessage("PE300 - Data Issue: No Policy Scope given."); - policyParameters.setPolicyName("test"); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testCreatePolicyNullActionAttributes() { - response.setResponseMessage("PE300 - Data Issue: No Action Attribute given."); - policyParameters.setActionAttribute(null); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testCreatePolicyNullActionPerformer() { - response.setResponseMessage("PE300 - Data Issue: No Action Performer given."); - policyParameters.setActionPerformer(null); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testCreatePolicyInvalidActionPerformer() { - response.setResponseMessage("PE300 - Data Issue: Invalid Action Performer given."); - policyParameters.setActionPerformer("testfail"); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullPolicyName() { - response.setResponseMessage("PE300 - Data Issue: No Policy Name given."); - policyParameters.setPolicyName(null); - try{ - result = policyEngine.updatePolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullPolicyScope() { - response.setResponseMessage("PE300 - Data Issue: No Policy Scope given."); - policyParameters.setPolicyName("test"); - try{ - result = policyEngine.updatePolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullActionAttributes() { - response.setResponseMessage("PE300 - Data Issue: No Action Attribute given."); - policyParameters.setActionAttribute(null); - try{ - result = policyEngine.updatePolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullActionPerformer() { - response.setResponseMessage("PE300 - Data Issue: No Action Performer given."); - policyParameters.setActionPerformer(null); - try{ - result = policyEngine.updatePolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyInvalidActionPerformer() { - response.setResponseMessage("PE300 - Data Issue: Invalid Action Performer given."); - policyParameters.setActionPerformer("testfail"); - try{ - result = policyEngine.updatePolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/AttributeTypeTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/AttributeTypeTest.java deleted file mode 100644 index df8713ab8..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/AttributeTypeTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.*; -import org.openecomp.policy.api.AttributeType; - -import static org.junit.Assert.*; - -/** - * The class AttributeTypeTest contains tests for the class {@link AttributeType}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class AttributeTypeTest { - /** - * Run the String toString() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testToString_1() - throws Exception { - AttributeType fixture = AttributeType.MATCHING; - - String result = fixture.toString(); - - // add additional test code here - assertEquals("matching", result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ConfigBasePolicyTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ConfigBasePolicyTest.java deleted file mode 100644 index 69de7fe87..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ConfigBasePolicyTest.java +++ /dev/null @@ -1,325 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.junit.Test; -import org.mockito.Mockito; -import org.openecomp.policy.api.AttributeType; -import org.openecomp.policy.api.PolicyChangeResponse; -import org.openecomp.policy.api.PolicyConfigType; -import org.openecomp.policy.api.PolicyEngine; -import org.openecomp.policy.api.PolicyEngineException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.api.PolicyType; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.std.StdPolicyChangeResponse; - -import junit.framework.TestCase; - -/** - * The class ConfigBasePolicyTest contains tests for the class - * {@link PolicyEngine} - * - * @pattern JUnit Test Case - * * - */ -public class ConfigBasePolicyTest extends TestCase { - - private static final Logger logger = FlexLogger.getLogger(DecisionPolicyApiTest.class); - - private PolicyEngine policyEngine = null; - private PolicyEngine mockPolicyEngine = null; - - PolicyChangeResponse result = null; - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - PolicyParameters policyParameters = new PolicyParameters(); - - /** - * Perform pre-test initialization - * - * @throws Exception - * - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - try { - policyEngine = new PolicyEngine("Test/config_pass.properties"); - } catch (PolicyEngineException e) { - logger.error(e.getMessage()); - fail("PolicyEngine Instantiation Error" + e); - } - logger.info("Loaded.. PolicyEngine"); - - mockPolicyEngine = Mockito.mock(PolicyEngine.class); - - policyParameters.setPolicyConfigType(PolicyConfigType.Base); //required - policyParameters.setPolicyName("test.junitTest"); //required - policyParameters.setEcompName("test"); - policyParameters.setConfigName("testBase"); - policyParameters.setConfigBodyType(PolicyType.OTHER); - policyParameters.setConfigBody("testing"); - policyParameters.setPolicyDescription("testing"); //optional - //policyParameters.setPolicyScope("test"); //Directory will be created where the Policies are saved... this displays a a subscope on the GUI - - //Set the Component Attributes... These are Optional - Map configAttributes = new HashMap(); - configAttributes.put("test", "testing"); - - Map> attributes = new HashMap>(); - attributes.put(AttributeType.MATCHING, configAttributes); - policyParameters.setAttributes(attributes); - - policyParameters.setRequestID(UUID.randomUUID()); - } - - /** - * Perform post-test clean up - * - * @throws Exception - * - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - // Add additional tear down code here - } - - /** - * Run the PolicyChangeResponse createPolicy(PolicyParameters) method test - */ - public void testCreatePolicy() { - response.setResponseMessage("success"); - PolicyChangeResponse result = null; - try { - - Mockito.when(mockPolicyEngine.createPolicy(policyParameters)).thenReturn(response); - result = mockPolicyEngine.createPolicy(policyParameters); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - /** - * Run the String createConfigPolicy() method test - */ - @SuppressWarnings("deprecation") - @Test - public void testCreateConfigPolicy() { - String response = "success"; - String result = null; - try { - - Mockito.when(mockPolicyEngine.createConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null)).thenReturn(response); - result = mockPolicyEngine.createConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - /** - * Run the PolicyChangeResponse updatePolicy(PolicyParameters) method test - */ - public void testUpdatePolicy() { - response.setResponseMessage("success"); - PolicyChangeResponse result = null; - try { - - Mockito.when(mockPolicyEngine.updatePolicy(policyParameters)).thenReturn(response); - result = mockPolicyEngine.updatePolicy(policyParameters); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - /** - * Run the String updateConfigPolicy() method test - */ - @SuppressWarnings("deprecation") - @Test - public void testUpdateConfigPolicy() { - String response = "success"; - String result = null; - try { - - Mockito.when(mockPolicyEngine.updateConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null)).thenReturn(response); - result = mockPolicyEngine.updateConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - @Test - public final void testCreatePolicyNullPolicyName() { - response.setResponseMessage("PE300 - Data Issue: No Policy Name given."); - policyParameters.setPolicyName(null); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testCreatePolicyNullPolicyScope() { - response.setResponseMessage("PE300 - Data Issue: No Policy Scope given."); - policyParameters.setPolicyName("test"); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testCreatePolicyNullEcompName() { - response.setResponseMessage("PE300 - Data Issue: No ECOMP Name given."); - policyParameters.setEcompName(null); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testCreatePolicyNullPolicyConfigName() { - response.setResponseMessage("PE300 - Data Issue: No Config Name given."); - policyParameters.setConfigName(null);; - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testCreatePolicyNullPolicyConfigBodyType() { - response.setResponseMessage("PE300 - Data Issue: No Config Body Type given."); - policyParameters.setConfigBodyType(null); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testCreatePolicyNullPolicyConfigBody() { - response.setResponseMessage("PE300 - Data Issue: No Config Body given."); - policyParameters.setConfigBody(null); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullPolicyName() { - response.setResponseMessage("PE300 - Data Issue: No Policy Name given."); - policyParameters.setPolicyName(null); - try{ - result = policyEngine.updatePolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullPolicyScope() { - response.setResponseMessage("PE300 - Data Issue: No Policy Scope given."); - policyParameters.setPolicyName("test"); - try{ - result = policyEngine.updatePolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullEcompName() { - response.setResponseMessage("PE300 - Data Issue: No ECOMP Name given."); - policyParameters.setEcompName(null); - try{ - result = policyEngine.updatePolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullPolicyConfigName() { - response.setResponseMessage("PE300 - Data Issue: No Config Name given."); - policyParameters.setConfigName(null);; - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullPolicyConfigBodyType() { - response.setResponseMessage("PE300 - Data Issue: No Config Body Type given."); - policyParameters.setConfigBodyType(null); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullPolicyConfigBody() { - response.setResponseMessage("PE300 - Data Issue: No Config Body given."); - policyParameters.setConfigBody(null); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - //assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } -} \ No newline at end of file diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ConfigFirewallPolicyTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ConfigFirewallPolicyTest.java deleted file mode 100644 index 280f06e10..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ConfigFirewallPolicyTest.java +++ /dev/null @@ -1,254 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import java.io.StringReader; -import java.util.UUID; - -import javax.json.Json; -import javax.json.JsonObject; -import javax.json.JsonReader; - -import org.junit.Test; -import org.mockito.Mockito; -import org.openecomp.policy.api.PolicyChangeResponse; -import org.openecomp.policy.api.PolicyConfigType; -import org.openecomp.policy.api.PolicyEngine; -import org.openecomp.policy.api.PolicyEngineException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.std.StdPolicyChangeResponse; - -import junit.framework.TestCase; - -public class ConfigFirewallPolicyTest extends TestCase { - - private static final Logger logger = FlexLogger.getLogger(DecisionPolicyApiTest.class); - - private PolicyEngine policyEngine = null; - private PolicyEngine mockPolicyEngine = null; - - PolicyChangeResponse result = null; - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - PolicyParameters policyParameters = new PolicyParameters(); - String json = null; - - /** - * Perform pre-test initialization - * - * @throws Exception - * - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - try { - policyEngine = new PolicyEngine("Test/config_pass.properties"); - } catch (PolicyEngineException e) { - logger.error(e.getMessage()); - fail("PolicyEngine Instantiation Error" + e); - } - logger.info("Loaded.. PolicyEngine"); - - mockPolicyEngine = Mockito.mock(PolicyEngine.class); - - policyParameters.setPolicyConfigType(PolicyConfigType.Firewall); //required - policyParameters.setPolicyName("test.junitTest"); //required - - json = "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"rule1607\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"/v0/firewall/pan\",\"serviceGroups\":[{\"name\":\"1607Group\",\"description\":null,\"members\":[{\"type\":\"REFERENCE\",\"name\":\"SList\"},{\"type\":\"REFERENCE\",\"name\":\"Syslog\"}]},{\"name\":\"Syslog\",\"description\":\"NA\",\"type\":\"SERVICE\",\"transportProtocol\":\"udp\",\"appProtocol\":null,\"ports\":\"514\"},{\"name\":\"SList\",\"description\":\"Service List\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"8080\"}],\"addressGroups\":[{\"name\":\"1607Group\",\"description\":null,\"members\":[{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"},{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"}]},{\"name\":\"PL_CCE3\",\"description\":\"CCE Routers\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"1607Rule\",\"fromZones\":[\"Trusted\"],\"toZones\":[\"Untrusted\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"value\":\"PL_CCE3\"},{\"type\":\"REFERENCE\",\"value\":\"1607Group\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"value\":\"1607Group\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"1607Group\"}],\"action\":\"accept\",\"description\":\"Rule for 1607 templates\",\"enabled\":true,\"log\":true}]}"; - - policyParameters.setConfigBody(buildJSON(json).toString()); - - //policyParameters.setPolicyScope("test"); //Directory will be created where the Policies are saved... this displays a a subscope on the GUI - policyParameters.setRequestID(UUID.randomUUID()); - } - - private static JsonObject buildJSON(String jsonString) { - JsonObject json = null;; - if (jsonString != null) { - StringReader in = null; - - in = new StringReader(jsonString); - - JsonReader jsonReader = Json.createReader(in); - json = jsonReader.readObject(); - } - - return json; - } - /** - * Perform post-test clean up - * - * @throws Exception - * - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - // Add additional tear down code here - } - - /** - * Run the PolicyChangeResponse createPolicy(PolicyParameters) method test - */ - public void testCreatePolicy() { - response.setResponseMessage("success"); - PolicyChangeResponse result = null; - try { - - Mockito.when(mockPolicyEngine.createPolicy(policyParameters)).thenReturn(response); - result = mockPolicyEngine.createPolicy(policyParameters); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - /** - * Run the String createConfigFirewallPolicy() method test - */ - @SuppressWarnings("deprecation") - @Test - public void testCreateConfigFirewallPolicy() { - String response = "success"; - String result = null; - JsonObject jsonObj = buildJSON(json); - try { - - Mockito.when(mockPolicyEngine.createConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null)).thenReturn(response); - result = mockPolicyEngine.createConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - /** - * Run the PolicyChangeResponse updatePolicy(PolicyParameters) method test - */ - public void testUpdatePolicy() { - response.setResponseMessage("success"); - PolicyChangeResponse result = null; - try { - - Mockito.when(mockPolicyEngine.updatePolicy(policyParameters)).thenReturn(response); - result = mockPolicyEngine.updatePolicy(policyParameters); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - /** - * Run the String updateConfigFirewallPolicy() method test - */ - @SuppressWarnings("deprecation") - @Test - public void testUpdateConfigFirewallPolicy() { - String response = "success"; - String result = null; - JsonObject jsonObj = buildJSON(json); - try { - - Mockito.when(mockPolicyEngine.updateConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null)).thenReturn(response); - result = mockPolicyEngine.updateConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - @Test - public final void testCreatePolicyNullPolicyName() { - response.setResponseMessage("PE500 - Process Flow Issue: :500:"); - policyParameters.setPolicyName(null); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testCreatePolicyNullPolicyScope() { - response.setResponseMessage("PE500 - Process Flow Issue: :500:"); - policyParameters.setPolicyName("test"); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testCreatePolicyNullPolicyConfigBody() { - response.setResponseMessage("PE500 - Process Flow Issue: :500:"); - policyParameters.setConfigBody(null); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullPolicyName() { - response.setResponseMessage("PE500 - Process Flow Issue: :500:"); - policyParameters.setPolicyName(null); - try{ - result = policyEngine.updatePolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullPolicyScope() { - response.setResponseMessage("PE500 - Process Flow Issue: :500:"); - policyParameters.setPolicyName("test"); - try{ - result = policyEngine.updatePolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullPolicyConfigBody() { - response.setResponseMessage("PE500 - Process Flow Issue: :500:"); - policyParameters.setConfigBody(null); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ConfigRequestParametersTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ConfigRequestParametersTest.java deleted file mode 100644 index 0e8f912c9..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ConfigRequestParametersTest.java +++ /dev/null @@ -1,362 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import java.util.Hashtable; -import java.util.Map; -import java.util.UUID; - -import org.junit.*; -import org.openecomp.policy.api.ConfigRequestParameters; - -import static org.junit.Assert.*; - -/** - * The class ConfigRequestParametersTest contains tests for the class {@link ConfigRequestParameters}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class ConfigRequestParametersTest { - /** - * Run the ConfigRequestParameters() constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testConfigRequestParameters_1() - throws Exception { - - ConfigRequestParameters result = new ConfigRequestParameters(); - - // add additional test code here - assertNotNull(result); - assertEquals(null, result.getPolicyName()); - assertEquals(null, result.getConfigName()); - assertEquals(null, result.getConfigAttributes()); - assertEquals(null, result.getRequestID()); - assertEquals(null, result.getEcompName()); - assertEquals(Boolean.FALSE, result.getUnique()); - } - - /** - * Run the ConfigRequestParameters(String,String,String,Map,Boolean,UUID) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testConfigRequestParameters_2() - throws Exception { - String policyName = ""; - String eCOMPComponentName = ""; - String configName = ""; - Map configAttributes = new Hashtable(); - Boolean unique = new Boolean(true); - UUID requestID = UUID.randomUUID(); - - ConfigRequestParameters result = createConfigRequest(policyName, eCOMPComponentName, configName, configAttributes, unique, requestID); - - // add additional test code here - assertNotNull(result); - assertEquals("", result.getPolicyName()); - assertEquals("", result.getConfigName()); - assertEquals("", result.getEcompName()); - assertEquals(Boolean.TRUE, result.getUnique()); - } - - /** - * Run the Map getConfigAttributes() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetConfigAttributes_1() - throws Exception { - ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); - - Map result = fixture.getConfigAttributes(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the String getConfigName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetConfigName_1() - throws Exception { - ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); - - String result = fixture.getConfigName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getEcompName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetEcompName_1() - throws Exception { - ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); - - String result = fixture.getEcompName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyName_1() - throws Exception { - ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the UUID getRequestID() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetRequestID_1() - throws Exception { - ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.fromString("6b5aa070-90bc-46a6-9a59-e1fe526df7ae")); - - UUID result = fixture.getRequestID(); - - // add additional test code here - assertNotNull(result); - assertEquals("6b5aa070-90bc-46a6-9a59-e1fe526df7ae", result.toString()); - assertEquals(4, result.version()); - assertEquals(2, result.variant()); - assertEquals(-7324574836520519762L, result.getLeastSignificantBits()); - assertEquals(7735671715287287462L, result.getMostSignificantBits()); - } - - /** - * Run the Boolean getUnique() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetUnique_1() - throws Exception { - ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); - - Boolean result = fixture.getUnique(); - - // add additional test code here - assertNotNull(result); - assertEquals("true", result.toString()); - assertEquals(true, result.booleanValue()); - } - - /** - * Run the void makeUnique(Boolean) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testMakeUnique_1() - throws Exception { - ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); - Boolean unique = new Boolean(true); - - fixture.makeUnique(unique); - - // add additional test code here - } - - /** - * Run the void setConfigAttributes(Map) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetConfigAttributes_1() - throws Exception { - ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); - Map configAttributes = new Hashtable(); - - fixture.setConfigAttributes(configAttributes); - - // add additional test code here - } - - /** - * Run the void setConfigName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetConfigName_1() - throws Exception { - ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); - String configName = ""; - - fixture.setConfigName(configName); - - // add additional test code here - } - - /** - * Run the void setEcompName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetEcompName_1() - throws Exception { - ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); - String eCOMPComponentName = ""; - - fixture.setEcompName(eCOMPComponentName); - - // add additional test code here - } - - /** - * Run the void setPolicyName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyName_1() - throws Exception { - ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); - String policyName = ""; - - fixture.setPolicyName(policyName); - - // add additional test code here - } - - /** - * Run the void setRequestID(UUID) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetRequestID_1() - throws Exception { - ConfigRequestParameters fixture = createConfigRequest("", "", "", new Hashtable(), new Boolean(true), UUID.randomUUID()); - UUID requestID = UUID.randomUUID(); - - fixture.setRequestID(requestID); - - // add additional test code here - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(ConfigRequestParametersTest.class); - } - - private ConfigRequestParameters createConfigRequest(String policyName, String eCOMPComponentName, String configName, Map configAttributes, Boolean unique, UUID requestID){ - ConfigRequestParameters configRequestParameters = new ConfigRequestParameters(); - configRequestParameters.setRequestID(requestID); - configRequestParameters.setPolicyName(policyName); - configRequestParameters.setEcompName(eCOMPComponentName); - configRequestParameters.setConfigName(configName); - configRequestParameters.setConfigAttributes(configAttributes); - configRequestParameters.makeUnique(unique); - return configRequestParameters; - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DecisionPolicyApiTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DecisionPolicyApiTest.java deleted file mode 100644 index 82ba1c7ca..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DecisionPolicyApiTest.java +++ /dev/null @@ -1,219 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.junit.Test; -import org.mockito.Mockito; -import org.openecomp.policy.api.AttributeType; -import org.openecomp.policy.api.PolicyChangeResponse; -import org.openecomp.policy.api.PolicyClass; -import org.openecomp.policy.api.PolicyEngine; -import org.openecomp.policy.api.PolicyEngineException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.std.StdPolicyChangeResponse; - -import junit.framework.TestCase; - -/** - * The class DecisionPolicyApiTest contains tests for the class - * {@link PolicyEngine} - * - * @pattern JUnit Test Case - * * - */ -public class DecisionPolicyApiTest extends TestCase { - - private static final Logger logger = FlexLogger.getLogger(DecisionPolicyApiTest.class); - - private PolicyEngine policyEngine = null; - private PolicyEngine mockPolicyEngine = null; - - PolicyChangeResponse result = null; - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - PolicyParameters policyParameters = new PolicyParameters(); - - /** - * Perform pre-test initialization - * - * @throws Exception - * - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - try { - policyEngine = new PolicyEngine("Test/config_pass.properties"); - } catch (PolicyEngineException e) { - logger.error(e.getMessage()); - fail("PolicyEngine Instantiation Error" + e); - } - logger.info("Loaded.. PolicyEngine"); - - mockPolicyEngine = Mockito.mock(PolicyEngine.class); - - policyParameters.setPolicyClass(PolicyClass.Decision); //required - policyParameters.setPolicyName("test.junitTest"); //required - policyParameters.setEcompName("test"); - policyParameters.setPolicyDescription("testing"); //optional - //policyParameters.setPolicyScope("test"); //Directory will be created where the Policies are saved... this displays a a subscope on the GUI - - //Set the Component Attributes... These are Optional - Map configAttributes = new HashMap(); - configAttributes.put("test", "testing"); - - Map> attributes = new HashMap>(); - attributes.put(AttributeType.MATCHING, configAttributes); - policyParameters.setAttributes(attributes); - - //Set the settings... These are Optional -/* Map settingsMap = new HashMap(); - settingsMap.put("server", "5"); - - Map> settings = new HashMap>(); - settings.put(AttributeType.SETTINGS, settingsMap); - policyParameters.setSettings(settings);*/ - - policyParameters.setRequestID(UUID.randomUUID()); - } - - /** - * Perform post-test clean up - * - * @throws Exception - * - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - // Add additional tear down code here - } - - /** - * Run the PolicyChangeResponse createPolicy(PolicyParameters) method test - */ - public void testCreatePolicy() { - response.setResponseMessage("success"); - PolicyChangeResponse result = null; - try { - - Mockito.when(mockPolicyEngine.createPolicy(policyParameters)).thenReturn(response); - result = mockPolicyEngine.createPolicy(policyParameters); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - /** - * Run the PolicyChangeResponse updatePolicy(PolicyParameters) method test - */ - public void testUpdatePolicy() { - response.setResponseMessage("success"); - PolicyChangeResponse result = null; - try { - - Mockito.when(mockPolicyEngine.updatePolicy(policyParameters)).thenReturn(response); - result = mockPolicyEngine.updatePolicy(policyParameters); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - @Test - public final void testCreatePolicyNullPolicyName() { - response.setResponseMessage("PE500 - Process Flow Issue: :500:"); - policyParameters.setPolicyName(null); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testCreatePolicyNullPolicyScope() { - response.setResponseMessage("PE500 - Process Flow Issue: :500:"); - policyParameters.setPolicyName("test"); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testCreatePolicyNullEcompName() { - response.setResponseMessage("PE500 - Process Flow Issue: :500:"); - policyParameters.setEcompName(null); - try{ - result = policyEngine.createPolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullPolicyName() { - response.setResponseMessage("PE500 - Process Flow Issue: :500:"); - policyParameters.setPolicyName(null); - try{ - result = policyEngine.updatePolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullPolicyScope() { - response.setResponseMessage("PE500 - Process Flow Issue: :500:"); - policyParameters.setPolicyName("test"); - try{ - result = policyEngine.updatePolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } - - @Test - public final void testUpdatePolicyNullEcompName() { - response.setResponseMessage("PE500 - Process Flow Issue: :500:"); - policyParameters.setEcompName(null); - try{ - result = policyEngine.updatePolicy(policyParameters); - } catch (Exception e){ - logger.warn(e.getMessage()); - } - assertEquals(result.getResponseMessage(), response.getResponseMessage()); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DecisionRequestParametersTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DecisionRequestParametersTest.java deleted file mode 100644 index d8fdfbc0a..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DecisionRequestParametersTest.java +++ /dev/null @@ -1,232 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import java.util.Hashtable; -import java.util.Map; -import java.util.UUID; - -import org.junit.*; -import org.openecomp.policy.api.DecisionRequestParameters; - -import static org.junit.Assert.*; - -/** - * The class DecisionRequestParametersTest contains tests for the class {@link DecisionRequestParameters}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class DecisionRequestParametersTest { - /** - * Run the DecisionRequestParameters() constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testDecisionRequestParameters_1() - throws Exception { - - DecisionRequestParameters result = new DecisionRequestParameters(); - - // add additional test code here - assertNotNull(result); - assertEquals(null, result.getECOMPComponentName()); - assertEquals(null, result.getDecisionAttributes()); - assertEquals(null, result.getRequestID()); - } - - /** - * Run the DecisionRequestParameters(String,Map,UUID) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testDecisionRequestParameters_2() - throws Exception { - String eCOMPComponentName = ""; - Map decisionAttributes = new Hashtable(); - UUID requestID = UUID.randomUUID(); - - DecisionRequestParameters result = new DecisionRequestParameters(eCOMPComponentName, decisionAttributes, requestID); - - // add additional test code here - assertNotNull(result); - assertEquals("", result.getECOMPComponentName()); - } - - /** - * Run the Map getDecisionAttributes() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetDecisionAttributes_1() - throws Exception { - DecisionRequestParameters fixture = new DecisionRequestParameters("", new Hashtable(), UUID.randomUUID()); - - Map result = fixture.getDecisionAttributes(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the String getECOMPComponentName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetECOMPComponentName_1() - throws Exception { - DecisionRequestParameters fixture = new DecisionRequestParameters("", new Hashtable(), UUID.randomUUID()); - - String result = fixture.getECOMPComponentName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the UUID getRequestID() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetRequestID_1() - throws Exception { - DecisionRequestParameters fixture = new DecisionRequestParameters("", new Hashtable(), UUID.fromString("d1db6a6d-7140-4864-8200-6b541261fdd2")); - - UUID result = fixture.getRequestID(); - - // add additional test code here - assertNotNull(result); - assertEquals("d1db6a6d-7140-4864-8200-6b541261fdd2", result.toString()); - assertEquals(4, result.version()); - assertEquals(2, result.variant()); - assertEquals(-9079138839949083182L, result.getLeastSignificantBits()); - assertEquals(-3324946881598961564L, result.getMostSignificantBits()); - } - - /** - * Run the void setDecisionAttributes(Map) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetDecisionAttributes_1() - throws Exception { - DecisionRequestParameters fixture = new DecisionRequestParameters("", new Hashtable(), UUID.randomUUID()); - Map decisionAttributes = new Hashtable(); - - fixture.setDecisionAttributes(decisionAttributes); - - // add additional test code here - } - - /** - * Run the void setECOMPComponentName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetECOMPComponentName_1() - throws Exception { - DecisionRequestParameters fixture = new DecisionRequestParameters("", new Hashtable(), UUID.randomUUID()); - String eCOMPComponentName = ""; - - fixture.setECOMPComponentName(eCOMPComponentName); - - // add additional test code here - } - - /** - * Run the void setRequestID(UUID) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetRequestID_1() - throws Exception { - DecisionRequestParameters fixture = new DecisionRequestParameters("", new Hashtable(), UUID.randomUUID()); - UUID requestID = UUID.randomUUID(); - - fixture.setRequestID(requestID); - - // add additional test code here - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(DecisionRequestParametersTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DeletePolicyConditionTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DeletePolicyConditionTest.java deleted file mode 100644 index c2941202b..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DeletePolicyConditionTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.*; -import org.openecomp.policy.api.DeletePolicyCondition; - -import static org.junit.Assert.*; - -/** - * The class DeletePolicyConditionTest contains tests for the class {@link DeletePolicyCondition}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class DeletePolicyConditionTest { - /** - * Run the String toString() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testToString_1() - throws Exception { - DeletePolicyCondition fixture = DeletePolicyCondition.ALL; - - String result = fixture.toString(); - - // add additional test code here - assertEquals("All Versions", result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(DeletePolicyConditionTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DeletePolicyParametersTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DeletePolicyParametersTest.java deleted file mode 100644 index 7723f9819..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/DeletePolicyParametersTest.java +++ /dev/null @@ -1,314 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import java.util.UUID; - -import org.junit.*; -import org.openecomp.policy.api.DeletePolicyCondition; -import org.openecomp.policy.api.DeletePolicyParameters; - -import static org.junit.Assert.*; - -/** - * The class DeletePolicyParametersTest contains tests for the class {@link DeletePolicyParameters}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class DeletePolicyParametersTest { - /** - * Run the DeletePolicyCondition getDeleteCondition() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetDeleteCondition_1() - throws Exception { - DeletePolicyParameters fixture = new DeletePolicyParameters(); - fixture.setPolicyComponent(""); - fixture.setPolicyName(""); - fixture.setDeleteCondition(DeletePolicyCondition.ALL); - fixture.setRequestID(UUID.randomUUID()); - fixture.setPdpGroup(""); - - DeletePolicyCondition result = fixture.getDeleteCondition(); - - // add additional test code here - assertNotNull(result); - assertEquals("All Versions", result.toString()); - assertEquals("ALL", result.name()); - assertEquals(1, result.ordinal()); - } - - /** - * Run the String getPdpGroup() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPdpGroup_1() - throws Exception { - DeletePolicyParameters fixture = new DeletePolicyParameters(); - fixture.setPolicyComponent(""); - fixture.setPolicyName(""); - fixture.setDeleteCondition(DeletePolicyCondition.ALL); - fixture.setRequestID(UUID.randomUUID()); - fixture.setPdpGroup(""); - - String result = fixture.getPdpGroup(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getPolicyComponent() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyComponent_1() - throws Exception { - DeletePolicyParameters fixture = new DeletePolicyParameters(); - fixture.setPolicyComponent(""); - fixture.setPolicyName(""); - fixture.setDeleteCondition(DeletePolicyCondition.ALL); - fixture.setRequestID(UUID.randomUUID()); - fixture.setPdpGroup(""); - - String result = fixture.getPolicyComponent(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyName_1() - throws Exception { - DeletePolicyParameters fixture = new DeletePolicyParameters(); - fixture.setPolicyComponent(""); - fixture.setPolicyName(""); - fixture.setDeleteCondition(DeletePolicyCondition.ALL); - fixture.setRequestID(UUID.randomUUID()); - fixture.setPdpGroup(""); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the UUID getRequestID() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetRequestID_1() - throws Exception { - DeletePolicyParameters fixture = new DeletePolicyParameters(); - fixture.setPolicyComponent(""); - fixture.setPolicyName(""); - fixture.setDeleteCondition(DeletePolicyCondition.ALL); - fixture.setRequestID(UUID.fromString("482e90e2-2ad7-4265-9893-4cfe08ef1e3d")); - fixture.setPdpGroup(""); - - UUID result = fixture.getRequestID(); - - // add additional test code here - assertNotNull(result); - assertEquals("482e90e2-2ad7-4265-9893-4cfe08ef1e3d", result.toString()); - assertEquals(4, result.version()); - assertEquals(2, result.variant()); - assertEquals(-7452528304412746179L, result.getLeastSignificantBits()); - assertEquals(5201253920715260517L, result.getMostSignificantBits()); - } - - /** - * Run the void setDeleteCondition(DeletePolicyCondition) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetDeleteCondition_1() - throws Exception { - DeletePolicyParameters fixture = new DeletePolicyParameters(); - fixture.setPolicyComponent(""); - fixture.setPolicyName(""); - fixture.setDeleteCondition(DeletePolicyCondition.ALL); - fixture.setRequestID(UUID.randomUUID()); - fixture.setPdpGroup(""); - DeletePolicyCondition deleteCondition = DeletePolicyCondition.ALL; - - fixture.setDeleteCondition(deleteCondition); - - // add additional test code here - } - - /** - * Run the void setPdpGroup(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPdpGroup_1() - throws Exception { - DeletePolicyParameters fixture = new DeletePolicyParameters(); - fixture.setPolicyComponent(""); - fixture.setPolicyName(""); - fixture.setDeleteCondition(DeletePolicyCondition.ALL); - fixture.setRequestID(UUID.randomUUID()); - fixture.setPdpGroup(""); - String pdpGroup = ""; - - fixture.setPdpGroup(pdpGroup); - - // add additional test code here - } - - /** - * Run the void setPolicyComponent(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyComponent_1() - throws Exception { - DeletePolicyParameters fixture = new DeletePolicyParameters(); - fixture.setPolicyComponent(""); - fixture.setPolicyName(""); - fixture.setDeleteCondition(DeletePolicyCondition.ALL); - fixture.setRequestID(UUID.randomUUID()); - fixture.setPdpGroup(""); - String policyComponent = ""; - - fixture.setPolicyComponent(policyComponent); - - // add additional test code here - } - - /** - * Run the void setPolicyName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyName_1() - throws Exception { - DeletePolicyParameters fixture = new DeletePolicyParameters(); - fixture.setPolicyComponent(""); - fixture.setPolicyName(""); - fixture.setDeleteCondition(DeletePolicyCondition.ALL); - fixture.setRequestID(UUID.randomUUID()); - fixture.setPdpGroup(""); - String policyName = ""; - - fixture.setPolicyName(policyName); - - // add additional test code here - } - - /** - * Run the void setRequestID(UUID) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetRequestID_1() - throws Exception { - DeletePolicyParameters fixture = new DeletePolicyParameters(); - fixture.setPolicyComponent(""); - fixture.setPolicyName(""); - fixture.setDeleteCondition(DeletePolicyCondition.ALL); - fixture.setRequestID(UUID.randomUUID()); - fixture.setPdpGroup(""); - UUID requestID = UUID.randomUUID(); - - fixture.setRequestID(requestID); - - // add additional test code here - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(DeletePolicyParametersTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/EventRequestParametersTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/EventRequestParametersTest.java deleted file mode 100644 index abfc31f8b..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/EventRequestParametersTest.java +++ /dev/null @@ -1,193 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import java.util.Hashtable; -import java.util.Map; -import java.util.UUID; - -import org.junit.*; -import org.openecomp.policy.api.EventRequestParameters; - -import static org.junit.Assert.*; - -/** - * The class EventRequestParametersTest contains tests for the class {@link EventRequestParameters}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class EventRequestParametersTest { - /** - * Run the EventRequestParameters() constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testEventRequestParameters_1() - throws Exception { - - EventRequestParameters result = new EventRequestParameters(); - - // add additional test code here - assertNotNull(result); - assertEquals(null, result.getEventAttributes()); - assertEquals(null, result.getRequestID()); - } - - /** - * Run the EventRequestParameters(Map,UUID) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testEventRequestParameters_2() - throws Exception { - Map eventAttributes = new Hashtable(); - UUID requestID = UUID.randomUUID(); - - EventRequestParameters result = new EventRequestParameters(eventAttributes, requestID); - - // add additional test code here - assertNotNull(result); - } - - /** - * Run the Map getEventAttributes() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetEventAttributes_1() - throws Exception { - EventRequestParameters fixture = new EventRequestParameters(new Hashtable(), UUID.randomUUID()); - - Map result = fixture.getEventAttributes(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the UUID getRequestID() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetRequestID_1() - throws Exception { - EventRequestParameters fixture = new EventRequestParameters(new Hashtable(), UUID.fromString("5b15376d-569b-4772-ac75-9362043f6a6c")); - - UUID result = fixture.getRequestID(); - - // add additional test code here - assertNotNull(result); - assertEquals("5b15376d-569b-4772-ac75-9362043f6a6c", result.toString()); - assertEquals(4, result.version()); - assertEquals(2, result.variant()); - assertEquals(-6019743277723456916L, result.getLeastSignificantBits()); - assertEquals(6563212974706345842L, result.getMostSignificantBits()); - } - - /** - * Run the void setEventAttributes(Map) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetEventAttributes_1() - throws Exception { - EventRequestParameters fixture = new EventRequestParameters(new Hashtable(), UUID.randomUUID()); - Map eventAttributes = new Hashtable(); - - fixture.setEventAttributes(eventAttributes); - - // add additional test code here - } - - /** - * Run the void setRequestID(UUID) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetRequestID_1() - throws Exception { - EventRequestParameters fixture = new EventRequestParameters(new Hashtable(), UUID.randomUUID()); - UUID requestID = UUID.randomUUID(); - - fixture.setRequestID(requestID); - - // add additional test code here - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(EventRequestParametersTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigByPolicyNameTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigByPolicyNameTest.java deleted file mode 100644 index 7bfa27c6e..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigByPolicyNameTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import java.util.Collection; - -import org.junit.Before; -import org.junit.Test; -import org.openecomp.policy.api.PolicyConfig; -import org.openecomp.policy.api.PolicyConfigException; -import org.openecomp.policy.api.PolicyEngine; -import org.openecomp.policy.api.PolicyEngineException; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -import junit.framework.TestCase; - -public class GetConfigByPolicyNameTest extends TestCase { - private PolicyEngine policyEngine = null; - private String policyName = null; - private Collection policyConfig = null; - private static final Logger logger = FlexLogger.getLogger(GetConfigByPolicyNameTest.class); - @Before - public void setUp() { - try { - policyEngine = new PolicyEngine("Test/config_pass.properties"); - } catch (PolicyEngineException e) { - logger.error(e.getMessage()); - fail("PolicyEngine Instantiation Error" + e); - } - logger.info("Loaded.. PolicyEngine"); - } - - @SuppressWarnings("deprecation") - @Test - public void testGetConfigPolicyNameNotValid(){ - policyName = null; - try{ - policyConfig = policyEngine.getConfigByPolicyName(policyName); - } catch (PolicyConfigException e){ - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigStringStringMapTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigStringStringMapTest.java deleted file mode 100644 index c5b7f8f6d..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigStringStringMapTest.java +++ /dev/null @@ -1,259 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.junit.Test; -import org.openecomp.policy.api.PolicyConfig; -import org.openecomp.policy.api.PolicyConfigException; -import org.openecomp.policy.api.PolicyConfigStatus; -import org.openecomp.policy.api.PolicyEngine; -import org.openecomp.policy.api.PolicyEngineException; -import org.openecomp.policy.api.PolicyType; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -public class GetConfigStringStringMapTest { - - private PolicyEngine policyEngine = null; - private String eCOMPComponentName = null; - private String configName = null; - private Map configAttributes = new HashMap(); - private Collection policyConfig = null; - private static final Logger logger = FlexLogger.getLogger(GetConfigStringStringMapTest.class); - @Before - public void setUp() { - try { - policyEngine = new PolicyEngine("Test/config_pass.properties"); - } catch (PolicyEngineException e) { - logger.error(e.getMessage()); - fail("PolicyEngine Instantiation Error" + e); - } - logger.info("Loaded.. PolicyEngine"); - } - - @SuppressWarnings("deprecation") - @Test - public void testGetConfigStringStringMapFail() { - eCOMPComponentName = null; - configName = null; - configAttributes = null; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName, configAttributes); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - @SuppressWarnings("deprecation") - @Test - public void testGetConfigStringStringMapFail1() { - eCOMPComponentName = null; - configName = "testFail"; - configAttributes.put("TestValue", "Fail"); - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName, configAttributes); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - @SuppressWarnings("deprecation") - @Test - public void testGetConfigStringStringMapFail2() { - eCOMPComponentName = "TestFail"; - configName = null; - configAttributes.put("TestValue", "Fail"); - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName, configAttributes); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - @SuppressWarnings("deprecation") - @Test - public void testGetConfigStringStringMapFail3() { - eCOMPComponentName = "TestFail"; - configName = "configFail"; - configAttributes= null; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName, configAttributes); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - @SuppressWarnings("deprecation") - @Test - public void testGetConfigStringStringMapfail4() { - eCOMPComponentName = "TestFail"; - configName = "configFail"; - configAttributes.put("", ""); - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName, configAttributes); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - //@Test - @SuppressWarnings("deprecation") - public void testGetConfigStringStringMapNotValid() { - eCOMPComponentName = "TestFail"; - configName = "configFail"; - configAttributes.put("Action:com.test.fail", "Value"); - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName, configAttributes); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - for(PolicyConfig policyConfig : this.policyConfig){ - logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig); - assertEquals(PolicyConfigStatus.CONFIG_NOT_FOUND,policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig.getPolicyConfigMessage()); - assertNull(policyConfig.getType()); - assertNull(policyConfig.toJSON()); - assertNull(policyConfig.toProperties()); - assertNull(policyConfig.toXML()); - assertNull(policyConfig.toOther()); - } - } - - //@Test - @SuppressWarnings("deprecation") - public void testGetConfigStringStringMapValidJSON() { - eCOMPComponentName = "JSON"; - configName = "JSONconfig"; - configAttributes.put("Resource.com:test:resource:json", "Test"); - configAttributes.put("Action.com:test:action:json", "TestJSON"); - configAttributes.put("Subject.com:test:subject:json", "TestSubject"); - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName, configAttributes); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - for(PolicyConfig policyConfig : this.policyConfig){ - logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig); - assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig.getPolicyConfigMessage()); - assertEquals(PolicyType.JSON,policyConfig.getType()); - assertNotNull(policyConfig.toJSON()); - assertNull(policyConfig.toProperties()); - assertNull(policyConfig.toXML()); - assertNull(policyConfig.toOther()); - } - } - - //@Test - @SuppressWarnings("deprecation") - public void testGetConfigStringStringMapValidXML() { - eCOMPComponentName = "XML"; - configName = "XMLconfig"; - configAttributes.put("Resource.com:test:resource:json", "Test"); - configAttributes.put("Action.com:test:action:json", "TestJSON"); - configAttributes.put("Subject.com:test:subject:json", "TestSubject"); - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName, configAttributes); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - for(PolicyConfig policyConfig : this.policyConfig){ - logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig); - assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig.getPolicyConfigMessage()); - assertEquals(PolicyType.XML,policyConfig.getType()); - assertNull(policyConfig.toJSON()); - assertNull(policyConfig.toProperties()); - assertNotNull(policyConfig.toXML()); - assertNull(policyConfig.toOther()); - } - } - - //@Test - @SuppressWarnings("deprecation") - public void testGetConfigStringStringMapValidProperties() { - eCOMPComponentName = "Properties"; - configName = "PropConfig" ; - configAttributes.put("Resource.com:test:resource:json", "Test"); - configAttributes.put("Action.com:test:action:json", "TestJSON"); - configAttributes.put("Subject.com:test:subject:json", "TestSubject"); - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName, configAttributes); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - for(PolicyConfig policyConfig : this.policyConfig){ - logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig); - assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig.getPolicyConfigMessage()); - assertEquals(PolicyType.PROPERTIES,policyConfig.getType()); - assertNull(policyConfig.toJSON()); - assertNotNull(policyConfig.toProperties()); - assertNull(policyConfig.toXML()); - assertNull(policyConfig.toOther()); - } - } - - //@Test - @SuppressWarnings("deprecation") - public void testGetConfigStringStringMapValidOther() { - eCOMPComponentName = "Other"; - configName = "OtherConfig" ; - configAttributes.put("Resource.com:test:resource:json", "Test"); - configAttributes.put("Action.com:test:action:json", "TestJSON"); - configAttributes.put("Subject.com:test:subject:json", "TestSubject"); - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName, configAttributes); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - for(PolicyConfig policyConfig : this.policyConfig){ - logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig); - assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig.getPolicyConfigMessage()); - assertEquals(PolicyType.OTHER,policyConfig.getType()); - assertNull(policyConfig.toJSON()); - assertNull(policyConfig.toProperties()); - assertNull(policyConfig.toXML()); - assertNotNull(policyConfig.toOther()); - } - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigStringStringTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigStringStringTest.java deleted file mode 100644 index b55abd734..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigStringStringTest.java +++ /dev/null @@ -1,213 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -import java.util.Collection; - -import org.junit.Before; -import org.junit.Test; -import org.openecomp.policy.api.PolicyConfig; -import org.openecomp.policy.api.PolicyConfigException; -import org.openecomp.policy.api.PolicyConfigStatus; -import org.openecomp.policy.api.PolicyEngine; -import org.openecomp.policy.api.PolicyEngineException; -import org.openecomp.policy.api.PolicyType; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -public class GetConfigStringStringTest { - - private PolicyEngine policyEngine = null; - private String eCOMPComponentName = null; - private String configName = null; - private Collection policyConfig = null; - private static final Logger logger = FlexLogger.getLogger(GetConfigStringStringTest.class); - @Before - public void setUp() { - try { - policyEngine = new PolicyEngine("Test/config_pass.properties"); - } catch (PolicyEngineException e) { - logger.error(e.getMessage()); - fail("PolicyEngine Instantiation Error" + e); - } - logger.info("Loaded.. PolicyEngine"); - } - - @SuppressWarnings("deprecation") - @Test - public void testGetConfigStringStringFail() { - eCOMPComponentName = null; - configName = null; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - @SuppressWarnings("deprecation") - @Test - public void testGetConfigStringStringFail1() { - eCOMPComponentName = null; - configName = ""; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - @SuppressWarnings("deprecation") - @Test - public void testGetConfigStringStringFail2() { - eCOMPComponentName = ""; - configName = null; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - //@Test - @SuppressWarnings("deprecation") - public void testGetConfigStringStringNotvalid() { - eCOMPComponentName = "fail"; - configName = "fail"; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - for(PolicyConfig policyConfig : this.policyConfig){ - logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig); - assertEquals(PolicyConfigStatus.CONFIG_NOT_FOUND,policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig.getPolicyConfigMessage()); - assertNull(policyConfig.getType()); - assertNull(policyConfig.toJSON()); - assertNull(policyConfig.toProperties()); - assertNull(policyConfig.toXML()); - assertNull(policyConfig.toOther()); - } - } - - //@Test - @SuppressWarnings("deprecation") - public void testGetConfigStringStringValidJSON() { - eCOMPComponentName = "JSON"; - configName = "JSONconfig"; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - for(PolicyConfig policyConfig : this.policyConfig){ - logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig); - assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig.getPolicyConfigMessage()); - assertEquals(PolicyType.JSON,policyConfig.getType()); - assertNotNull(policyConfig.toJSON()); - assertNull(policyConfig.toProperties()); - assertNull(policyConfig.toXML()); - assertNull(policyConfig.toOther()); - } - } - - //@Test - @SuppressWarnings("deprecation") - public void testGetConfigStringStringValidXML() { - eCOMPComponentName = "XML"; - configName = "XMLconfig"; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - for(PolicyConfig policyConfig : this.policyConfig){ - logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig); - assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig.getPolicyConfigMessage()); - assertEquals(PolicyType.XML,policyConfig.getType()); - assertNull(policyConfig.toJSON()); - assertNull(policyConfig.toProperties()); - assertNotNull(policyConfig.toXML()); - assertNull(policyConfig.toOther()); - } - } - - //@Test - @SuppressWarnings("deprecation") - public void testGetConfigStringStringValidProperties() { - eCOMPComponentName = "Properties"; - configName = "PropConfig" ; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - for(PolicyConfig policyConfig : this.policyConfig){ - logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig); - assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig.getPolicyConfigMessage()); - assertEquals(PolicyType.PROPERTIES,policyConfig.getType()); - assertNull(policyConfig.toJSON()); - assertNotNull(policyConfig.toProperties()); - assertNull(policyConfig.toXML()); - assertNull(policyConfig.toOther()); - } - } - - //@Test - @SuppressWarnings("deprecation") - public void testGetConfigStringStringValidOther() { - eCOMPComponentName = "Other"; - configName = "OtherConfig" ; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName, configName); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - for(PolicyConfig policyConfig : this.policyConfig){ - logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig); - assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig.getPolicyConfigMessage()); - assertEquals(PolicyType.OTHER,policyConfig.getType()); - assertNull(policyConfig.toJSON()); - assertNull(policyConfig.toProperties()); - assertNull(policyConfig.toXML()); - assertNotNull(policyConfig.toOther()); - } - } - -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigStringTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigStringTest.java deleted file mode 100644 index ffa1913aa..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/GetConfigStringTest.java +++ /dev/null @@ -1,170 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import java.util.Collection; - -import org.junit.Before; -import org.openecomp.policy.api.PolicyConfig; -import org.openecomp.policy.api.PolicyConfigException; -import org.openecomp.policy.api.PolicyEngine; -import org.openecomp.policy.api.PolicyEngineException; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -import junit.framework.TestCase; - -public class GetConfigStringTest extends TestCase{ - - private PolicyEngine policyEngine = null; - private String eCOMPComponentName = null; - private Collection policyConfig = null; - private static final Logger logger = FlexLogger.getLogger(GetConfigStringTest.class); - @Before - public void setUp() { - try { - policyEngine = new PolicyEngine("Test/config_pass.properties"); - } catch (PolicyEngineException e) { - logger.error(e.getMessage()); - fail("PolicyEngine Instantiation Error" + e); - } - logger.info("Loaded.. PolicyEngine"); - } - - //@Test - @SuppressWarnings("deprecation") - public void testGetConfigStringFail() { - eCOMPComponentName = null; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - /*@Test - public void testGetConfigStringNotvalid() { - eCOMPComponentName = "fail"; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - for(PolicyConfig policyConfig : this.policyConfig){ - logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig); - assertEquals(PolicyConfigStatus.CONFIG_NOT_FOUND,policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig.getPolicyConfigMessage()); - assertNull(policyConfig.getType()); - assertNull(policyConfig.toJSON()); - assertNull(policyConfig.toProperties()); - assertNull(policyConfig.toXML()); - assertNull(policyConfig.toOther()); - } - } - */ - - /*@Test - public void testGetConfigStringValidJSON() { - eCOMPComponentName = "JSON"; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - for(PolicyConfig policyConfig : this.policyConfig){ - logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig); - assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig.getPolicyConfigMessage()); - assertEquals(PolicyType.JSON,policyConfig.getType()); - assertNotNull(policyConfig.toJSON()); - assertNull(policyConfig.toProperties()); - assertNull(policyConfig.toXML()); - assertNull(policyConfig.toOther()); - } - } - */ - /*@Test - public void testGetConfigStringValidXML() { - eCOMPComponentName = "XML"; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - for(PolicyConfig policyConfig : this.policyConfig){ - logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig); - assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig.getPolicyConfigMessage()); - assertEquals(PolicyType.XML,policyConfig.getType()); - assertNull(policyConfig.toJSON()); - assertNull(policyConfig.toProperties()); - assertNotNull(policyConfig.toXML()); - assertNull(policyConfig.toOther()); - } - } - */ - /*@Test - public void testGetConfigStringValidProperties() { - eCOMPComponentName = "Properties"; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - for(PolicyConfig policyConfig : this.policyConfig){ - logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig); - assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig.getPolicyConfigMessage()); - assertEquals(PolicyType.PROPERTIES,policyConfig.getType()); - assertNull(policyConfig.toJSON()); - assertNotNull(policyConfig.toProperties()); - assertNull(policyConfig.toXML()); - assertNull(policyConfig.toOther()); - } - } - */ - /*@Test - public void testGetConfigStringValidOther() { - eCOMPComponentName = "Other"; - try { - policyConfig = policyEngine.getConfig(eCOMPComponentName); - } catch (PolicyConfigException e) { - logger.warn(e.getMessage()); - } - for(PolicyConfig policyConfig : this.policyConfig){ - logger.info(policyConfig.getPolicyConfigMessage() + " , " +policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig); - assertEquals(PolicyConfigStatus.CONFIG_RETRIEVED,policyConfig.getPolicyConfigStatus()); - assertNotNull(policyConfig.getPolicyConfigMessage()); - assertEquals(PolicyType.OTHER,policyConfig.getType()); - assertNull(policyConfig.toJSON()); - assertNull(policyConfig.toProperties()); - assertNull(policyConfig.toXML()); - assertNotNull(policyConfig.toOther()); - } - } - */ -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ImportParametersTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ImportParametersTest.java deleted file mode 100644 index 3719b5d2f..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/ImportParametersTest.java +++ /dev/null @@ -1,403 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.util.UUID; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.policy.api.ImportParameters; - -/** - * The class ImportParametersTest contains tests for the class {@link ImportParameters}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class ImportParametersTest { - /** - * Run the String getDescription() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetDescription_1() - throws Exception { - ImportParameters fixture = new ImportParameters(); - fixture.setFilePath(""); - fixture.setVersion(""); - fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); - fixture.setRequestID(UUID.randomUUID()); - fixture.setDescription(""); - fixture.setServiceName(""); - - String result = fixture.getDescription(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getFilePath() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetFilePath_1() - throws Exception { - ImportParameters fixture = new ImportParameters(); - fixture.setFilePath(""); - fixture.setVersion(""); - fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); - fixture.setRequestID(UUID.randomUUID()); - fixture.setDescription(""); - fixture.setServiceName(""); - - String result = fixture.getFilePath(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the UUID getRequestID() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetRequestID_1() - throws Exception { - ImportParameters fixture = new ImportParameters(); - fixture.setFilePath(""); - fixture.setVersion(""); - fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); - fixture.setRequestID(UUID.fromString("731dca0a-fe99-456c-8ad2-87cff8437b2f")); - fixture.setDescription(""); - fixture.setServiceName(""); - - UUID result = fixture.getRequestID(); - - // add additional test code here - assertNotNull(result); - assertEquals("731dca0a-fe99-456c-8ad2-87cff8437b2f", result.toString()); - assertEquals(4, result.version()); - assertEquals(2, result.variant()); - assertEquals(-8443537024073106641L, result.getLeastSignificantBits()); - assertEquals(8295008237256263020L, result.getMostSignificantBits()); - } - - /** - * Run the String getServiceName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetServiceName_1() - throws Exception { - ImportParameters fixture = new ImportParameters(); - fixture.setFilePath(""); - fixture.setVersion(""); - fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); - fixture.setRequestID(UUID.randomUUID()); - fixture.setDescription(""); - fixture.setServiceName(""); - - String result = fixture.getServiceName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the ImportParameters.IMPORT_TYPE getServiceType() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetServiceType_1() - throws Exception { - ImportParameters fixture = new ImportParameters(); - fixture.setFilePath(""); - fixture.setVersion(""); - fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); - fixture.setRequestID(UUID.randomUUID()); - fixture.setDescription(""); - fixture.setServiceName(""); - - ImportParameters.IMPORT_TYPE result = fixture.getServiceType(); - - // add additional test code here - assertNotNull(result); - assertEquals("MICROSERVICE", result.name()); - assertEquals("MICROSERVICE", result.toString()); - assertEquals(0, result.ordinal()); - } - - /** - * Run the String getVersion() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetVersion_1() - throws Exception { - ImportParameters fixture = new ImportParameters(); - fixture.setFilePath(""); - fixture.setVersion(""); - fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); - fixture.setRequestID(UUID.randomUUID()); - fixture.setDescription(""); - fixture.setServiceName(""); - - String result = fixture.getVersion(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the void setDescription(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetDescription_1() - throws Exception { - ImportParameters fixture = new ImportParameters(); - fixture.setFilePath(""); - fixture.setVersion(""); - fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); - fixture.setRequestID(UUID.randomUUID()); - fixture.setDescription(""); - fixture.setServiceName(""); - String description = ""; - - fixture.setDescription(description); - - // add additional test code here - } - - /** - * Run the void setFilePath(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetFilePath_1() - throws Exception { - ImportParameters fixture = new ImportParameters(); - fixture.setFilePath(""); - fixture.setVersion(""); - fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); - fixture.setRequestID(UUID.randomUUID()); - fixture.setDescription(""); - fixture.setServiceName(""); - String filePath = ""; - - fixture.setFilePath(filePath); - - // add additional test code here - } - - /** - * Run the void setImportParameters(String,String,UUID,String,IMPORT_TYPE,String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetImportParameters_1() - throws Exception { - ImportParameters fixture = new ImportParameters(); - fixture.setFilePath(""); - fixture.setVersion(""); - fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); - fixture.setRequestID(UUID.randomUUID()); - fixture.setDescription(""); - fixture.setServiceName(""); - String serviceName = ""; - String description = ""; - UUID requestID = UUID.randomUUID(); - String filePath = ""; - ImportParameters.IMPORT_TYPE importType = ImportParameters.IMPORT_TYPE.MICROSERVICE; - String version = ""; - - fixture.setImportParameters(serviceName, description, requestID, filePath, importType, version); - - // add additional test code here - } - - /** - * Run the void setRequestID(UUID) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetRequestID_1() - throws Exception { - ImportParameters fixture = new ImportParameters(); - fixture.setFilePath(""); - fixture.setVersion(""); - fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); - fixture.setRequestID(UUID.randomUUID()); - fixture.setDescription(""); - fixture.setServiceName(""); - UUID requestID = UUID.randomUUID(); - - fixture.setRequestID(requestID); - - // add additional test code here - } - - /** - * Run the void setServiceName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetServiceName_1() - throws Exception { - ImportParameters fixture = new ImportParameters(); - fixture.setFilePath(""); - fixture.setVersion(""); - fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); - fixture.setRequestID(UUID.randomUUID()); - fixture.setDescription(""); - fixture.setServiceName(""); - String serviceName = ""; - - fixture.setServiceName(serviceName); - - // add additional test code here - } - - /** - * Run the void setServiceType(IMPORT_TYPE) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetServiceType_1() - throws Exception { - ImportParameters fixture = new ImportParameters(); - fixture.setFilePath(""); - fixture.setVersion(""); - fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); - fixture.setRequestID(UUID.randomUUID()); - fixture.setDescription(""); - fixture.setServiceName(""); - ImportParameters.IMPORT_TYPE enumImportType = ImportParameters.IMPORT_TYPE.MICROSERVICE; - - fixture.setServiceType(enumImportType); - - // add additional test code here - } - - /** - * Run the void setVersion(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetVersion_1() - throws Exception { - ImportParameters fixture = new ImportParameters(); - fixture.setFilePath(""); - fixture.setVersion(""); - fixture.setServiceType(ImportParameters.IMPORT_TYPE.MICROSERVICE); - fixture.setRequestID(UUID.randomUUID()); - fixture.setDescription(""); - fixture.setServiceName(""); - String version = ""; - - fixture.setVersion(version); - - // add additional test code here - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(ImportParametersTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/LoadedPolicyTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/LoadedPolicyTest.java deleted file mode 100644 index 0748d0ad9..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/LoadedPolicyTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.After; -import org.junit.Before; -import org.openecomp.policy.api.LoadedPolicy; - -/** - * The class LoadedPolicyTest contains tests for the class {@link LoadedPolicy}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class LoadedPolicyTest { - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(LoadedPolicyTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/NotificationHandlerTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/NotificationHandlerTest.java deleted file mode 100644 index 68ba3a773..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/NotificationHandlerTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.After; -import org.junit.Before; -import org.openecomp.policy.api.NotificationHandler; - -/** - * The class NotificationHandlerTest contains tests for the class {@link NotificationHandler}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class NotificationHandlerTest { - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(NotificationHandlerTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/NotificationSchemeTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/NotificationSchemeTest.java deleted file mode 100644 index 1cb105c2f..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/NotificationSchemeTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.*; -import org.openecomp.policy.api.NotificationScheme; - -import static org.junit.Assert.*; - -/** - * The class NotificationSchemeTest contains tests for the class {@link NotificationScheme}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class NotificationSchemeTest { - /** - * Run the String toString() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testToString_1() - throws Exception { - NotificationScheme fixture = NotificationScheme.AUTO_ALL_NOTIFICATIONS; - - String result = fixture.toString(); - - // add additional test code here - assertEquals("auto_all_notifications", result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(NotificationSchemeTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/NotificationTypeTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/NotificationTypeTest.java deleted file mode 100644 index 95dce6a60..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/NotificationTypeTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.*; -import org.openecomp.policy.api.NotificationType; - -import static org.junit.Assert.*; - -/** - * The class NotificationTypeTest contains tests for the class {@link NotificationType}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class NotificationTypeTest { - /** - * Run the String toString() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testToString_1() - throws Exception { - NotificationType fixture = NotificationType.BOTH; - - String result = fixture.toString(); - - // add additional test code here - assertEquals("both", result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(NotificationTypeTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PDPNotificationTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PDPNotificationTest.java deleted file mode 100644 index 43754f8df..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PDPNotificationTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.After; -import org.junit.Before; -import org.openecomp.policy.api.PDPNotification; - -/** - * The class PDPNotificationTest contains tests for the class {@link PDPNotification}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class PDPNotificationTest { - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PDPNotificationTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyChangeResponseTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyChangeResponseTest.java deleted file mode 100644 index d36ae44c2..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyChangeResponseTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.After; -import org.junit.Before; -import org.openecomp.policy.api.PolicyChangeResponse; - -/** - * The class PolicyChangeResponseTest contains tests for the class {@link PolicyChangeResponse}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class PolicyChangeResponseTest { - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PolicyChangeResponseTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyClassTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyClassTest.java deleted file mode 100644 index 28e5beefd..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyClassTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.*; -import org.openecomp.policy.api.PolicyClass; - -import static org.junit.Assert.*; - -/** - * The class PolicyClassTest contains tests for the class {@link PolicyClass}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class PolicyClassTest { - /** - * Run the String toString() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testToString_1() - throws Exception { - PolicyClass fixture = PolicyClass.Action; - - String result = fixture.toString(); - - // add additional test code here - assertEquals("Action", result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PolicyClassTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigExceptionTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigExceptionTest.java deleted file mode 100644 index 4134eacc2..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigExceptionTest.java +++ /dev/null @@ -1,183 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.*; -import org.openecomp.policy.api.PolicyConfigException; - -import static org.junit.Assert.*; - -/** - * The class PolicyConfigExceptionTest contains tests for the class {@link PolicyConfigException}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class PolicyConfigExceptionTest { - /** - * Run the PolicyConfigException() constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPolicyConfigException_1() - throws Exception { - - PolicyConfigException result = new PolicyConfigException(); - - // add additional test code here - assertNotNull(result); - assertEquals(null, result.getCause()); - assertEquals("org.openecomp.policy.api.PolicyConfigException", result.toString()); - assertEquals(null, result.getLocalizedMessage()); - assertEquals(null, result.getMessage()); - } - - /** - * Run the PolicyConfigException(String) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPolicyConfigException_2() - throws Exception { - String message = ""; - - PolicyConfigException result = new PolicyConfigException(message); - - // add additional test code here - assertNotNull(result); - assertEquals(null, result.getCause()); - assertEquals("org.openecomp.policy.api.PolicyConfigException: ", result.toString()); - assertEquals("", result.getLocalizedMessage()); - assertEquals("", result.getMessage()); - } - - /** - * Run the PolicyConfigException(Throwable) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPolicyConfigException_3() - throws Exception { - Throwable cause = new Throwable(); - - PolicyConfigException result = new PolicyConfigException(cause); - - // add additional test code here - assertNotNull(result); - assertEquals("org.openecomp.policy.api.PolicyConfigException: java.lang.Throwable", result.toString()); - assertEquals("java.lang.Throwable", result.getLocalizedMessage()); - assertEquals("java.lang.Throwable", result.getMessage()); - } - - /** - * Run the PolicyConfigException(String,Throwable) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPolicyConfigException_4() - throws Exception { - String message = ""; - Throwable cause = new Throwable(); - - PolicyConfigException result = new PolicyConfigException(message, cause); - - // add additional test code here - assertNotNull(result); - assertEquals("org.openecomp.policy.api.PolicyConfigException: ", result.toString()); - assertEquals("", result.getLocalizedMessage()); - assertEquals("", result.getMessage()); - } - - /** - * Run the PolicyConfigException(String,Throwable,boolean,boolean) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPolicyConfigException_5() - throws Exception { - String message = ""; - Throwable cause = new Throwable(); - boolean enableSuppression = true; - boolean writableStackTrace = true; - - PolicyConfigException result = new PolicyConfigException(message, cause, enableSuppression, writableStackTrace); - - // add additional test code here - assertNotNull(result); - assertEquals("org.openecomp.policy.api.PolicyConfigException: ", result.toString()); - assertEquals("", result.getLocalizedMessage()); - assertEquals("", result.getMessage()); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PolicyConfigExceptionTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigStatusTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigStatusTest.java deleted file mode 100644 index c40253890..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigStatusTest.java +++ /dev/null @@ -1,133 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.*; -import org.openecomp.policy.api.PolicyConfigStatus; - -import static org.junit.Assert.*; - -/** - * The class PolicyConfigStatusTest contains tests for the class {@link PolicyConfigStatus}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class PolicyConfigStatusTest { - /** - * Run the PolicyConfigStatus getStatus(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetStatus_1() - throws Exception { - String configStatus = ""; - - PolicyConfigStatus result = PolicyConfigStatus.getStatus(configStatus); - - // add additional test code here - assertNotNull(result); - assertEquals("not_found", result.toString()); - assertEquals("CONFIG_NOT_FOUND", result.name()); - assertEquals(1, result.ordinal()); - } - - /** - * Run the PolicyConfigStatus getStatus(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetStatus_2() - throws Exception { - String configStatus = ""; - - PolicyConfigStatus result = PolicyConfigStatus.getStatus(configStatus); - - // add additional test code here - assertNotNull(result); - assertEquals("not_found", result.toString()); - assertEquals("CONFIG_NOT_FOUND", result.name()); - assertEquals(1, result.ordinal()); - } - - /** - * Run the String toString() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testToString_1() - throws Exception { - PolicyConfigStatus fixture = PolicyConfigStatus.CONFIG_NOT_FOUND; - - String result = fixture.toString(); - - // add additional test code here - assertEquals("not_found", result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PolicyConfigStatusTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigTest.java deleted file mode 100644 index c6247fcdf..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.After; -import org.junit.Before; -import org.openecomp.policy.api.PolicyConfig; - -/** - * The class PolicyConfigTest contains tests for the class {@link PolicyConfig}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class PolicyConfigTest { - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PolicyConfigTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigTypeTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigTypeTest.java deleted file mode 100644 index cd6c6a977..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyConfigTypeTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.*; -import org.openecomp.policy.api.PolicyConfigType; - -import static org.junit.Assert.*; - -/** - * The class PolicyConfigTypeTest contains tests for the class {@link PolicyConfigType}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class PolicyConfigTypeTest { - /** - * Run the String toString() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testToString_1() - throws Exception { - PolicyConfigType fixture = PolicyConfigType.BRMS_PARAM; - - String result = fixture.toString(); - - // add additional test code here - assertEquals("BRMS_Param", result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PolicyConfigTypeTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyDecisionExceptionTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyDecisionExceptionTest.java deleted file mode 100644 index 95dfd7acd..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyDecisionExceptionTest.java +++ /dev/null @@ -1,183 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.*; -import org.openecomp.policy.api.PolicyDecisionException; - -import static org.junit.Assert.*; - -/** - * The class PolicyDecisionExceptionTest contains tests for the class {@link PolicyDecisionException}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class PolicyDecisionExceptionTest { - /** - * Run the PolicyDecisionException() constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPolicyDecisionException_1() - throws Exception { - - PolicyDecisionException result = new PolicyDecisionException(); - - // add additional test code here - assertNotNull(result); - assertEquals(null, result.getCause()); - assertEquals("org.openecomp.policy.api.PolicyDecisionException", result.toString()); - assertEquals(null, result.getLocalizedMessage()); - assertEquals(null, result.getMessage()); - } - - /** - * Run the PolicyDecisionException(String) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPolicyDecisionException_2() - throws Exception { - String message = ""; - - PolicyDecisionException result = new PolicyDecisionException(message); - - // add additional test code here - assertNotNull(result); - assertEquals(null, result.getCause()); - assertEquals("org.openecomp.policy.api.PolicyDecisionException: ", result.toString()); - assertEquals("", result.getLocalizedMessage()); - assertEquals("", result.getMessage()); - } - - /** - * Run the PolicyDecisionException(Throwable) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPolicyDecisionException_3() - throws Exception { - Throwable cause = new Throwable(); - - PolicyDecisionException result = new PolicyDecisionException(cause); - - // add additional test code here - assertNotNull(result); - assertEquals("org.openecomp.policy.api.PolicyDecisionException: java.lang.Throwable", result.toString()); - assertEquals("java.lang.Throwable", result.getLocalizedMessage()); - assertEquals("java.lang.Throwable", result.getMessage()); - } - - /** - * Run the PolicyDecisionException(String,Throwable) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPolicyDecisionException_4() - throws Exception { - String message = ""; - Throwable cause = new Throwable(); - - PolicyDecisionException result = new PolicyDecisionException(message, cause); - - // add additional test code here - assertNotNull(result); - assertEquals("org.openecomp.policy.api.PolicyDecisionException: ", result.toString()); - assertEquals("", result.getLocalizedMessage()); - assertEquals("", result.getMessage()); - } - - /** - * Run the PolicyDecisionException(String,Throwable,boolean,boolean) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPolicyDecisionException_5() - throws Exception { - String message = ""; - Throwable cause = new Throwable(); - boolean enableSuppression = true; - boolean writableStackTrace = true; - - PolicyDecisionException result = new PolicyDecisionException(message, cause, enableSuppression, writableStackTrace); - - // add additional test code here - assertNotNull(result); - assertEquals("org.openecomp.policy.api.PolicyDecisionException: ", result.toString()); - assertEquals("", result.getLocalizedMessage()); - assertEquals("", result.getMessage()); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PolicyDecisionExceptionTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyDecisionTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyDecisionTest.java deleted file mode 100644 index 12069abeb..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyDecisionTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.*; -import org.openecomp.policy.api.PolicyDecision; - -import static org.junit.Assert.*; - -/** - * The class PolicyDecisionTest contains tests for the class {@link PolicyDecision}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class PolicyDecisionTest { - /** - * Run the String toString() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testToString_1() - throws Exception { - PolicyDecision fixture = PolicyDecision.DENY; - - String result = fixture.toString(); - - // add additional test code here - assertEquals("deny", result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PolicyDecisionTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEngineExceptionTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEngineExceptionTest.java deleted file mode 100644 index d21fb12e2..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEngineExceptionTest.java +++ /dev/null @@ -1,183 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.*; -import org.openecomp.policy.api.PolicyEngineException; - -import static org.junit.Assert.*; - -/** - * The class PolicyEngineExceptionTest contains tests for the class {@link PolicyEngineException}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class PolicyEngineExceptionTest { - /** - * Run the PolicyEngineException() constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testPolicyEngineException_1() - throws Exception { - - PolicyEngineException result = new PolicyEngineException(); - - // add additional test code here - assertNotNull(result); - assertEquals(null, result.getCause()); - assertEquals("org.openecomp.policy.api.PolicyEngineException", result.toString()); - assertEquals(null, result.getLocalizedMessage()); - assertEquals(null, result.getMessage()); - } - - /** - * Run the PolicyEngineException(String) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testPolicyEngineException_2() - throws Exception { - String message = ""; - - PolicyEngineException result = new PolicyEngineException(message); - - // add additional test code here - assertNotNull(result); - assertEquals(null, result.getCause()); - assertEquals("org.openecomp.policy.api.PolicyEngineException: ", result.toString()); - assertEquals("", result.getLocalizedMessage()); - assertEquals("", result.getMessage()); - } - - /** - * Run the PolicyEngineException(Throwable) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testPolicyEngineException_3() - throws Exception { - Throwable cause = new Throwable(); - - PolicyEngineException result = new PolicyEngineException(cause); - - // add additional test code here - assertNotNull(result); - assertEquals("org.openecomp.policy.api.PolicyEngineException: java.lang.Throwable", result.toString()); - assertEquals("java.lang.Throwable", result.getLocalizedMessage()); - assertEquals("java.lang.Throwable", result.getMessage()); - } - - /** - * Run the PolicyEngineException(String,Throwable) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testPolicyEngineException_4() - throws Exception { - String message = ""; - Throwable cause = new Throwable(); - - PolicyEngineException result = new PolicyEngineException(message, cause); - - // add additional test code here - assertNotNull(result); - assertEquals("org.openecomp.policy.api.PolicyEngineException: ", result.toString()); - assertEquals("", result.getLocalizedMessage()); - assertEquals("", result.getMessage()); - } - - /** - * Run the PolicyEngineException(String,Throwable,boolean,boolean) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testPolicyEngineException_5() - throws Exception { - String message = ""; - Throwable cause = new Throwable(); - boolean enableSuppression = true; - boolean writableStackTrace = true; - - PolicyEngineException result = new PolicyEngineException(message, cause, enableSuppression, writableStackTrace); - - // add additional test code here - assertNotNull(result); - assertEquals("org.openecomp.policy.api.PolicyEngineException: ", result.toString()); - assertEquals("", result.getLocalizedMessage()); - assertEquals("", result.getMessage()); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PolicyEngineExceptionTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEngineInterfaceTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEngineInterfaceTest.java deleted file mode 100644 index fd5f65fa3..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEngineInterfaceTest.java +++ /dev/null @@ -1,670 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import java.io.StringReader; -import java.net.HttpURLConnection; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import javax.json.Json; -import javax.json.JsonObject; -import javax.json.JsonReader; - -import org.mockito.Mockito; -import org.openecomp.policy.api.AttributeType; -import org.openecomp.policy.api.ConfigRequestParameters; -import org.openecomp.policy.api.DecisionRequestParameters; -import org.openecomp.policy.api.DecisionResponse; -import org.openecomp.policy.api.DeletePolicyCondition; -import org.openecomp.policy.api.DeletePolicyParameters; -import org.openecomp.policy.api.EventRequestParameters; -import org.openecomp.policy.api.ImportParameters; -import org.openecomp.policy.api.ImportParameters.IMPORT_TYPE; -import org.openecomp.policy.api.NotificationHandler; -import org.openecomp.policy.api.NotificationScheme; -import org.openecomp.policy.api.PDPNotification; -import org.openecomp.policy.api.PolicyChangeResponse; -import org.openecomp.policy.api.PolicyClass; -import org.openecomp.policy.api.PolicyConfig; -import org.openecomp.policy.api.PolicyConfigException; -import org.openecomp.policy.api.PolicyDecisionException; -import org.openecomp.policy.api.PolicyEngine; -import org.openecomp.policy.api.PolicyEngineException; -import org.openecomp.policy.api.PolicyEventException; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.api.PolicyResponse; -import org.openecomp.policy.api.PushPolicyParameters; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; -import org.openecomp.policy.std.StdPDPNotification; -import org.openecomp.policy.std.StdPolicyChangeResponse; -import org.openecomp.policy.std.StdPolicyResponse; - -import junit.framework.TestCase; - -/** - * The class PolicyEngineInterfaceTest contains tests for the - * class {@link PolicyEngine} - * - * @pattern JUnit Test Case - * - * @generatedBy CodePro at 5/27/16 10:33 AM - * - * - * @version $Revision$ - */ -public class PolicyEngineInterfaceTest extends TestCase { - - private static final Logger logger = FlexLogger.getLogger(PolicyEngineInterfaceTest.class); - - private PolicyEngine policyEngine = null; - private PolicyEngine mockPolicyEngine = null; - private Collection policyConfig = null; - private UUID requestID = UUID.randomUUID(); - - - PolicyChangeResponse result = null; - StdPolicyChangeResponse response = new StdPolicyChangeResponse(); - - - /** - * Construct new test instance - * - * @param name the test name - */ - public PolicyEngineInterfaceTest(String name) { - super(name); - } - - /** - * Perform pre-test initialization - * - * @throws Exception - * - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - try { - policyEngine = new PolicyEngine("Test/config_pass.properties"); - } catch (PolicyEngineException e) { - logger.error(e.getMessage()); - fail("PolicyEngine Instantiation Error" + e); - } - logger.info("Loaded.. PolicyEngine"); - - mockPolicyEngine = Mockito.mock(PolicyEngine.class); - HttpURLConnection conn = Mockito.mock(HttpURLConnection.class); - Mockito.when(conn.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); - - } - - /** - * Perform post-test clean up - * - * @throws Exception - * - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - // Add additional tear down code here - } - - /** - * Run the Collection getConfigByPolicyName(String) method - * test - */ - @SuppressWarnings("deprecation") - public void testGetConfigByPolicyName() { - String policyName = null; - try{ - policyConfig = policyEngine.getConfigByPolicyName(policyName); - } catch (PolicyConfigException e){ - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - @SuppressWarnings("deprecation") - public void testGetConfigByPolicyName2() { - String policyName = null; - - try{ - policyConfig = policyEngine.getConfigByPolicyName(policyName, requestID); - } catch (PolicyConfigException e){ - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - /** - * Run the Collection getConfig(String) method test - */ - @SuppressWarnings("deprecation") - public void testGetConfig() { - String ecompName = null; - - try{ - policyConfig = policyEngine.getConfig(ecompName); - } catch (PolicyConfigException e){ - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - @SuppressWarnings("deprecation") - public void testGetConfig2() { - String ecompName = null; - - try{ - policyConfig = policyEngine.getConfig(ecompName,requestID); - } catch (PolicyConfigException e){ - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - - @SuppressWarnings("deprecation") - public void testGetConfig3() { - String ecompName = null; - String configName = null; - - try{ - policyConfig = policyEngine.getConfig(ecompName,configName,requestID); - } catch (PolicyConfigException e){ - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - @SuppressWarnings("deprecation") - public void testGetConfig4() { - String ecompName = null; - String configName = null; - Map configAttributes = null; - - try{ - policyConfig = policyEngine.getConfig(ecompName,configName,configAttributes); - } catch (PolicyConfigException e){ - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - @SuppressWarnings("deprecation") - public void testGetConfig5() { - String ecompName = null; - String configName = null; - Map configAttributes = null; - - try{ - policyConfig = policyEngine.getConfig(ecompName,configName,configAttributes,requestID); - } catch (PolicyConfigException e){ - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - public void testGetConfig6() { - ConfigRequestParameters parameters = new ConfigRequestParameters(); - - try{ - policyConfig = policyEngine.getConfig(parameters); - } catch (PolicyConfigException e){ - logger.warn(e.getMessage()); - } - assertNull(policyConfig); - } - - - /** - * Run the Collection sendEvent(Map) method - * test - */ - @SuppressWarnings("deprecation") - public void testSendEvent() - { - Collection result = null; - Collection response = null; - Map eventAttributes = null; - - try { - Mockito.when(mockPolicyEngine.sendEvent(eventAttributes)).thenReturn(result); - result = mockPolicyEngine.sendEvent(eventAttributes); - } catch (PolicyEventException e) { - logger.error("Exception Occured"+e); - } - - - assertEquals(result,response); - - } - - @SuppressWarnings("deprecation") - public void testSendEvent2() - { - Collection result = null; - Collection response = null; - Map eventAttributes = null; - - try { - Mockito.when(mockPolicyEngine.sendEvent(eventAttributes,requestID)).thenReturn(result); - result = mockPolicyEngine.sendEvent(eventAttributes,requestID); - } catch (PolicyEventException e) { - logger.error("Exception Occured"+e); - } - - - assertEquals(result,response); - - } - - public void testSendEvent3() - { - Collection result = null; - Collection response = null; - EventRequestParameters parameters = new EventRequestParameters(); - - try { - Mockito.when(mockPolicyEngine.sendEvent(parameters)).thenReturn(result); - result = mockPolicyEngine.sendEvent(parameters); - } catch (PolicyEventException e) { - logger.error("Exception Occured"+e); - } - - assertEquals(result,response); - - } - - - - /** - * Run the PolicyDecision getDecision(String, Map) method - * test - */ - @SuppressWarnings("deprecation") - public void testGetDecision() - { - String eCOMPComponentName = null; - Map decisionAttributes = null; - - DecisionResponse result = null; - - try { - Mockito.when(mockPolicyEngine.getDecision(eCOMPComponentName,decisionAttributes)).thenReturn(null); - result = mockPolicyEngine.getDecision(eCOMPComponentName,decisionAttributes); - } catch (PolicyDecisionException e) { - logger.error("Exception Occured"+e); - } - - assertEquals(result,null); - } - - @SuppressWarnings("deprecation") - public void testGetDecision2() - { - String eCOMPComponentName = null; - Map decisionAttributes = null; - - DecisionResponse result = null; - - try { - Mockito.when(mockPolicyEngine.getDecision(eCOMPComponentName,decisionAttributes,requestID)).thenReturn(null); - result = mockPolicyEngine.getDecision(eCOMPComponentName,decisionAttributes); - } catch (PolicyDecisionException e) { - logger.error("Exception Occured"+e); - } - - assertEquals(result,null); - } - - public void testGetDecision3() - { - DecisionRequestParameters parameters = new DecisionRequestParameters(); - DecisionResponse result = null; - - try { - Mockito.when(mockPolicyEngine.getDecision(parameters)).thenReturn(null); - result = mockPolicyEngine.getDecision(parameters); - } catch (PolicyDecisionException e) { - logger.error("Exception Occured"+e); - } - - assertEquals(result,null); - } - - /** - * Run the void setNotification(NotificationScheme, NotificationHandler) - * method test - */ - public void testSetNotification() { - // add test code here - - NotificationScheme scheme = null; - NotificationHandler handler = null; - - Mockito.doNothing().when(mockPolicyEngine).setNotification(scheme, handler); - mockPolicyEngine.setNotification(scheme, handler); - //assertTrue(true); - } - - /** - * Run the void clearNotification() method test - */ - public void testClearNotification() { - // add test code here - - Mockito.doNothing().when(mockPolicyEngine).clearNotification(); - mockPolicyEngine.clearNotification(); - //assertTrue(true); - } - - /** - * Run the void setScheme(NotificationScheme) method test - */ - public void testSetScheme() { - NotificationScheme scheme = null; - - Mockito.doNothing().when(mockPolicyEngine).setScheme(scheme); - mockPolicyEngine.setScheme(scheme); - //assertTrue(true); - } - - /** - * Run the PDPNotification getNotification() method test - */ - public void testGetNotification() { - PDPNotification result = null; - StdPDPNotification response = null; - Mockito.when(mockPolicyEngine.getNotification()).thenReturn(response); - result = mockPolicyEngine.getNotification(); - - assertEquals(result,response); - } - - /** - * Run the String createConfigPolicy(String, String, String, String, - * Map, String, String, String, UUID) method test - */ - @SuppressWarnings("deprecation") - public void testCreateConfigPolicy() - { - String response = "success"; - String result = null; - try { - - Mockito.when(mockPolicyEngine.createConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null)).thenReturn(response); - result = mockPolicyEngine.createConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - /** - * Run the String updateConfigPolicy(String, String, String, String, - * Map, String, String, String, UUID) method test - */ - @SuppressWarnings("deprecation") - public void testUpdateConfigPolicy() - { - String response = "success"; - String result = null; - try { - - Mockito.when(mockPolicyEngine.updateConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null)).thenReturn(response); - result = mockPolicyEngine.updateConfigPolicy("testPolicy","test","test","testConfig",null,"OTHER","test","test",null, null, null, null, null); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - /** - * Run the String createConfigFirewallPolicy(String, JsonObject, String, - * UUID) method test - */ - @SuppressWarnings("deprecation") - public void testCreateConfigFirewallPolicy() { - String response = "success"; - String result = null; - String json = "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"rule1607\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"/v0/firewall/pan\",\"serviceGroups\":[{\"name\":\"1607Group\",\"description\":null,\"members\":[{\"type\":\"REFERENCE\",\"name\":\"SList\"},{\"type\":\"REFERENCE\",\"name\":\"Syslog\"}]},{\"name\":\"Syslog\",\"description\":\"NA\",\"type\":\"SERVICE\",\"transportProtocol\":\"udp\",\"appProtocol\":null,\"ports\":\"514\"},{\"name\":\"SList\",\"description\":\"Service List\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"8080\"}],\"addressGroups\":[{\"name\":\"1607Group\",\"description\":null,\"members\":[{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"},{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"}]},{\"name\":\"PL_CCE3\",\"description\":\"CCE Routers\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"1607Rule\",\"fromZones\":[\"Trusted\"],\"toZones\":[\"Untrusted\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"value\":\"PL_CCE3\"},{\"type\":\"REFERENCE\",\"value\":\"1607Group\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"value\":\"1607Group\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"1607Group\"}],\"action\":\"accept\",\"description\":\"Rule for 1607 templates\",\"enabled\":true,\"log\":true}]}"; - JsonObject jsonObj = buildJSON(json); - try { - - Mockito.when(mockPolicyEngine.createConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null)).thenReturn(response); - result = mockPolicyEngine.createConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - /** - * Run the String updateConfigFirewallPolicy(String, JsonObject, String, - * UUID) method test - */ - @SuppressWarnings("deprecation") - public void testUpdateConfigFirewallPolicy() { - String response = "success"; - String result = null; - String json = "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"rule1607\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"/v0/firewall/pan\",\"serviceGroups\":[{\"name\":\"1607Group\",\"description\":null,\"members\":[{\"type\":\"REFERENCE\",\"name\":\"SList\"},{\"type\":\"REFERENCE\",\"name\":\"Syslog\"}]},{\"name\":\"Syslog\",\"description\":\"NA\",\"type\":\"SERVICE\",\"transportProtocol\":\"udp\",\"appProtocol\":null,\"ports\":\"514\"},{\"name\":\"SList\",\"description\":\"Service List\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"8080\"}],\"addressGroups\":[{\"name\":\"1607Group\",\"description\":null,\"members\":[{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"},{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"}]},{\"name\":\"PL_CCE3\",\"description\":\"CCE Routers\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"10.11.12.13/14\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"1607Rule\",\"fromZones\":[\"Trusted\"],\"toZones\":[\"Untrusted\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"value\":\"PL_CCE3\"},{\"type\":\"REFERENCE\",\"value\":\"1607Group\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"value\":\"1607Group\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"1607Group\"}],\"action\":\"accept\",\"description\":\"Rule for 1607 templates\",\"enabled\":true,\"log\":true}]}"; - JsonObject jsonObj = buildJSON(json); - try { - - Mockito.when(mockPolicyEngine.updateConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null)).thenReturn(response); - result = mockPolicyEngine.updateConfigFirewallPolicy("testPolicy",jsonObj, "test", null, null, null, null, null); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - /** - * Run the PolicyChangeResponse createPolicy(PolicyParameters) method test - */ - public void testCreatePolicy() { - response.setResponseMessage("success"); - PolicyChangeResponse result = null; - PolicyParameters policyParameters = new PolicyParameters(); - - policyParameters.setPolicyClass(PolicyClass.Action); //required - policyParameters.setPolicyName("test.junitTest"); //required - policyParameters.setPolicyDescription("testing"); //optional - - //Set the Component Attributes... These are Optional - Map configAttributes = new HashMap(); - configAttributes.put("test", "testing"); - - Map> attributes = new HashMap>(); - attributes.put(AttributeType.MATCHING, configAttributes); - policyParameters.setAttributes(attributes); - - policyParameters.setActionPerformer("PEP"); - policyParameters.setActionAttribute("testing"); - policyParameters.setRequestID(UUID.randomUUID()); - - try { - - //stdPolicyEngine = Mockito.mock(StdPolicyEngine.class); - //Mockito.when(stdPolicyEngine.callPAP(newPAPPolicy, new String[] {"operation=create", "apiflag=api", "policyType=Action"}, null, "Action")).thenReturn(callPapResponse); - Mockito.when(mockPolicyEngine.createPolicy(policyParameters)).thenReturn(response); - result = mockPolicyEngine.createPolicy(policyParameters); - - } catch (Exception e) { - logger.warn(e.getMessage()); - logger.error("Exception Occured"+e); - } - assertEquals(result, response); - } - - /** - * Run the PolicyChangeResponse updatePolicy(PolicyParameters) method test - */ - public void testUpdatePolicy() { - response.setResponseMessage("success"); - PolicyChangeResponse result = null; - PolicyParameters policyParameters = new PolicyParameters(); - - policyParameters.setPolicyClass(PolicyClass.Action); //required - policyParameters.setPolicyName("test.junitTest"); //required - policyParameters.setPolicyDescription("testing"); //optional - - //Set the Component Attributes... These are Optional - Map configAttributes = new HashMap(); - configAttributes.put("test", "testing"); - - Map> attributes = new HashMap>(); - attributes.put(AttributeType.MATCHING, configAttributes); - policyParameters.setAttributes(attributes); - - policyParameters.setActionPerformer("PEP"); - policyParameters.setActionAttribute("testing"); - policyParameters.setRequestID(UUID.randomUUID()); - - try { - - Mockito.when(mockPolicyEngine.updatePolicy(policyParameters)).thenReturn(response); - result = mockPolicyEngine.updatePolicy(policyParameters); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - assertEquals(result, response); - } - - /** - * Run the String pushPolicy(String, String, String, String, UUID) method - * test - */ - @SuppressWarnings("deprecation") - public void testPushPolicy() { - String response = "Success"; - String result = null; - try { - - Mockito.when(mockPolicyEngine.pushPolicy("testing","test","Base","default",requestID)).thenReturn(response); - result = mockPolicyEngine.pushPolicy("testing","test","Base","default",requestID); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - - assertEquals(result, response); - } - - public void testPushPolicy2() { - PushPolicyParameters policyParameters = new PushPolicyParameters(); - PolicyChangeResponse result = null; - - //String policyScope = null; - policyParameters.setPolicyName("test.junitTest"); - policyParameters.setPolicyType("Action"); - policyParameters.setPdpGroup("Default"); - - try { - - Mockito.when(mockPolicyEngine.pushPolicy(policyParameters)).thenReturn(response); - result = mockPolicyEngine.pushPolicy(policyParameters); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - - assertEquals(result, response); - } - - /** - * Run the PolicyChangeResponse deletePolicy(DeletePolicyParameters) method - * test - */ - public void testDeletePolicy() { - DeletePolicyParameters policyParameters = new DeletePolicyParameters(); - PolicyChangeResponse result = null; - - //String policyScope = null; - policyParameters.setPolicyName("test.junitTest.1.xml"); - policyParameters.setDeleteCondition(DeletePolicyCondition.ALL); - policyParameters.setPolicyComponent("PAP"); - policyParameters.setPdpGroup("Default"); - - try { - - Mockito.when(mockPolicyEngine.deletePolicy(policyParameters)).thenReturn(response); - result = mockPolicyEngine.deletePolicy(policyParameters); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - - assertEquals(result, response); - } - - /** - * Run the PolicyChangeResponse policyEngineImport(ImportParameters) method - * test - */ - public void testPolicyEngineImport() { - ImportParameters importParameters = new ImportParameters(); - PolicyChangeResponse result = null; - - importParameters.setFilePath("C:\\Workspaces\\models\\TestingModel\\ControllerServiceSampleSdnlServiceInstance-v0.1.0-SNAPSHOT.zip"); - importParameters.setServiceName("ControllerServiceSampleSdnlServiceInstance"); - - importParameters.setRequestID(UUID.randomUUID()); - importParameters.setServiceType(IMPORT_TYPE.MICROSERVICE); - importParameters.setVersion("1607-2"); - - - try { - - Mockito.when(mockPolicyEngine.policyEngineImport(importParameters)).thenReturn(response); - result = mockPolicyEngine.policyEngineImport(importParameters); - - } catch (Exception e) { - logger.warn(e.getMessage()); - } - - assertEquals(result, response); - } - - private static JsonObject buildJSON(String jsonString) { - JsonObject json = null;; - if (jsonString != null) { - StringReader in = null; - - in = new StringReader(jsonString); - - JsonReader jsonReader = Json.createReader(in); - json = jsonReader.readObject(); - } - - return json; - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEngineTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEngineTest.java deleted file mode 100644 index c36a921d4..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEngineTest.java +++ /dev/null @@ -1,170 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -import org.junit.Test; -import org.openecomp.policy.api.NotificationScheme; -import org.openecomp.policy.api.PolicyEngine; -import org.openecomp.policy.api.PolicyEngineException; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -public class PolicyEngineTest { - - private static final Logger logger = FlexLogger.getLogger(PolicyEngineTest.class); - private PolicyEngine policyEngine = null; - private String filePath = null; - - @Test - public void testPolicyEngineForFail() { - filePath = null; - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNull(policyEngine); - // Test even for this case. - filePath = "NotNull"; - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNull(policyEngine); - } - - @Test - public void testPolicyEngineforPropertyFileError() { - filePath = "Test/config_error.property"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNull(policyEngine); - } - - @Test - public void testPolicyEngineforPDPURLError() { - String filePath = "Test/config_fail.properties"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNull(policyEngine); - } - - @Test - public void testPolicyEngineForPass() { - String filePath = "Test/config_pass.properties"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNotNull(policyEngine); - } - - @Test - public void testPolicyEngineForUEBPass() { - String filePath = "Test/config_UEB_pass.properties"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNotNull(policyEngine); - } - - - @Test - public void testPolicyEngineForUEBBadType() { - String filePath = "Test/config_UEB_bad_type.properties"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNotNull(policyEngine); - } - - @Test - public void testPolicyEngineForUEBBadServerType() { - String filePath = "Test/config_UEB_badservers.properties"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNotNull(policyEngine); - } - - @Test - public void testPolicyEngineNotficationAutoUEB() { - String filePath = "Test/config_UEB_pass.properties"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - policyEngine.setScheme(NotificationScheme.AUTO_ALL_NOTIFICATIONS); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNotNull(policyEngine); - } - - @Test - public void testPolicyEngineNotficationAuto() { - String filePath = "Test/config_pass.properties"; - isFileAvailable(filePath); - try { - policyEngine = new PolicyEngine(filePath); - policyEngine.setScheme(NotificationScheme.AUTO_ALL_NOTIFICATIONS); - //policyEngine.getNotification(); - } catch (PolicyEngineException e) { - logger.warn(e.getMessage()); - } - assertNotNull(policyEngine); - } - - public void isFileAvailable(String filePath) { - Path file = Paths.get(filePath); - if (Files.notExists(file)) { - logger.error("File Doesn't Exist "+ file.toString()); - fail("File: " +filePath + " Not found"); - } - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEventExceptionTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEventExceptionTest.java deleted file mode 100644 index fa8d5d1d8..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyEventExceptionTest.java +++ /dev/null @@ -1,183 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.*; -import org.openecomp.policy.api.PolicyEventException; - -import static org.junit.Assert.*; - -/** - * The class PolicyEventExceptionTest contains tests for the class {@link PolicyEventException}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class PolicyEventExceptionTest { - /** - * Run the PolicyEventException() constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPolicyEventException_1() - throws Exception { - - PolicyEventException result = new PolicyEventException(); - - // add additional test code here - assertNotNull(result); - assertEquals(null, result.getCause()); - assertEquals("org.openecomp.policy.api.PolicyEventException", result.toString()); - assertEquals(null, result.getLocalizedMessage()); - assertEquals(null, result.getMessage()); - } - - /** - * Run the PolicyEventException(String) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPolicyEventException_2() - throws Exception { - String message = ""; - - PolicyEventException result = new PolicyEventException(message); - - // add additional test code here - assertNotNull(result); - assertEquals(null, result.getCause()); - assertEquals("org.openecomp.policy.api.PolicyEventException: ", result.toString()); - assertEquals("", result.getLocalizedMessage()); - assertEquals("", result.getMessage()); - } - - /** - * Run the PolicyEventException(Throwable) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPolicyEventException_3() - throws Exception { - Throwable cause = new Throwable(); - - PolicyEventException result = new PolicyEventException(cause); - - // add additional test code here - assertNotNull(result); - assertEquals("org.openecomp.policy.api.PolicyEventException: java.lang.Throwable", result.toString()); - assertEquals("java.lang.Throwable", result.getLocalizedMessage()); - assertEquals("java.lang.Throwable", result.getMessage()); - } - - /** - * Run the PolicyEventException(String,Throwable) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPolicyEventException_4() - throws Exception { - String message = ""; - Throwable cause = new Throwable(); - - PolicyEventException result = new PolicyEventException(message, cause); - - // add additional test code here - assertNotNull(result); - assertEquals("org.openecomp.policy.api.PolicyEventException: ", result.toString()); - assertEquals("", result.getLocalizedMessage()); - assertEquals("", result.getMessage()); - } - - /** - * Run the PolicyEventException(String,Throwable,boolean,boolean) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPolicyEventException_5() - throws Exception { - String message = ""; - Throwable cause = new Throwable(); - boolean enableSuppression = true; - boolean writableStackTrace = true; - - PolicyEventException result = new PolicyEventException(message, cause, enableSuppression, writableStackTrace); - - // add additional test code here - assertNotNull(result); - assertEquals("org.openecomp.policy.api.PolicyEventException: ", result.toString()); - assertEquals("", result.getLocalizedMessage()); - assertEquals("", result.getMessage()); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PolicyEventExceptionTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyParametersTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyParametersTest.java deleted file mode 100644 index eeb973b90..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyParametersTest.java +++ /dev/null @@ -1,1409 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import java.util.Hashtable; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.openecomp.policy.api.AttributeType; -import org.openecomp.policy.api.PolicyClass; -import org.openecomp.policy.api.PolicyConfigType; -import org.openecomp.policy.api.PolicyParameters; -import org.openecomp.policy.api.PolicyType; - -/** - * The class PolicyParametersTest contains tests for the class {@link PolicyParameters}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class PolicyParametersTest { - /** - * Run the String getActionAttribute() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetActionAttribute_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - String result = fixture.getActionAttribute(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getActionPerformer() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetActionPerformer_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - String result = fixture.getActionPerformer(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the Map> getAttributes() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetAttributes_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - Map> result = fixture.getAttributes(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the String getConfigBody() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetConfigBody_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - String result = fixture.getConfigBody(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the PolicyType getConfigBodyType() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetConfigBodyType_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - PolicyType result = fixture.getConfigBodyType(); - - // add additional test code here - assertNotNull(result); - assertEquals("json", result.toString()); - assertEquals("JSON", result.name()); - assertEquals(1, result.ordinal()); - } - - /** - * Run the String getConfigName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetConfigName_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - String result = fixture.getConfigName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the List getDynamicRuleAlgorithmField1() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetDynamicRuleAlgorithmField1_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - List result = fixture.getDynamicRuleAlgorithmField1(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the List getDynamicRuleAlgorithmField2() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetDynamicRuleAlgorithmField2_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - List result = fixture.getDynamicRuleAlgorithmField2(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the List getDynamicRuleAlgorithmFunctions() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetDynamicRuleAlgorithmFunctions_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - List result = fixture.getDynamicRuleAlgorithmFunctions(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the List getDynamicRuleAlgorithmLabels() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetDynamicRuleAlgorithmLabels_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - List result = fixture.getDynamicRuleAlgorithmLabels(); - - // add additional test code here - assertNotNull(result); - assertEquals(0, result.size()); - } - - /** - * Run the String getEcompName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetEcompName_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - String result = fixture.getEcompName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the PolicyClass getPolicyClass() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetPolicyClass_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - PolicyClass result = fixture.getPolicyClass(); - - // add additional test code here - assertNotNull(result); - assertEquals("Action", result.toString()); - assertEquals("Action", result.name()); - assertEquals(1, result.ordinal()); - } - - /** - * Run the PolicyConfigType getPolicyConfigType() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetPolicyConfigType_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - PolicyConfigType result = (PolicyConfigType) fixture.getPolicyConfigType(); - - // add additional test code here - assertNotNull(result); - assertEquals("BRMS_Param", result.toString()); - assertEquals("BRMS_PARAM", result.name()); - assertEquals(5, result.ordinal()); - } - - /** - * Run the String getPolicyDescription() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetPolicyDescription_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - String result = fixture.getPolicyDescription(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetPolicyName_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getPriority() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetPriority_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - String result = fixture.getPriority(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the UUID getRequestID() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetRequestID_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.fromString("878d319c-2799-4684-b480-99f40e1042b2")); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - - UUID result = fixture.getRequestID(); - - // add additional test code here - assertNotNull(result); - assertEquals("878d319c-2799-4684-b480-99f40e1042b2", result.toString()); - assertEquals(4, result.version()); - assertEquals(2, result.variant()); - assertEquals(-5440179076376542542L, result.getLeastSignificantBits()); - assertEquals(-8679226360124062076L, result.getMostSignificantBits()); - } - - /** - * Run the void setActionAttribute(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetActionAttribute_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - String actionAttribute = ""; - - fixture.setActionAttribute(actionAttribute); - - // add additional test code here - } - - /** - * Run the void setActionPerformer(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetActionPerformer_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - String actionPerformer = ""; - - fixture.setActionPerformer(actionPerformer); - - // add additional test code here - } - - /** - * Run the void setAttributes(Map>) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetAttributes_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - Map> attributes = new Hashtable>(); - - fixture.setAttributes(attributes); - - // add additional test code here - } - - /** - * Run the void setConfigBody(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetConfigBody_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - String configBody = ""; - - fixture.setConfigBody(configBody); - - // add additional test code here - } - - /** - * Run the void setConfigBodyType(PolicyType) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetConfigBodyType_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - PolicyType configBodyType = PolicyType.JSON; - - fixture.setConfigBodyType(configBodyType); - - // add additional test code here - } - - /** - * Run the void setConfigFirewallPolicyParameters(String,String,UUID) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetConfigFirewallPolicyParameters_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - String policyName = ""; - String firewallJson = ""; - UUID requestID = UUID.randomUUID(); - - fixture.setConfigFirewallPolicyParameters(policyName, firewallJson, requestID); - - // add additional test code here - } - - /** - * Run the void setConfigName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetConfigName_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - String configName = ""; - - fixture.setConfigName(configName); - - // add additional test code here - } - - /** - * Run the void setConfigPolicyParameters(PolicyConfigType,String,String,String,String,Map>,PolicyType,String,UUID) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetConfigPolicyParameters_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - PolicyConfigType policyConfigType = PolicyConfigType.BRMS_PARAM; - String policyName = ""; - String policyDescription = ""; - String ecompName = ""; - String configName = ""; - Map> attributes = new Hashtable>(); - PolicyType configBodyType = PolicyType.JSON; - String configBody = ""; - UUID requestID = UUID.randomUUID(); - - fixture.setConfigPolicyParameters(policyConfigType, policyName, policyDescription, ecompName, configName, attributes, configBodyType, configBody, requestID); - - // add additional test code here - } - - /** - * Run the void setDynamicRuleAlgorithmField1(List) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetDynamicRuleAlgorithmField1_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - List dynamicRuleAlgorithmField1 = new LinkedList(); - - fixture.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); - - // add additional test code here - } - - /** - * Run the void setDynamicRuleAlgorithmField2(List) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetDynamicRuleAlgorithmField2_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - List dynamicRuleAlgorithmField2 = new LinkedList(); - - fixture.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); - - // add additional test code here - } - - /** - * Run the void setDynamicRuleAlgorithmFunctions(List) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetDynamicRuleAlgorithmFunctions_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - List dynamicRuleAlgorithmFunctions = new LinkedList(); - - fixture.setDynamicRuleAlgorithmFunctions(dynamicRuleAlgorithmFunctions); - - // add additional test code here - } - - /** - * Run the void setDynamicRuleAlgorithmLabels(List) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetDynamicRuleAlgorithmLabels_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - List dynamicRuleAlgorithmLabels = new LinkedList(); - - fixture.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); - - // add additional test code here - } - - /** - * Run the void setEcompName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetEcompName_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - String ecompName = ""; - - fixture.setEcompName(ecompName); - - // add additional test code here - } - - /** - * Run the void setPolicyClass(PolicyClass) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetPolicyClass_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - PolicyClass policyClass = PolicyClass.Action; - - fixture.setPolicyClass(policyClass); - - // add additional test code here - } - - /** - * Run the void setPolicyConfigType(PolicyConfigType) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetPolicyConfigType_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - PolicyConfigType policyConfigType = PolicyConfigType.BRMS_PARAM; - - fixture.setPolicyConfigType(policyConfigType); - - // add additional test code here - } - - /** - * Run the void setPolicyDescription(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetPolicyDescription_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - String policyDescription = ""; - - fixture.setPolicyDescription(policyDescription); - - // add additional test code here - } - - /** - * Run the void setPolicyName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetPolicyName_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - String policyName = ""; - - fixture.setPolicyName(policyName); - - // add additional test code here - } - - /** - * Run the void setPriority(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetPriority_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - String priority = ""; - - fixture.setPriority(priority); - - // add additional test code here - } - - /** - * Run the void setRequestID(UUID) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testSetRequestID_1() - throws Exception { - PolicyParameters fixture = new PolicyParameters(); - fixture.setRequestID(UUID.randomUUID()); - fixture.setActionAttribute(""); - fixture.setAttributes(new Hashtable>()); - fixture.setDynamicRuleAlgorithmLabels(new LinkedList()); - fixture.setPolicyDescription(""); - - fixture.setPolicyConfigType(PolicyConfigType.BRMS_PARAM); - fixture.setDynamicRuleAlgorithmField2(new LinkedList()); - fixture.setPolicyName(""); - fixture.setConfigName(""); - fixture.setDynamicRuleAlgorithmFunctions(new LinkedList()); - fixture.setPolicyClass(PolicyClass.Action); - fixture.setEcompName(""); - fixture.setConfigBodyType(PolicyType.JSON); - fixture.setDynamicRuleAlgorithmField1(new LinkedList()); - fixture.setPriority(""); - fixture.setActionPerformer(""); - fixture.setConfigBody(""); - UUID requestID = UUID.randomUUID(); - - fixture.setRequestID(requestID); - - // add additional test code here - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PolicyParametersTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyResponseStatusTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyResponseStatusTest.java deleted file mode 100644 index 5841571bd..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyResponseStatusTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.*; -import org.openecomp.policy.api.PolicyResponseStatus; - -import static org.junit.Assert.*; - -/** - * The class PolicyResponseStatusTest contains tests for the class {@link PolicyResponseStatus}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class PolicyResponseStatusTest { - /** - * Run the PolicyResponseStatus getStatus(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetStatus_1() - throws Exception { - String responseStatus = ""; - - PolicyResponseStatus result = PolicyResponseStatus.getStatus(responseStatus); - - // add additional test code here - assertNotNull(result); - assertEquals("no_action", result.toString()); - assertEquals("NO_ACTION_REQUIRED", result.name()); - assertEquals(0, result.ordinal()); - } - - /** - * Run the PolicyResponseStatus getStatus(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetStatus_2() - throws Exception { - String responseStatus = ""; - - PolicyResponseStatus result = PolicyResponseStatus.getStatus(responseStatus); - - // add additional test code here - assertNotNull(result); - assertEquals("no_action", result.toString()); - assertEquals("NO_ACTION_REQUIRED", result.name()); - assertEquals(0, result.ordinal()); - } - - /** - * Run the PolicyResponseStatus getStatus(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testGetStatus_3() - throws Exception { - String responseStatus = ""; - - PolicyResponseStatus result = PolicyResponseStatus.getStatus(responseStatus); - - // add additional test code here - assertNotNull(result); - assertEquals("no_action", result.toString()); - assertEquals("NO_ACTION_REQUIRED", result.name()); - assertEquals(0, result.ordinal()); - } - - /** - * Run the String toString() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testToString_1() - throws Exception { - PolicyResponseStatus fixture = PolicyResponseStatus.ACTION_ADVISED; - - String result = fixture.toString(); - - // add additional test code here - assertEquals("action_advised", result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PolicyResponseStatusTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyResponseTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyResponseTest.java deleted file mode 100644 index ec6ac09f0..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyResponseTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.After; -import org.junit.Before; -import org.openecomp.policy.api.PolicyResponse; - -/** - * The class PolicyResponseTest contains tests for the class {@link PolicyResponse}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class PolicyResponseTest { - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PolicyResponseTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyTypeTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyTypeTest.java deleted file mode 100644 index 5b31e857b..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PolicyTypeTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.*; -import org.openecomp.policy.api.PolicyType; - -import static org.junit.Assert.*; - -/** - * The class PolicyTypeTest contains tests for the class {@link PolicyType}. - * - * @generatedBy CodePro at 6/1/16 1:41 PM - * @version $Revision: 1.0 $ - */ -public class PolicyTypeTest { - /** - * Run the String toString() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Test - public void testToString_1() - throws Exception { - PolicyType fixture = PolicyType.JSON; - - String result = fixture.toString(); - - // add additional test code here - assertEquals("json", result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:41 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PolicyTypeTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PushPolicyParametersTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PushPolicyParametersTest.java deleted file mode 100644 index ef005f1f4..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/PushPolicyParametersTest.java +++ /dev/null @@ -1,269 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import java.util.UUID; - -import org.junit.*; -import org.openecomp.policy.api.PushPolicyParameters; - -import static org.junit.Assert.*; - -/** - * The class PushPolicyParametersTest contains tests for the class {@link PushPolicyParameters}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class PushPolicyParametersTest { - /** - * Run the PushPolicyParameters() constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPushPolicyParameters_1() - throws Exception { - - PushPolicyParameters result = new PushPolicyParameters(); - - // add additional test code here - assertNotNull(result); - assertEquals(null, result.getPolicyName()); - assertEquals(null, result.getRequestID()); - assertEquals(null, result.getPolicyType()); - assertEquals(null, result.getPdpGroup()); - } - - /** - * Run the PushPolicyParameters(String,String,String,UUID) constructor test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testPushPolicyParameters_2() - throws Exception { - String policyName = ""; - String policyType = ""; - String pdpGroup = ""; - UUID requestID = UUID.randomUUID(); - - PushPolicyParameters result = new PushPolicyParameters(policyName, policyType, pdpGroup, requestID); - - // add additional test code here - assertNotNull(result); - assertEquals("", result.getPolicyName()); - assertEquals("", result.getPolicyType()); - assertEquals("", result.getPdpGroup()); - } - - /** - * Run the String getPdpGroup() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPdpGroup_1() - throws Exception { - PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.randomUUID()); - - String result = fixture.getPdpGroup(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getPolicyName() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyName_1() - throws Exception { - PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.randomUUID()); - - String result = fixture.getPolicyName(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the String getPolicyType() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetPolicyType_1() - throws Exception { - PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.randomUUID()); - - String result = fixture.getPolicyType(); - - // add additional test code here - assertEquals("", result); - } - - /** - * Run the UUID getRequestID() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testGetRequestID() - throws Exception { - PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.fromString("d1dbaac1-0944-4f07-9ce7-733c697537ea")); - - UUID result = fixture.getRequestID(); - - // add additional test code here - assertNotNull(result); - assertEquals("d1dbaac1-0944-4f07-9ce7-733c697537ea", result.toString()); - assertEquals(4, result.version()); - assertEquals(2, result.variant()); - assertEquals(-7140611980868110358L, result.getLeastSignificantBits()); - assertEquals(-3324876153822097657L, result.getMostSignificantBits()); - } - - /** - * Run the void setPdpGroup(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPdpGroup_1() - throws Exception { - PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.randomUUID()); - String pdpGroup = ""; - - fixture.setPdpGroup(pdpGroup); - - // add additional test code here - } - - /** - * Run the void setPolicyName(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyName_1() - throws Exception { - PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.randomUUID()); - String policyName = ""; - - fixture.setPolicyName(policyName); - - // add additional test code here - } - - /** - * Run the void setPolicyType(String) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetPolicyType_1() - throws Exception { - PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.randomUUID()); - String policyType = ""; - - fixture.setPolicyType(policyType); - - // add additional test code here - } - - /** - * Run the void setRequestID(UUID) method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Test - public void testSetRequestID_1() - throws Exception { - PushPolicyParameters fixture = new PushPolicyParameters("", "", "", UUID.randomUUID()); - UUID requestID = UUID.randomUUID(); - - fixture.setRequestID(requestID); - - // add additional test code here - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(PushPolicyParametersTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/RemovedPolicyTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/RemovedPolicyTest.java deleted file mode 100644 index ef77e6d5f..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/RemovedPolicyTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.After; -import org.junit.Before; -import org.openecomp.policy.api.RemovedPolicy; - -/** - * The class RemovedPolicyTest contains tests for the class {@link RemovedPolicy}. - * - * @generatedBy CodePro at 6/1/16 1:40 PM - * @version $Revision: 1.0 $ - */ -public class RemovedPolicyTest { - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:40 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(RemovedPolicyTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/SendEventTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/SendEventTest.java deleted file mode 100644 index 5757f8915..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/SendEventTest.java +++ /dev/null @@ -1,155 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import org.junit.Before; -import org.openecomp.policy.api.PolicyEngine; -import org.openecomp.policy.api.PolicyEngineException; -import org.openecomp.policy.api.PolicyEventException; -import org.openecomp.policy.api.PolicyResponse; -import org.openecomp.policy.api.PolicyResponseStatus; -import org.openecomp.policy.common.logging.flexlogger.FlexLogger; -import org.openecomp.policy.common.logging.flexlogger.Logger; - -public class SendEventTest { - - private PolicyEngine policyEngine = null; - private Map eventAttributes = new HashMap(); - private Collection policyResponse = null; - private static final Logger logger = FlexLogger.getLogger(SendEventTest.class); - @Before - public void setUp() { - try { - policyEngine = new PolicyEngine("Test/config_pass.properties"); - } catch (PolicyEngineException e) { - logger.error(e.getMessage()); - fail("PolicyEngine Instantiation Error" + e); - } - logger.info("Loaded.. PolicyEngine"); - } - - //@Test - @SuppressWarnings("deprecation") - public void testSendEventFail() { - eventAttributes = null; - try { - policyResponse = policyEngine.sendEvent(eventAttributes); - } catch (PolicyEventException e) { - logger.warn(e.getMessage()); - } - assertNull(policyResponse); - } - - //@Test - @SuppressWarnings("deprecation") - public void testSendEventFailNull() { - eventAttributes.put("", ""); - try { - policyResponse = policyEngine.sendEvent(eventAttributes); - } catch (PolicyEventException e) { - logger.warn(e.getMessage()); - } - assertNull(policyResponse); - } - - // deprecated Test. - /*@Test - public void testSendEventFailAttribute() { - eventAttributes.put("Fail.key", "Value"); - try { - policyResponse = policyEngine.sendEvent(eventAttributes); - } catch (PolicyEventException e) { - logger.warn(e.getMessage()); - } - assertNull(policyResponse.getPolicyResponseMessage()); - }*/ - - //@Test - @SuppressWarnings("deprecation") - public void testSendEventNotValid() { - eventAttributes.put("Action.fail", "Value"); - try { - policyResponse = policyEngine.sendEvent(eventAttributes); - } catch (PolicyEventException e) { - logger.warn(e.getMessage()); - } - for(PolicyResponse policyResponse: this.policyResponse){ - logger.info(policyResponse.getPolicyResponseMessage() + " , " + policyResponse.getPolicyResponseStatus()); - assertNotNull(policyResponse); - assertEquals(PolicyResponseStatus.NO_ACTION_REQUIRED, policyResponse.getPolicyResponseStatus()); - assertNotNull(policyResponse.getPolicyResponseMessage()); - assertNotNull(policyResponse.getRequestAttributes()); - assertNull(policyResponse.getActionTaken()); - assertNull(policyResponse.getActionAdvised()); - } - } - - //@Test - @SuppressWarnings("deprecation") - public void testSendEventActionAdvised() { - eventAttributes.put("Key", "Value"); - eventAttributes.put("cpu", "80"); - try { - policyResponse = policyEngine.sendEvent(eventAttributes); - } catch (PolicyEventException e) { - logger.warn(e.getMessage()); - } - for(PolicyResponse policyResponse: this.policyResponse){ - logger.info(policyResponse.getPolicyResponseMessage() + " , " + policyResponse.getPolicyResponseStatus()); - assertNotNull(policyResponse); - assertEquals(PolicyResponseStatus.ACTION_ADVISED, policyResponse.getPolicyResponseStatus()); - assertNotNull(policyResponse.getPolicyResponseMessage()); - assertNotNull(policyResponse.getRequestAttributes()); - assertNull(policyResponse.getActionTaken()); - assertNotNull(policyResponse.getActionAdvised()); - } - } - - //@Test - @SuppressWarnings("deprecation") - public void testSendEventActionTaken() { - eventAttributes.put("Key", "Value"); - eventAttributes.put("cpu", "91"); - try { - policyResponse = policyEngine.sendEvent(eventAttributes); - } catch (PolicyEventException e) { - logger.warn(e.getMessage()); - } - for(PolicyResponse policyResponse: this.policyResponse){ - logger.info(policyResponse.getPolicyResponseMessage() + " , " + policyResponse.getPolicyResponseStatus()); - assertNotNull(policyResponse); - assertEquals(PolicyResponseStatus.ACTION_TAKEN, policyResponse.getPolicyResponseStatus()); - assertNotNull(policyResponse.getPolicyResponseMessage()); - assertNotNull(policyResponse.getRequestAttributes()); - assertNotNull(policyResponse.getActionTaken()); - assertNull(policyResponse.getActionAdvised()); - } - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/TestRunner.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/TestRunner.java deleted file mode 100644 index 69cbd834e..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/TestRunner.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.runner.JUnitCore; -import org.junit.runner.Result; -import org.junit.runner.notification.Failure; - -public class TestRunner { - public static void main(String[] args) { - Result result = JUnitCore.runClasses(PolicyEngineTest.class); - for(Failure failure: result.getFailures()) { - System.out.println("Failed Test: " + failure.toString()); - } - Result results = null; - if(result.wasSuccessful()) { - System.out.println("API Methods are being Tested.. "); - results = JUnitCore.runClasses(GetConfigByPolicyNameTest.class, GetConfigStringTest.class,GetConfigStringStringTest.class,GetConfigStringStringMapTest.class,SendEventTest.class); - for(Failure failure: results.getFailures()) { - System.out.println("Failed Test: " + failure.toString()); - } - System.out.println("Test Results.. "); - System.out.println("Stats: \nRun Time: " + (results.getRunTime()+result.getRunTime()) + "\nTotal Tests:" + results.getRunCount()+ result.getRunCount() - + "\nFailures: " + results.getFailureCount()+ result.getFailureCount()); - System.exit(1); - } - System.out.println("Test Failed.."); - System.out.println("Stats: \nRun Time: " + result.getRunTime() + "\nTests:" + result.getRunCount() - + "\nFailures: " + result.getFailureCount()); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/UpdateTypeTest.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/UpdateTypeTest.java deleted file mode 100644 index 909a05f0e..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/UpdateTypeTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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.test; - -import org.junit.*; -import org.openecomp.policy.api.UpdateType; - -import static org.junit.Assert.*; - -/** - * The class UpdateTypeTest contains tests for the class {@link UpdateType}. - * - * @generatedBy CodePro at 6/1/16 1:39 PM - * @version $Revision: 1.0 $ - */ -public class UpdateTypeTest { - /** - * Run the String toString() method test. - * - * @throws Exception - * - * @generatedBy CodePro at 6/1/16 1:39 PM - */ - @Test - public void testToString_1() - throws Exception { - UpdateType fixture = UpdateType.NEW; - - String result = fixture.toString(); - - // add additional test code here - assertEquals("new", result); - } - - /** - * Perform pre-test initialization. - * - * @throws Exception - * if the initialization fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:39 PM - */ - @Before - public void setUp() - throws Exception { - // add additional set up code here - } - - /** - * Perform post-test clean-up. - * - * @throws Exception - * if the clean-up fails for some reason - * - * @generatedBy CodePro at 6/1/16 1:39 PM - */ - @After - public void tearDown() - throws Exception { - // Add additional tear down code here - } - - /** - * Launch the test. - * - * @param args the command line arguments - * - * @generatedBy CodePro at 6/1/16 1:39 PM - */ - public static void main(String[] args) { - new org.junit.runner.JUnitCore().run(UpdateTypeTest.class); - } -} diff --git a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/package-info.java b/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/package-info.java deleted file mode 100644 index e678c4be2..000000000 --- a/PolicyEngineAPI/src/test/java/org/openecomp/policy/test/package-info.java +++ /dev/null @@ -1,24 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * PolicyEngineAPI - * ================================================================================ - * 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========================================================= - */ - -/** - * API JUNIT TestCases. - */ -package org.openecomp.policy.test; diff --git a/PolicyEngineClient/input.testCases b/PolicyEngineClient/input.testCases index edb374001..a170fbef4 100644 --- a/PolicyEngineClient/input.testCases +++ b/PolicyEngineClient/input.testCases @@ -4,7 +4,7 @@ "testCaseDescription": "test GetConfig String Not valid", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "fail", + "ONAPName": "fail", "ConfigName": null, "configAttributes": null, "expectedResult":[ @@ -16,7 +16,7 @@ "testCaseDescription": "test Get ConfigString Valid JSON", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "JSON", + "ONAPName": "JSON", "ConfigName": null, "configAttributes": null, "expectedResult":[ @@ -28,7 +28,7 @@ "testCaseDescription": "test Get ConfigString Valid XML", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "XML", + "ONAPName": "XML", "ConfigName": null, "configAttributes": null, "expectedResult":[ @@ -40,7 +40,7 @@ "testCaseDescription": "test Get ConfigString Valid properties", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "Properties", + "ONAPName": "Properties", "ConfigName": null, "configAttributes": null, "expectedResult":[ @@ -52,7 +52,7 @@ "testCaseDescription": "test Get ConfigString Valid other", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "Other", + "ONAPName": "Other", "ConfigName": null, "configAttributes": null, "expectedResult":[ @@ -64,11 +64,11 @@ "testCaseDescription": "test GetConfig String String Fail", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": null, + "ONAPName": null, "ConfigName": null, "configAttributes": null, "expectedResult":[ - "org.openecomp.policy.api.PolicyConfigException: No eCOMPComponentName given.", + "org.onap.policy.api.PolicyConfigException: No onapComponentName given.", ] }, { @@ -76,11 +76,11 @@ "testCaseDescription": "test GetConfig String String Fail1", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": null, + "ONAPName": null, "ConfigName": null, "configAttributes": null, "expectedResult":[ - "org.openecomp.policy.api.PolicyConfigException: No eCOMPComponentName given." + "org.onap.policy.api.PolicyConfigException: No onapComponentName given." ] }, @@ -89,7 +89,7 @@ "testCaseDescription": "test GetConfig String String Valid ", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "fail", + "ONAPName": "fail", "ConfigName": "fail", "configAttributes": null, "expectedResult":[ @@ -101,7 +101,7 @@ "testCaseDescription": "test GetConfig String String Valid JSON", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "JSON", + "ONAPName": "JSON", "ConfigName": "JSONconfig", "configAttributes": null, "expectedResult":[ @@ -113,7 +113,7 @@ "testCaseDescription": "test GetConfig String String Valid XML", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "XML", + "ONAPName": "XML", "ConfigName": "XMLconfig", "configAttributes": null, "expectedResult":[ @@ -125,7 +125,7 @@ "testCaseDescription": "test GetConfig String String Valid properties", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "Properties", + "ONAPName": "Properties", "ConfigName": "PropConfig", "configAttributes": null, "expectedResult":[ @@ -137,7 +137,7 @@ "testCaseDescription": "test GetConfig String String Valid other", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "Other", + "ONAPName": "Other", "ConfigName": "OtherConfig", "configAttributes": null, "expectedResult":[ @@ -149,11 +149,11 @@ "testCaseDescription": "test GetConfig String String String fail", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": null, + "ONAPName": null, "ConfigName": null, "configAttributes": null, "expectedResult":[ - "org.openecomp.policy.api.PolicyConfigException: No eCOMPComponentName given." + "org.onap.policy.api.PolicyConfigException: No onapComponentName given." ] }, { @@ -161,7 +161,7 @@ "testCaseDescription": "test GetConfig String String String fail1", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": null, + "ONAPName": null, "ConfigName": "testFail", "configAttributes": [ { @@ -170,7 +170,7 @@ }, ], "expectedResult":[ - "org.openecomp.policy.api.PolicyConfigException: No eCOMPComponentName given.", + "org.onap.policy.api.PolicyConfigException: No onapComponentName given.", ] }, { @@ -178,7 +178,7 @@ "testCaseDescription": "test GetConfig String String String fail2", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "TestFail", + "ONAPName": "TestFail", "ConfigName": null, "configAttributes": [ { @@ -195,7 +195,7 @@ "testCaseDescription": "test GetConfig String String String fail3", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "TestFail", + "ONAPName": "TestFail", "ConfigName": "configFail", "configAttributes": null, "expectedResult":[ @@ -207,7 +207,7 @@ "testCaseDescription": "test GetConfig String String String fail4", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "TestFail", + "ONAPName": "TestFail", "ConfigName": "configFail", "configAttributes": [ { @@ -216,7 +216,7 @@ }, ], "expectedResult":[ - "org.openecomp.policy.api.PolicyConfigException: Cannot have an empty Key", + "org.onap.policy.api.PolicyConfigException: Cannot have an empty Key", ] }, @@ -225,7 +225,7 @@ "testCaseDescription": "test GetConfig String String String Valid", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "TestFail", + "ONAPName": "TestFail", "ConfigName": "configFail", "configAttributes": [ { @@ -242,7 +242,7 @@ "testCaseDescription": "test GetConfig String String String Valid JSON", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "JSON", + "ONAPName": "JSON", "ConfigName": "JSONconfig", "configAttributes": [ { @@ -267,7 +267,7 @@ "testCaseDescription": "test GetConfig String String String Valid XML", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "XML", + "ONAPName": "XML", "ConfigName": "XMLconfig", "configAttributes": [ { @@ -292,7 +292,7 @@ "testCaseDescription": "test GetConfig String String String Valid properties", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "Properties", + "ONAPName": "Properties", "ConfigName": "PropConfig", "configAttributes": [ { @@ -317,7 +317,7 @@ "testCaseDescription": "test GetConfig String String String Valid other", "testFor": "getConfig", "PDP_URLConfigFile": "config.properties" - "ECOMPName": "Other", + "ONAPName": "Other", "ConfigName": "OtherConfig", "configAttributes": [ { @@ -344,7 +344,7 @@ "PDP_URLConfigFile": "config.properties", "eventAttributes": null, "expectedResult":[ - "org.openecomp.policy.api.PolicyEventException: No EventAttributes Given.", + "org.onap.policy.api.PolicyEventException: No EventAttributes Given.", ] }, { @@ -359,7 +359,7 @@ }, ], "expectedResult":[ - "org.openecomp.policy.api.PolicyEventException: Cannot have an empty Key", + "org.onap.policy.api.PolicyEventException: Cannot have an empty Key", ] }, diff --git a/PolicyEngineClient/pom.xml b/PolicyEngineClient/pom.xml index fb6267c2a..04be78565 100644 --- a/PolicyEngineClient/pom.xml +++ b/PolicyEngineClient/pom.xml @@ -1,7 +1,7 @@ - diff --git a/pom.xml b/pom.xml index f57ff264c..b8dd4c74e 100644 --- a/pom.xml +++ b/pom.xml @@ -2,13 +2,13 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 - org.openecomp.policy.engine + org.onap.policy.engine PolicyEngineSuite 1.1.0-SNAPSHOT pom Policy Engine - Policy Engine Suite - The ECOMP Policy Engine main pom + The ONAP Policy Engine main pom 1.8 @@ -39,36 +39,36 @@ PolicyEngineUtils - ECOMP-XACML - ECOMP-REST - ECOMP-ASDC - ECOMP-ControlloopPolicy + ONAP-XACML + ONAP-REST + ONAP-ASDC + ONAP-ControlloopPolicy PolicyEngineAPI - ECOMP-PDP - ECOMP-PDP-REST - ECOMP-PAP-REST + ONAP-PDP + ONAP-PDP-REST + ONAP-PAP-REST LogParser PolicyEngineClient BRMSGateway POLICY-SDK-APP - ECOMP-SDK-APP + ONAP-SDK-APP packages ecomp-snapshots - OpenECOMP Snapshot Repository + ONAP Snapshot Repository ${nexusproxy}/${snapshots.path} ecomp-releases - OpenECOMP Release Repository + ONAP Release Repository ${nexusproxy}/${releases.path}/ ecomp-staging - OpenECOMP Staging Repository + ONAP Staging Repository ${nexusproxy}/${staging.path} @@ -76,12 +76,12 @@ ecomp-releases - OpenECOMP Release Repository + ONAP Release Repository ${nexusproxy}/${releases.path} ecomp-snapshots - OpenECOMP Snapshot Repository + ONAP Snapshot Repository ${nexusproxy}/${snapshots.path} @@ -136,7 +136,7 @@ ${nexusproxy} 176c31dfe190a - ecomp-staging + onap-staging @@ -252,7 +252,7 @@ true - org.openecomp.* + org.onap.* diff --git a/project-configs/maven/conf/settings.xml b/project-configs/maven/conf/settings.xml index 918117d7b..226451b4f 100644 --- a/project-configs/maven/conf/settings.xml +++ b/project-configs/maven/conf/settings.xml @@ -1,7 +1,7 @@